var De = Object.defineProperty
  , Ne = Object.defineProperties;
var we = Object.getOwnPropertyDescriptors;
var be = Object.getOwnPropertySymbols;
var Me = Object.prototype.hasOwnProperty
  , Ie = Object.prototype.propertyIsEnumerable;
var Se = (i,e,t)=>e in i ? De(i, e, {
    enumerable: !0,
    configurable: !0,
    writable: !0,
    value: t
}) : i[e] = t
  , oe = (i,e)=>{
    for (var t in e || (e = {}))
        Me.call(e, t) && Se(i, t, e[t]);
    if (be)
        for (var t of be(e))
            Ie.call(e, t) && Se(i, t, e[t]);
    return i
}
  , le = (i,e)=>Ne(i, we(e));
var Oe = (i,e)=>{
    var t = {};
    for (var r in i)
        Me.call(i, r) && e.indexOf(r) < 0 && (t[r] = i[r]);
    if (i != null && be)
        for (var r of be(i))
            e.indexOf(r) < 0 && Ie.call(i, r) && (t[r] = i[r]);
    return t
}
;
var E = (i,e,t)=>(Se(i, typeof e != "symbol" ? e + "" : e, t),
t);
import {_ as __extends, a as __awaiter, b as __generator, c as __assign, d as __decorate, D as Dexie$1, e as commonjsGlobal, f as commonjsRequire, n as nipplejs, j as jsxRuntime, r as react, R as ReactDOM, g as React} from "./vendor.03350293.js";
const p = function() {
    const e = document.createElement("link").relList;
    if (e && e.supports && e.supports("modulepreload"))
        return;
    for (const n of document.querySelectorAll('link[rel="modulepreload"]'))
        r(n);
    new MutationObserver(n=>{
        for (const o of n)
            if (o.type === "childList")
                for (const a of o.addedNodes)
                    a.tagName === "LINK" && a.rel === "modulepreload" && r(a)
    }
    ).observe(document, {
        childList: !0,
        subtree: !0
    });
    function t(n) {
        const o = {};
        return n.integrity && (o.integrity = n.integrity),
        n.referrerpolicy && (o.referrerPolicy = n.referrerpolicy),
        n.crossorigin === "use-credentials" ? o.credentials = "include" : n.crossorigin === "anonymous" ? o.credentials = "omit" : o.credentials = "same-origin",
        o
    }
    function r(n) {
        if (n.ep)
            return;
        n.ep = !0;
        const o = t(n);
        fetch(n.href, o)
    }
};
p();
Promise.prototype._timeout = function(i, e) {
    let t;
    return new Promise((r,n)=>(t = window.setTimeout(()=>{
        n(e)
    }
    , i),
    this.then(o=>{
        clearTimeout(t),
        r(o)
    }
    , o=>{
        clearTimeout(t),
        n(o)
    }
    )))
}
;
function clear() {
    const i = console.log;
    console.log = function(...e) {
        typeof e[0] == "string" && e[0].indexOf("Babylon.js") == 0 || i(...e)
    }
}
clear();
var EventState = function() {
    function i(e, t, r, n) {
        t === void 0 && (t = !1),
        this.initialize(e, t, r, n)
    }
    return i.prototype.initialize = function(e, t, r, n) {
        return t === void 0 && (t = !1),
        this.mask = e,
        this.skipNextObservers = t,
        this.target = r,
        this.currentTarget = n,
        this
    }
    ,
    i
}()
  , Observer = function() {
    function i(e, t, r) {
        r === void 0 && (r = null),
        this.callback = e,
        this.mask = t,
        this.scope = r,
        this._willBeUnregistered = !1,
        this.unregisterOnNextCall = !1
    }
    return i
}()
  , Observable = function() {
    function i(e) {
        this._observers = new Array,
        this._eventState = new EventState(0),
        e && (this._onObserverAdded = e)
    }
    return i.FromPromise = function(e, t) {
        var r = new i;
        return e.then(function(n) {
            r.notifyObservers(n)
        }).catch(function(n) {
            if (t)
                t.notifyObservers(n);
            else
                throw n
        }),
        r
    }
    ,
    Object.defineProperty(i.prototype, "observers", {
        get: function() {
            return this._observers
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.add = function(e, t, r, n, o) {
        if (t === void 0 && (t = -1),
        r === void 0 && (r = !1),
        n === void 0 && (n = null),
        o === void 0 && (o = !1),
        !e)
            return null;
        var a = new Observer(e,t,n);
        return a.unregisterOnNextCall = o,
        r ? this._observers.unshift(a) : this._observers.push(a),
        this._onObserverAdded && this._onObserverAdded(a),
        a
    }
    ,
    i.prototype.addOnce = function(e) {
        return this.add(e, void 0, void 0, void 0, !0)
    }
    ,
    i.prototype.remove = function(e) {
        if (!e)
            return !1;
        var t = this._observers.indexOf(e);
        return t !== -1 ? (this._deferUnregister(e),
        !0) : !1
    }
    ,
    i.prototype.removeCallback = function(e, t) {
        for (var r = 0; r < this._observers.length; r++) {
            var n = this._observers[r];
            if (!n._willBeUnregistered && n.callback === e && (!t || t === n.scope))
                return this._deferUnregister(n),
                !0
        }
        return !1
    }
    ,
    i.prototype._deferUnregister = function(e) {
        var t = this;
        e.unregisterOnNextCall = !1,
        e._willBeUnregistered = !0,
        setTimeout(function() {
            t._remove(e)
        }, 0)
    }
    ,
    i.prototype._remove = function(e) {
        if (!e)
            return !1;
        var t = this._observers.indexOf(e);
        return t !== -1 ? (this._observers.splice(t, 1),
        !0) : !1
    }
    ,
    i.prototype.makeObserverTopPriority = function(e) {
        this._remove(e),
        this._observers.unshift(e)
    }
    ,
    i.prototype.makeObserverBottomPriority = function(e) {
        this._remove(e),
        this._observers.push(e)
    }
    ,
    i.prototype.notifyObservers = function(e, t, r, n, o) {
        if (t === void 0 && (t = -1),
        !this._observers.length)
            return !0;
        var a = this._eventState;
        a.mask = t,
        a.target = r,
        a.currentTarget = n,
        a.skipNextObservers = !1,
        a.lastReturnValue = e,
        a.userInfo = o;
        for (var s = 0, l = this._observers; s < l.length; s++) {
            var u = l[s];
            if (!u._willBeUnregistered && (u.mask & t && (u.scope ? a.lastReturnValue = u.callback.apply(u.scope, [e, a]) : a.lastReturnValue = u.callback(e, a),
            u.unregisterOnNextCall && this._deferUnregister(u)),
            a.skipNextObservers))
                return !1
        }
        return !0
    }
    ,
    i.prototype.notifyObserversWithPromise = function(e, t, r, n, o) {
        var a = this;
        t === void 0 && (t = -1);
        var s = Promise.resolve(e);
        if (!this._observers.length)
            return s;
        var l = this._eventState;
        return l.mask = t,
        l.target = r,
        l.currentTarget = n,
        l.skipNextObservers = !1,
        l.userInfo = o,
        this._observers.forEach(function(u) {
            l.skipNextObservers || u._willBeUnregistered || u.mask & t && (u.scope ? s = s.then(function(c) {
                return l.lastReturnValue = c,
                u.callback.apply(u.scope, [e, l])
            }) : s = s.then(function(c) {
                return l.lastReturnValue = c,
                u.callback(e, l)
            }),
            u.unregisterOnNextCall && a._deferUnregister(u))
        }),
        s.then(function() {
            return e
        })
    }
    ,
    i.prototype.notifyObserver = function(e, t, r) {
        if (r === void 0 && (r = -1),
        !e._willBeUnregistered) {
            var n = this._eventState;
            n.mask = r,
            n.skipNextObservers = !1,
            e.callback(t, n),
            e.unregisterOnNextCall && this._deferUnregister(e)
        }
    }
    ,
    i.prototype.hasObservers = function() {
        return this._observers.length > 0
    }
    ,
    i.prototype.clear = function() {
        this._observers = new Array,
        this._onObserverAdded = null
    }
    ,
    i.prototype.clone = function() {
        var e = new i;
        return e._observers = this._observers.slice(0),
        e
    }
    ,
    i.prototype.hasSpecificMask = function(e) {
        e === void 0 && (e = -1);
        for (var t = 0, r = this._observers; t < r.length; t++) {
            var n = r[t];
            if (n.mask & e || n.mask === e)
                return !0
        }
        return !1
    }
    ,
    i
}();
function IsWindowObjectExist() {
    return typeof window != "undefined"
}
function IsNavigatorAvailable() {
    return typeof navigator != "undefined"
}
function IsDocumentAvailable() {
    return typeof document != "undefined"
}
function GetDOMTextContent(i) {
    for (var e = "", t = i.firstChild; t; )
        t.nodeType === 3 && (e += t.textContent),
        t = t.nextSibling;
    return e
}
var DomManagement = {
    IsWindowObjectExist,
    IsNavigatorAvailable,
    IsDocumentAvailable,
    GetDOMTextContent
}
  , Logger$2 = function() {
    function i() {}
    return i._CheckLimit = function(e, t) {
        var r = i._LogLimitOutputs[e];
        return r ? r.current++ : (r = {
            limit: t,
            current: 1
        },
        i._LogLimitOutputs[e] = r),
        r.current <= r.limit
    }
    ,
    i._GenerateLimitMessage = function(e, t) {
        var r = i._LogLimitOutputs[e];
        if (!(!r || !i.MessageLimitReached) && r.current === r.limit)
            switch (t) {
            case 0:
                i.Log(i.MessageLimitReached.replace(/%LIMIT%/g, "" + r.limit).replace(/%TYPE%/g, "log"));
                break;
            case 1:
                i.Warn(i.MessageLimitReached.replace(/%LIMIT%/g, "" + r.limit).replace(/%TYPE%/g, "warning"));
                break;
            case 2:
                i.Error(i.MessageLimitReached.replace(/%LIMIT%/g, "" + r.limit).replace(/%TYPE%/g, "error"));
                break
            }
    }
    ,
    i._AddLogEntry = function(e) {
        i._LogCache = e + i._LogCache,
        i.OnNewCacheEntry && i.OnNewCacheEntry(e)
    }
    ,
    i._FormatMessage = function(e) {
        var t = function(n) {
            return n < 10 ? "0" + n : "" + n
        }
          , r = new Date;
        return "[" + t(r.getHours()) + ":" + t(r.getMinutes()) + ":" + t(r.getSeconds()) + "]: " + e
    }
    ,
    i._LogDisabled = function(e, t) {}
    ,
    i._LogEnabled = function(e, t) {
        if (!(t !== void 0 && !i._CheckLimit(e, t))) {
            var r = i._FormatMessage(e);
            console.log("BJS - " + r);
            var n = "<div style='color:white'>" + r + "</div><br>";
            i._AddLogEntry(n),
            i._GenerateLimitMessage(e, 0)
        }
    }
    ,
    i._WarnDisabled = function(e, t) {}
    ,
    i._WarnEnabled = function(e, t) {
        if (!(t !== void 0 && !i._CheckLimit(e, t))) {
            var r = i._FormatMessage(e);
            console.warn("BJS - " + r);
            var n = "<div style='color:orange'>" + e + "</div><br>";
            i._AddLogEntry(n),
            i._GenerateLimitMessage(e, 1)
        }
    }
    ,
    i._ErrorDisabled = function(e, t) {}
    ,
    i._ErrorEnabled = function(e, t) {
        if (!(t !== void 0 && !i._CheckLimit(e, t))) {
            var r = i._FormatMessage(e);
            i.errorsCount++,
            console.error("BJS - " + r);
            var n = "<div style='color:red'>" + r + "</div><br>";
            i._AddLogEntry(n),
            i._GenerateLimitMessage(e, 2)
        }
    }
    ,
    Object.defineProperty(i, "LogCache", {
        get: function() {
            return i._LogCache
        },
        enumerable: !1,
        configurable: !0
    }),
    i.ClearLogCache = function() {
        i._LogCache = "",
        i._LogLimitOutputs = {},
        i.errorsCount = 0
    }
    ,
    Object.defineProperty(i, "LogLevels", {
        set: function(e) {
            (e & i.MessageLogLevel) === i.MessageLogLevel ? i.Log = i._LogEnabled : i.Log = i._LogDisabled,
            (e & i.WarningLogLevel) === i.WarningLogLevel ? i.Warn = i._WarnEnabled : i.Warn = i._WarnDisabled,
            (e & i.ErrorLogLevel) === i.ErrorLogLevel ? i.Error = i._ErrorEnabled : i.Error = i._ErrorDisabled
        },
        enumerable: !1,
        configurable: !0
    }),
    i.NoneLogLevel = 0,
    i.MessageLogLevel = 1,
    i.WarningLogLevel = 2,
    i.ErrorLogLevel = 4,
    i.AllLogLevel = 7,
    i.MessageLimitReached = "Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.",
    i._LogCache = "",
    i._LogLimitOutputs = {},
    i.errorsCount = 0,
    i.Log = i._LogEnabled,
    i.Warn = i._WarnEnabled,
    i.Error = i._ErrorEnabled,
    i
}()
  , EndsWith = function(i, e) {
    return i.indexOf(e, i.length - e.length) !== -1
}
  , StartsWith = function(i, e) {
    return i ? i.indexOf(e) === 0 : !1
}
  , Decode = function(i) {
    if (typeof TextDecoder != "undefined")
        return new TextDecoder().decode(i);
    for (var e = "", t = 0; t < i.byteLength; t++)
        e += String.fromCharCode(i[t]);
    return e
}
  , EncodeArrayBufferToBase64 = function(i) {
    for (var e = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", t = "", r, n, o, a, s, l, u, c = 0, h = ArrayBuffer.isView(i) ? new Uint8Array(i.buffer,i.byteOffset,i.byteLength) : new Uint8Array(i); c < h.length; )
        r = h[c++],
        n = c < h.length ? h[c++] : Number.NaN,
        o = c < h.length ? h[c++] : Number.NaN,
        a = r >> 2,
        s = (r & 3) << 4 | n >> 4,
        l = (n & 15) << 2 | o >> 6,
        u = o & 63,
        isNaN(n) ? l = u = 64 : isNaN(o) && (u = 64),
        t += e.charAt(a) + e.charAt(s) + e.charAt(l) + e.charAt(u);
    return t
}
  , DecodeBase64ToString = function(i) {
    return atob(i)
}
  , DecodeBase64ToBinary = function(i) {
    for (var e = DecodeBase64ToString(i), t = e.length, r = new Uint8Array(new ArrayBuffer(t)), n = 0; n < t; n++)
        r[n] = e.charCodeAt(n);
    return r.buffer
}
  , PadNumber = function(i, e) {
    for (var t = String(i); t.length < e; )
        t = "0" + t;
    return t
}
  , StringTools = {
    EndsWith,
    StartsWith,
    Decode,
    EncodeArrayBufferToBase64,
    DecodeBase64ToString,
    DecodeBase64ToBinary,
    PadNumber
}
  , cloneValue = function(i, e) {
    return !i || i.getClassName && i.getClassName() === "Mesh" ? null : i.getClassName && i.getClassName() === "SubMesh" ? i.clone(e) : i.clone ? i.clone() : null
};
function getAllPropertyNames(i) {
    var e = [];
    do
        Object.getOwnPropertyNames(i).forEach(function(t) {
            e.indexOf(t) === -1 && e.push(t)
        });
    while (i = Object.getPrototypeOf(i));
    return e
}
var DeepCopier = function() {
    function i() {}
    return i.DeepCopy = function(e, t, r, n) {
        for (var o = getAllPropertyNames(e), a = 0, s = o; a < s.length; a++) {
            var l = s[a];
            if (!(l[0] === "_" && (!n || n.indexOf(l) === -1)) && !EndsWith(l, "Observable") && !(r && r.indexOf(l) !== -1)) {
                var u = e[l]
                  , c = typeof u;
                if (c !== "function")
                    try {
                        if (c === "object")
                            if (u instanceof Array) {
                                if (t[l] = [],
                                u.length > 0)
                                    if (typeof u[0] == "object")
                                        for (var h = 0; h < u.length; h++) {
                                            var f = cloneValue(u[h], t);
                                            t[l].indexOf(f) === -1 && t[l].push(f)
                                        }
                                    else
                                        t[l] = u.slice(0)
                            } else
                                t[l] = cloneValue(u, t);
                        else
                            t[l] = u
                    } catch (d) {
                        Logger$2.Warn(d.message)
                    }
            }
        }
    }
    ,
    i
}()
  , PrecisionDate = function() {
    function i() {}
    return Object.defineProperty(i, "Now", {
        get: function() {
            return DomManagement.IsWindowObjectExist() && window.performance && window.performance.now ? window.performance.now() : Date.now()
        },
        enumerable: !1,
        configurable: !0
    }),
    i
}();
function _WarnImport(i) {
    return i + " needs to be imported before as it contains a side-effect required by your code."
}
function createXMLHttpRequest() {
    return typeof _native != "undefined" && _native.XMLHttpRequest ? new _native.XMLHttpRequest : new XMLHttpRequest
}
var WebRequest = function() {
    function i() {
        this._xhr = createXMLHttpRequest()
    }
    return i.prototype._injectCustomRequestHeaders = function() {
        for (var e in i.CustomRequestHeaders) {
            var t = i.CustomRequestHeaders[e];
            t && this._xhr.setRequestHeader(e, t)
        }
    }
    ,
    Object.defineProperty(i.prototype, "onprogress", {
        get: function() {
            return this._xhr.onprogress
        },
        set: function(e) {
            this._xhr.onprogress = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "readyState", {
        get: function() {
            return this._xhr.readyState
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "status", {
        get: function() {
            return this._xhr.status
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "statusText", {
        get: function() {
            return this._xhr.statusText
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "response", {
        get: function() {
            return this._xhr.response
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "responseURL", {
        get: function() {
            return this._xhr.responseURL
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "responseText", {
        get: function() {
            return this._xhr.responseText
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "responseType", {
        get: function() {
            return this._xhr.responseType
        },
        set: function(e) {
            this._xhr.responseType = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "timeout", {
        get: function() {
            return this._xhr.timeout
        },
        set: function(e) {
            this._xhr.timeout = e
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.addEventListener = function(e, t, r) {
        this._xhr.addEventListener(e, t, r)
    }
    ,
    i.prototype.removeEventListener = function(e, t, r) {
        this._xhr.removeEventListener(e, t, r)
    }
    ,
    i.prototype.abort = function() {
        this._xhr.abort()
    }
    ,
    i.prototype.send = function(e) {
        i.CustomRequestHeaders && this._injectCustomRequestHeaders(),
        this._xhr.send(e)
    }
    ,
    i.prototype.open = function(e, t) {
        for (var r = 0, n = i.CustomRequestModifiers; r < n.length; r++) {
            var o = n[r];
            o(this._xhr, t)
        }
        return t = t.replace("file:http:", "http:"),
        t = t.replace("file:https:", "https:"),
        this._xhr.open(e, t, !0)
    }
    ,
    i.prototype.setRequestHeader = function(e, t) {
        this._xhr.setRequestHeader(e, t)
    }
    ,
    i.prototype.getResponseHeader = function(e) {
        return this._xhr.getResponseHeader(e)
    }
    ,
    i.CustomRequestHeaders = {},
    i.CustomRequestModifiers = new Array,
    i
}(), EngineStore = function() {
    function i() {}
    return Object.defineProperty(i, "LastCreatedEngine", {
        get: function() {
            return this.Instances.length === 0 ? null : this.Instances[this.Instances.length - 1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i, "LastCreatedScene", {
        get: function() {
            return this._LastCreatedScene
        },
        enumerable: !1,
        configurable: !0
    }),
    i.Instances = new Array,
    i._LastCreatedScene = null,
    i.UseFallbackTexture = !0,
    i.FallbackTexture = "",
    i
}(), FilesInputStore = function() {
    function i() {}
    return i.FilesToLoad = {},
    i
}(), RetryStrategy = function() {
    function i() {}
    return i.ExponentialBackoff = function(e, t) {
        return e === void 0 && (e = 3),
        t === void 0 && (t = 500),
        function(r, n, o) {
            return n.status !== 0 || o >= e || r.indexOf("file:") !== -1 ? -1 : Math.pow(2, o) * t
        }
    }
    ,
    i
}(), BaseError = function(i) {
    __extends(e, i);
    function e() {
        return i !== null && i.apply(this, arguments) || this
    }
    return e._setPrototypeOf = Object.setPrototypeOf || function(t, r) {
        return t.__proto__ = r,
        t
    }
    ,
    e
}(Error), ShaderCodeNode = function() {
    function i() {
        this.children = []
    }
    return i.prototype.isValid = function(e) {
        return !0
    }
    ,
    i.prototype.process = function(e, t) {
        var r = "";
        if (this.line) {
            var n = this.line
              , o = t.processor;
            if (o) {
                if (o.lineProcessor && (n = o.lineProcessor(n, t.isFragment, t.processingContext)),
                o.attributeProcessor && StartsWith(this.line, "attribute"))
                    n = o.attributeProcessor(this.line, e, t.processingContext);
                else if (o.varyingProcessor && StartsWith(this.line, "varying"))
                    n = o.varyingProcessor(this.line, t.isFragment, e, t.processingContext);
                else if (o.uniformProcessor && o.uniformRegexp && o.uniformRegexp.test(this.line))
                    t.lookForClosingBracketForUniformBuffer || (n = o.uniformProcessor(this.line, t.isFragment, e, t.processingContext));
                else if (o.uniformBufferProcessor && o.uniformBufferRegexp && o.uniformBufferRegexp.test(this.line))
                    t.lookForClosingBracketForUniformBuffer || (n = o.uniformBufferProcessor(this.line, t.isFragment, t.processingContext),
                    t.lookForClosingBracketForUniformBuffer = !0);
                else if (o.textureProcessor && o.textureRegexp && o.textureRegexp.test(this.line))
                    n = o.textureProcessor(this.line, t.isFragment, e, t.processingContext);
                else if ((o.uniformProcessor || o.uniformBufferProcessor) && StartsWith(this.line, "uniform") && !t.lookForClosingBracketForUniformBuffer) {
                    var a = /uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/;
                    a.test(this.line) ? o.uniformProcessor && (n = o.uniformProcessor(this.line, t.isFragment, e, t.processingContext)) : o.uniformBufferProcessor && (n = o.uniformBufferProcessor(this.line, t.isFragment, t.processingContext),
                    t.lookForClosingBracketForUniformBuffer = !0)
                }
                t.lookForClosingBracketForUniformBuffer && this.line.indexOf("}") !== -1 && (t.lookForClosingBracketForUniformBuffer = !1,
                o.endOfUniformBufferProcessor && (n = o.endOfUniformBufferProcessor(this.line, t.isFragment, t.processingContext)))
            }
            r += n + `\r
`
        }
        return this.children.forEach(function(s) {
            r += s.process(e, t)
        }),
        this.additionalDefineKey && (e[this.additionalDefineKey] = this.additionalDefineValue || "true"),
        r
    }
    ,
    i
}(), ShaderCodeCursor = function() {
    function i() {}
    return Object.defineProperty(i.prototype, "currentLine", {
        get: function() {
            return this._lines[this.lineIndex]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "canRead", {
        get: function() {
            return this.lineIndex < this._lines.length - 1
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "lines", {
        set: function(e) {
            this._lines = [];
            for (var t = 0, r = e; t < r.length; t++) {
                var n = r[t];
                if (n[0] === "#") {
                    this._lines.push(n);
                    continue
                }
                for (var o = n.split(";"), a = 0; a < o.length; a++) {
                    var s = o[a];
                    s = s.trim(),
                    s && this._lines.push(s + (a !== o.length - 1 ? ";" : ""))
                }
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    i
}(), ShaderCodeConditionNode = function(i) {
    __extends(e, i);
    function e() {
        return i !== null && i.apply(this, arguments) || this
    }
    return e.prototype.process = function(t, r) {
        for (var n = 0; n < this.children.length; n++) {
            var o = this.children[n];
            if (o.isValid(t))
                return o.process(t, r)
        }
        return ""
    }
    ,
    e
}(ShaderCodeNode), ShaderCodeTestNode = function(i) {
    __extends(e, i);
    function e() {
        return i !== null && i.apply(this, arguments) || this
    }
    return e.prototype.isValid = function(t) {
        return this.testExpression.isTrue(t)
    }
    ,
    e
}(ShaderCodeNode), ShaderDefineExpression = function() {
    function i() {}
    return i.prototype.isTrue = function(e) {
        return !0
    }
    ,
    i.postfixToInfix = function(e) {
        for (var t = [], r = 0, n = e; r < n.length; r++) {
            var o = n[r];
            if (i._OperatorPriority[o] === void 0)
                t.push(o);
            else {
                var a = t[t.length - 1]
                  , s = t[t.length - 2];
                t.length -= 2,
                t.push("(" + s + o + a + ")")
            }
        }
        return t[t.length - 1]
    }
    ,
    i.infixToPostfix = function(e) {
        for (var t = [], r = -1, n = function() {
            u = u.trim(),
            u !== "" && (t.push(u),
            u = "")
        }, o = function(f) {
            r < i._Stack.length - 1 && (i._Stack[++r] = f)
        }, a = function() {
            return i._Stack[r]
        }, s = function() {
            return r === -1 ? "!!INVALID EXPRESSION!!" : i._Stack[r--]
        }, l = 0, u = ""; l < e.length; ) {
            var c = e.charAt(l)
              , h = l < e.length - 1 ? e.substr(l, 2) : "";
            if (c === "(")
                u = "",
                o(c);
            else if (c === ")") {
                for (n(); r !== -1 && a() !== "("; )
                    t.push(s());
                s()
            } else if (i._OperatorPriority[h] > 1) {
                for (n(); r !== -1 && i._OperatorPriority[a()] >= i._OperatorPriority[h]; )
                    t.push(s());
                o(h),
                l++
            } else
                u += c;
            l++
        }
        for (n(); r !== -1; )
            a() === "(" ? s() : t.push(s());
        return t
    }
    ,
    i._OperatorPriority = {
        ")": 0,
        "(": 1,
        "||": 2,
        "&&": 3
    },
    i._Stack = ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""],
    i
}(), ShaderDefineIsDefinedOperator = function(i) {
    __extends(e, i);
    function e(t, r) {
        r === void 0 && (r = !1);
        var n = i.call(this) || this;
        return n.define = t,
        n.not = r,
        n
    }
    return e.prototype.isTrue = function(t) {
        var r = t[this.define] !== void 0;
        return this.not && (r = !r),
        r
    }
    ,
    e
}(ShaderDefineExpression), ShaderDefineOrOperator = function(i) {
    __extends(e, i);
    function e() {
        return i !== null && i.apply(this, arguments) || this
    }
    return e.prototype.isTrue = function(t) {
        return this.leftOperand.isTrue(t) || this.rightOperand.isTrue(t)
    }
    ,
    e
}(ShaderDefineExpression), ShaderDefineAndOperator = function(i) {
    __extends(e, i);
    function e() {
        return i !== null && i.apply(this, arguments) || this
    }
    return e.prototype.isTrue = function(t) {
        return this.leftOperand.isTrue(t) && this.rightOperand.isTrue(t)
    }
    ,
    e
}(ShaderDefineExpression), ShaderDefineArithmeticOperator = function(i) {
    __extends(e, i);
    function e(t, r, n) {
        var o = i.call(this) || this;
        return o.define = t,
        o.operand = r,
        o.testValue = n,
        o
    }
    return e.prototype.isTrue = function(t) {
        var r = t[this.define];
        r === void 0 && (r = this.define);
        var n = !1
          , o = parseInt(r)
          , a = parseInt(this.testValue);
        switch (this.operand) {
        case ">":
            n = o > a;
            break;
        case "<":
            n = o < a;
            break;
        case "<=":
            n = o <= a;
            break;
        case ">=":
            n = o >= a;
            break;
        case "==":
            n = o === a;
            break
        }
        return n
    }
    ,
    e
}(ShaderDefineExpression), ShaderLanguage;
(function(i) {
    i[i.GLSL = 0] = "GLSL",
    i[i.WGSL = 1] = "WGSL"
}
)(ShaderLanguage || (ShaderLanguage = {}));
var regexSE = /defined\s*?\((.+?)\)/g, regexSERevert = /defined\s*?\[(.+?)\]/g, ShaderProcessor = function() {
    function i() {}
    return i.Initialize = function(e) {
        e.processor && e.processor.initializeShaders && e.processor.initializeShaders(e.processingContext)
    }
    ,
    i.Process = function(e, t, r, n) {
        var o = this, a;
        !((a = t.processor) === null || a === void 0) && a.preProcessShaderCode && (e = t.processor.preProcessShaderCode(e)),
        this._ProcessIncludes(e, t, function(s) {
            var l = o._ProcessShaderConversion(s, t, n);
            r(l)
        })
    }
    ,
    i.PreProcess = function(e, t, r, n) {
        var o = this, a;
        !((a = t.processor) === null || a === void 0) && a.preProcessShaderCode && (e = t.processor.preProcessShaderCode(e)),
        this._ProcessIncludes(e, t, function(s) {
            var l = o._ApplyPreProcessing(s, t, n);
            r(l)
        })
    }
    ,
    i.Finalize = function(e, t, r) {
        return !r.processor || !r.processor.finalizeShaders ? {
            vertexCode: e,
            fragmentCode: t
        } : r.processor.finalizeShaders(e, t, r.processingContext)
    }
    ,
    i._ProcessPrecision = function(e, t) {
        var r;
        if (!((r = t.processor) === null || r === void 0) && r.noPrecision)
            return e;
        var n = t.shouldUseHighPrecisionShader;
        return e.indexOf("precision highp float") === -1 ? n ? e = `precision highp float;
` + e : e = `precision mediump float;
` + e : n || (e = e.replace("precision highp float", "precision mediump float")),
        e
    }
    ,
    i._ExtractOperation = function(e) {
        var t = /defined\((.+)\)/
          , r = t.exec(e);
        if (r && r.length)
            return new ShaderDefineIsDefinedOperator(r[1].trim(),e[0] === "!");
        for (var n = ["==", ">=", "<=", "<", ">"], o = "", a = 0, s = 0, l = n; s < l.length && (o = l[s],
        a = e.indexOf(o),
        !(a > -1)); s++)
            ;
        if (a === -1)
            return new ShaderDefineIsDefinedOperator(e);
        var u = e.substring(0, a).trim()
          , c = e.substring(a + o.length).trim();
        return new ShaderDefineArithmeticOperator(u,o,c)
    }
    ,
    i._BuildSubExpression = function(e) {
        e = e.replace(regexSE, "defined[$1]");
        for (var t = ShaderDefineExpression.infixToPostfix(e), r = [], n = 0, o = t; n < o.length; n++) {
            var a = o[n];
            if (a !== "||" && a !== "&&")
                r.push(a);
            else if (r.length >= 2) {
                var s = r[r.length - 1]
                  , l = r[r.length - 2];
                r.length -= 2;
                var u = a == "&&" ? new ShaderDefineAndOperator : new ShaderDefineOrOperator;
                typeof s == "string" && (s = s.replace(regexSERevert, "defined($1)")),
                typeof l == "string" && (l = l.replace(regexSERevert, "defined($1)")),
                u.leftOperand = typeof l == "string" ? this._ExtractOperation(l) : l,
                u.rightOperand = typeof s == "string" ? this._ExtractOperation(s) : s,
                r.push(u)
            }
        }
        var c = r[r.length - 1];
        return typeof c == "string" && (c = c.replace(regexSERevert, "defined($1)")),
        typeof c == "string" ? this._ExtractOperation(c) : c
    }
    ,
    i._BuildExpression = function(e, t) {
        var r = new ShaderCodeTestNode
          , n = e.substring(0, t)
          , o = e.substring(t);
        return o = o.substring(0, (o.indexOf("//") + 1 || o.length + 1) - 1).trim(),
        n === "#ifdef" ? r.testExpression = new ShaderDefineIsDefinedOperator(o) : n === "#ifndef" ? r.testExpression = new ShaderDefineIsDefinedOperator(o,!0) : r.testExpression = this._BuildSubExpression(o),
        r
    }
    ,
    i._MoveCursorWithinIf = function(e, t, r) {
        for (var n = e.currentLine; this._MoveCursor(e, r); ) {
            n = e.currentLine;
            var o = n.substring(0, 5).toLowerCase();
            if (o === "#else") {
                var a = new ShaderCodeNode;
                t.children.push(a),
                this._MoveCursor(e, a);
                return
            } else if (o === "#elif") {
                var s = this._BuildExpression(n, 5);
                t.children.push(s),
                r = s
            }
        }
    }
    ,
    i._MoveCursor = function(e, t) {
        for (; e.canRead; ) {
            e.lineIndex++;
            var r = e.currentLine
              , n = /(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/
              , o = n.exec(r);
            if (o && o.length) {
                var a = o[0];
                switch (a) {
                case "#ifdef":
                    {
                        var s = new ShaderCodeConditionNode;
                        t.children.push(s);
                        var l = this._BuildExpression(r, 6);
                        s.children.push(l),
                        this._MoveCursorWithinIf(e, s, l);
                        break
                    }
                case "#else":
                case "#elif":
                    return !0;
                case "#endif":
                    return !1;
                case "#ifndef":
                    {
                        var s = new ShaderCodeConditionNode;
                        t.children.push(s);
                        var l = this._BuildExpression(r, 7);
                        s.children.push(l),
                        this._MoveCursorWithinIf(e, s, l);
                        break
                    }
                case "#if":
                    {
                        var s = new ShaderCodeConditionNode
                          , l = this._BuildExpression(r, 3);
                        t.children.push(s),
                        s.children.push(l),
                        this._MoveCursorWithinIf(e, s, l);
                        break
                    }
                }
            } else {
                var u = new ShaderCodeNode;
                if (u.line = r,
                t.children.push(u),
                r[0] === "#" && r[1] === "d") {
                    var c = r.replace(";", "").split(" ");
                    u.additionalDefineKey = c[1],
                    c.length === 3 && (u.additionalDefineValue = c[2])
                }
            }
        }
        return !1
    }
    ,
    i._EvaluatePreProcessors = function(e, t, r) {
        var n = new ShaderCodeNode
          , o = new ShaderCodeCursor;
        return o.lineIndex = -1,
        o.lines = e.split(`
`),
        this._MoveCursor(o, n),
        n.process(t, r)
    }
    ,
    i._PreparePreProcessors = function(e, t) {
        for (var r, n = e.defines, o = {}, a = 0, s = n; a < s.length; a++) {
            var l = s[a]
              , u = l.replace("#define", "").replace(";", "").trim()
              , c = u.split(" ");
            o[c[0]] = c.length > 1 ? c[1] : ""
        }
        return ((r = e.processor) === null || r === void 0 ? void 0 : r.shaderLanguage) === ShaderLanguage.GLSL && (o.GL_ES = "true"),
        o.__VERSION__ = e.version,
        o[e.platformName] = "true",
        t._getGlobalDefines(o),
        o
    }
    ,
    i._ProcessShaderConversion = function(e, t, r) {
        var n = this._ProcessPrecision(e, t);
        if (!t.processor)
            return n;
        if (t.processor.shaderLanguage === ShaderLanguage.GLSL && n.indexOf("#version 3") !== -1)
            return n.replace("#version 300 es", "");
        var o = t.defines
          , a = this._PreparePreProcessors(t, r);
        return t.processor.preProcessor && (n = t.processor.preProcessor(n, o, t.isFragment, t.processingContext)),
        n = this._EvaluatePreProcessors(n, a, t),
        t.processor.postProcessor && (n = t.processor.postProcessor(n, o, t.isFragment, t.processingContext, r)),
        r._features.needShaderCodeInlining && (n = r.inlineShaderCode(n)),
        n
    }
    ,
    i._ApplyPreProcessing = function(e, t, r) {
        var n, o, a = e, s = t.defines, l = this._PreparePreProcessors(t, r);
        return !((n = t.processor) === null || n === void 0) && n.preProcessor && (a = t.processor.preProcessor(a, s, t.isFragment, t.processingContext)),
        a = this._EvaluatePreProcessors(a, l, t),
        !((o = t.processor) === null || o === void 0) && o.postProcessor && (a = t.processor.postProcessor(a, s, t.isFragment, t.processingContext, r)),
        r._features.needShaderCodeInlining && (a = r.inlineShaderCode(a)),
        a
    }
    ,
    i._ProcessIncludes = function(e, t, r) {
        for (var n = this, o = /#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g, a = o.exec(e), s = new String(e), l = !1; a != null; ) {
            var u = a[1];
            if (u.indexOf("__decl__") !== -1 && (u = u.replace(/__decl__/, ""),
            t.supportsUniformBuffers && (u = u.replace(/Vertex/, "Ubo"),
            u = u.replace(/Fragment/, "Ubo")),
            u = u + "Declaration"),
            t.includesShadersStore[u]) {
                var c = t.includesShadersStore[u];
                if (a[2])
                    for (var h = a[3].split(","), f = 0; f < h.length; f += 2) {
                        var d = new RegExp(h[f],"g")
                          , _ = h[f + 1];
                        c = c.replace(d, _)
                    }
                if (a[4]) {
                    var g = a[5];
                    if (g.indexOf("..") !== -1) {
                        var m = g.split("..")
                          , v = parseInt(m[0])
                          , y = parseInt(m[1])
                          , b = c.slice(0);
                        c = "",
                        isNaN(y) && (y = t.indexParameters[m[1]]);
                        for (var T = v; T < y; T++)
                            t.supportsUniformBuffers || (b = b.replace(/light\{X\}.(\w*)/g, function(A, S) {
                                return S + "{X}"
                            })),
                            c += b.replace(/\{X\}/g, T.toString()) + `
`
                    } else
                        t.supportsUniformBuffers || (c = c.replace(/light\{X\}.(\w*)/g, function(A, S) {
                            return S + "{X}"
                        })),
                        c = c.replace(/\{X\}/g, g)
                }
                s = s.replace(a[0], c),
                l = l || c.indexOf("#include<") >= 0 || c.indexOf("#include <") >= 0
            } else {
                var C = t.shadersRepository + "ShadersInclude/" + u + ".fx";
                i._FileToolsLoadFile(C, function(A) {
                    t.includesShadersStore[u] = A,
                    n._ProcessIncludes(s, t, r)
                });
                return
            }
            a = o.exec(e)
        }
        l ? this._ProcessIncludes(s.toString(), t, r) : r(s)
    }
    ,
    i._FileToolsLoadFile = function(e, t, r, n, o, a) {
        throw _WarnImport("FileTools")
    }
    ,
    i
}(), ShaderStore = function() {
    function i() {}
    return i.GetShadersRepository = function(e) {
        return e === void 0 && (e = ShaderLanguage.GLSL),
        e === ShaderLanguage.GLSL ? i.ShadersRepository : i.ShadersRepositoryWGSL
    }
    ,
    i.GetShadersStore = function(e) {
        return e === void 0 && (e = ShaderLanguage.GLSL),
        e === ShaderLanguage.GLSL ? i.ShadersStore : i.ShadersStoreWGSL
    }
    ,
    i.GetIncludesShadersStore = function(e) {
        return e === void 0 && (e = ShaderLanguage.GLSL),
        e === ShaderLanguage.GLSL ? i.IncludesShadersStore : i.IncludesShadersStoreWGSL
    }
    ,
    i.ShadersRepository = "src/Shaders/",
    i.ShadersStore = {},
    i.IncludesShadersStore = {},
    i.ShadersRepositoryWGSL = "src/ShadersWGSL/",
    i.ShadersStoreWGSL = {},
    i.IncludesShadersStoreWGSL = {},
    i
}(), Effect = function() {
    function i(e, t, r, n, o, a, s, l, u, c, h, f) {
        var d = this;
        n === void 0 && (n = null),
        a === void 0 && (a = null),
        s === void 0 && (s = null),
        l === void 0 && (l = null),
        u === void 0 && (u = null),
        h === void 0 && (h = ""),
        f === void 0 && (f = ShaderLanguage.GLSL);
        var _, g;
        this.name = null,
        this.defines = "",
        this.onCompiled = null,
        this.onError = null,
        this.onBind = null,
        this.uniqueId = 0,
        this.onCompileObservable = new Observable,
        this.onErrorObservable = new Observable,
        this._onBindObservable = null,
        this._wasPreviouslyReady = !1,
        this._bonesComputationForcedToCPU = !1,
        this._uniformBuffersNames = {},
        this._multiTarget = !1,
        this._samplers = {},
        this._isReady = !1,
        this._compilationError = "",
        this._allFallbacksProcessed = !1,
        this._uniforms = {},
        this._key = "",
        this._fallbacks = null,
        this._vertexSourceCodeOverride = "",
        this._fragmentSourceCodeOverride = "",
        this._transformFeedbackVaryings = null,
        this._pipelineContext = null,
        this._vertexSourceCode = "",
        this._fragmentSourceCode = "",
        this._rawVertexSourceCode = "",
        this._rawFragmentSourceCode = "",
        this.name = e,
        this._key = h;
        var m = null;
        if (t.attributes) {
            var v = t;
            if (this._engine = r,
            this._attributesNames = v.attributes,
            this._uniformsNames = v.uniformsNames.concat(v.samplers),
            this._samplerList = v.samplers.slice(),
            this.defines = v.defines,
            this.onError = v.onError,
            this.onCompiled = v.onCompiled,
            this._fallbacks = v.fallbacks,
            this._indexParameters = v.indexParameters,
            this._transformFeedbackVaryings = v.transformFeedbackVaryings || null,
            this._multiTarget = !!v.multiTarget,
            this._shaderLanguage = (_ = v.shaderLanguage) !== null && _ !== void 0 ? _ : ShaderLanguage.GLSL,
            v.uniformBuffersNames) {
                this._uniformBuffersNamesList = v.uniformBuffersNames.slice();
                for (var y = 0; y < v.uniformBuffersNames.length; y++)
                    this._uniformBuffersNames[v.uniformBuffersNames[y]] = y
            }
            m = (g = v.processFinalCode) !== null && g !== void 0 ? g : null
        } else
            this._engine = o,
            this.defines = a == null ? "" : a,
            this._uniformsNames = r.concat(n),
            this._samplerList = n ? n.slice() : [],
            this._attributesNames = t,
            this._uniformBuffersNamesList = [],
            this._shaderLanguage = f,
            this.onError = u,
            this.onCompiled = l,
            this._indexParameters = c,
            this._fallbacks = s;
        this._attributeLocationByName = {},
        this.uniqueId = i._uniqueIdSeed++;
        var b, T, C = IsWindowObjectExist() ? this._engine.getHostDocument() : null;
        e.vertexSource ? b = "source:" + e.vertexSource : e.vertexElement ? (b = C ? C.getElementById(e.vertexElement) : null,
        b || (b = e.vertexElement)) : b = e.vertex || e,
        e.fragmentSource ? T = "source:" + e.fragmentSource : e.fragmentElement ? (T = C ? C.getElementById(e.fragmentElement) : null,
        T || (T = e.fragmentElement)) : T = e.fragment || e,
        this._processingContext = this._engine._getShaderProcessingContext(this._shaderLanguage);
        var A = {
            defines: this.defines.split(`
`),
            indexParameters: this._indexParameters,
            isFragment: !1,
            shouldUseHighPrecisionShader: this._engine._shouldUseHighPrecisionShader,
            processor: this._engine._getShaderProcessor(this._shaderLanguage),
            supportsUniformBuffers: this._engine.supportsUniformBuffers,
            shadersRepository: ShaderStore.GetShadersRepository(this._shaderLanguage),
            includesShadersStore: ShaderStore.GetIncludesShadersStore(this._shaderLanguage),
            version: (this._engine.version * 100).toString(),
            platformName: this._engine.shaderPlatformName,
            processingContext: this._processingContext,
            isNDCHalfZRange: this._engine.isNDCHalfZRange,
            useReverseDepthBuffer: this._engine.useReverseDepthBuffer
        }
          , S = [void 0, void 0]
          , P = function() {
            if (S[0] && S[1]) {
                A.isFragment = !0;
                var R = S[0]
                  , M = S[1];
                ShaderProcessor.Process(M, A, function(x) {
                    m && (x = m("fragment", x));
                    var I = ShaderProcessor.Finalize(R, x, A);
                    d._useFinalCode(I.vertexCode, I.fragmentCode, e)
                }, d._engine)
            }
        };
        this._loadShader(b, "Vertex", "", function(R) {
            ShaderProcessor.Initialize(A),
            ShaderProcessor.Process(R, A, function(M) {
                d._rawVertexSourceCode = R,
                m && (M = m("vertex", M)),
                S[0] = M,
                P()
            }, d._engine)
        }),
        this._loadShader(T, "Fragment", "Pixel", function(R) {
            d._rawFragmentSourceCode = R,
            S[1] = R,
            P()
        })
    }
    return Object.defineProperty(i, "ShadersRepository", {
        get: function() {
            return ShaderStore.ShadersRepository
        },
        set: function(e) {
            ShaderStore.ShadersRepository = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "onBindObservable", {
        get: function() {
            return this._onBindObservable || (this._onBindObservable = new Observable),
            this._onBindObservable
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype._useFinalCode = function(e, t, r) {
        if (r) {
            var n = r.vertexElement || r.vertex || r.spectorName || r
              , o = r.fragmentElement || r.fragment || r.spectorName || r;
            this._vertexSourceCode = (this._shaderLanguage === ShaderLanguage.WGSL ? "//" : "") + "#define SHADER_NAME vertex:" + n + `
` + e,
            this._fragmentSourceCode = (this._shaderLanguage === ShaderLanguage.WGSL ? "//" : "") + "#define SHADER_NAME fragment:" + o + `
` + t
        } else
            this._vertexSourceCode = e,
            this._fragmentSourceCode = t;
        this._prepareEffect()
    }
    ,
    Object.defineProperty(i.prototype, "key", {
        get: function() {
            return this._key
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.isReady = function() {
        try {
            return this._isReadyInternal()
        } catch {
            return !1
        }
    }
    ,
    i.prototype._isReadyInternal = function() {
        return this._isReady ? !0 : this._pipelineContext ? this._pipelineContext.isReady : !1
    }
    ,
    i.prototype.getEngine = function() {
        return this._engine
    }
    ,
    i.prototype.getPipelineContext = function() {
        return this._pipelineContext
    }
    ,
    i.prototype.getAttributesNames = function() {
        return this._attributesNames
    }
    ,
    i.prototype.getAttributeLocation = function(e) {
        return this._attributes[e]
    }
    ,
    i.prototype.getAttributeLocationByName = function(e) {
        return this._attributeLocationByName[e]
    }
    ,
    i.prototype.getAttributesCount = function() {
        return this._attributes.length
    }
    ,
    i.prototype.getUniformIndex = function(e) {
        return this._uniformsNames.indexOf(e)
    }
    ,
    i.prototype.getUniform = function(e) {
        return this._uniforms[e]
    }
    ,
    i.prototype.getSamplers = function() {
        return this._samplerList
    }
    ,
    i.prototype.getUniformNames = function() {
        return this._uniformsNames
    }
    ,
    i.prototype.getUniformBuffersNames = function() {
        return this._uniformBuffersNamesList
    }
    ,
    i.prototype.getIndexParameters = function() {
        return this._indexParameters
    }
    ,
    i.prototype.getCompilationError = function() {
        return this._compilationError
    }
    ,
    i.prototype.allFallbacksProcessed = function() {
        return this._allFallbacksProcessed
    }
    ,
    i.prototype.executeWhenCompiled = function(e) {
        var t = this;
        if (this.isReady()) {
            e(this);
            return
        }
        this.onCompileObservable.add(function(r) {
            e(r)
        }),
        (!this._pipelineContext || this._pipelineContext.isAsync) && setTimeout(function() {
            t._checkIsReady(null)
        }, 16)
    }
    ,
    i.prototype._checkIsReady = function(e) {
        var t = this;
        try {
            if (this._isReadyInternal())
                return
        } catch (r) {
            this._processCompilationErrors(r, e);
            return
        }
        setTimeout(function() {
            t._checkIsReady(e)
        }, 16)
    }
    ,
    i.prototype._loadShader = function(e, t, r, n) {
        if (typeof HTMLElement != "undefined" && e instanceof HTMLElement) {
            var o = GetDOMTextContent(e);
            n(o);
            return
        }
        if (e.substr(0, 7) === "source:") {
            n(e.substr(7));
            return
        }
        if (e.substr(0, 7) === "base64:") {
            var a = window.atob(e.substr(7));
            n(a);
            return
        }
        var s = ShaderStore.GetShadersStore(this._shaderLanguage);
        if (s[e + t + "Shader"]) {
            n(s[e + t + "Shader"]);
            return
        }
        if (r && s[e + r + "Shader"]) {
            n(s[e + r + "Shader"]);
            return
        }
        var l;
        e[0] === "." || e[0] === "/" || e.indexOf("http") > -1 ? l = e : l = ShaderStore.GetShadersRepository(this._shaderLanguage) + e,
        this._engine._loadFile(l + "." + t.toLowerCase() + ".fx", n)
    }
    ,
    Object.defineProperty(i.prototype, "vertexSourceCode", {
        get: function() {
            var e, t;
            return this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride ? this._vertexSourceCodeOverride : (t = (e = this._pipelineContext) === null || e === void 0 ? void 0 : e._getVertexShaderCode()) !== null && t !== void 0 ? t : this._vertexSourceCode
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "fragmentSourceCode", {
        get: function() {
            var e, t;
            return this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride ? this._fragmentSourceCodeOverride : (t = (e = this._pipelineContext) === null || e === void 0 ? void 0 : e._getFragmentShaderCode()) !== null && t !== void 0 ? t : this._fragmentSourceCode
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "rawVertexSourceCode", {
        get: function() {
            return this._rawVertexSourceCode
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "rawFragmentSourceCode", {
        get: function() {
            return this._rawFragmentSourceCode
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype._rebuildProgram = function(e, t, r, n) {
        var o = this;
        this._isReady = !1,
        this._vertexSourceCodeOverride = e,
        this._fragmentSourceCodeOverride = t,
        this.onError = function(a, s) {
            n && n(s)
        }
        ,
        this.onCompiled = function() {
            var a = o.getEngine().scenes;
            if (a)
                for (var s = 0; s < a.length; s++)
                    a[s].markAllMaterialsAsDirty(63);
            o._pipelineContext._handlesSpectorRebuildCallback(r)
        }
        ,
        this._fallbacks = null,
        this._prepareEffect()
    }
    ,
    i.prototype._prepareEffect = function() {
        var e = this
          , t = this._attributesNames
          , r = this.defines
          , n = this._pipelineContext;
        this._isReady = !1;
        try {
            var o = this._engine;
            this._pipelineContext = o.createPipelineContext(this._processingContext),
            this._pipelineContext._name = this._key;
            var a = this._rebuildProgram.bind(this);
            this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride ? o._preparePipelineContext(this._pipelineContext, this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, !0, this._rawVertexSourceCode, this._rawFragmentSourceCode, a, null, this._transformFeedbackVaryings, this._key) : o._preparePipelineContext(this._pipelineContext, this._vertexSourceCode, this._fragmentSourceCode, !1, this._rawVertexSourceCode, this._rawFragmentSourceCode, a, r, this._transformFeedbackVaryings, this._key),
            o._executeWhenRenderingStateIsCompiled(this._pipelineContext, function() {
                if (e._attributes = [],
                e._pipelineContext._fillEffectInformation(e, e._uniformBuffersNames, e._uniformsNames, e._uniforms, e._samplerList, e._samplers, t, e._attributes),
                t)
                    for (var s = 0; s < t.length; s++) {
                        var l = t[s];
                        e._attributeLocationByName[l] = e._attributes[s]
                    }
                o.bindSamplers(e),
                e._compilationError = "",
                e._isReady = !0,
                e.onCompiled && e.onCompiled(e),
                e.onCompileObservable.notifyObservers(e),
                e.onCompileObservable.clear(),
                e._fallbacks && e._fallbacks.unBindMesh(),
                n && e.getEngine()._deletePipelineContext(n)
            }),
            this._pipelineContext.isAsync && this._checkIsReady(n)
        } catch (s) {
            this._processCompilationErrors(s, n)
        }
    }
    ,
    i.prototype._getShaderCodeAndErrorLine = function(e, t, r) {
        var n = r ? /FRAGMENT SHADER ERROR: 0:(\d+?):/ : /VERTEX SHADER ERROR: 0:(\d+?):/
          , o = null;
        if (t && e) {
            var a = t.match(n);
            if (a && a.length === 2) {
                var s = parseInt(a[1])
                  , l = e.split(`
`, -1);
                l.length >= s && (o = "Offending line [" + s + "] in " + (r ? "fragment" : "vertex") + " code: " + l[s - 1])
            }
        }
        return [e, o]
    }
    ,
    i.prototype._processCompilationErrors = function(e, t) {
        var r, n, o, a, s;
        t === void 0 && (t = null),
        this._compilationError = e.message;
        var l = this._attributesNames
          , u = this._fallbacks;
        if (Logger$2.Error("Unable to compile effect:"),
        Logger$2.Error("Uniforms: " + this._uniformsNames.map(function(d) {
            return " " + d
        })),
        Logger$2.Error("Attributes: " + l.map(function(d) {
            return " " + d
        })),
        Logger$2.Error(`Defines:\r
` + this.defines),
        i.LogShaderCodeOnCompilationError) {
            var c = null
              , h = null
              , f = null;
            !((o = this._pipelineContext) === null || o === void 0) && o._getVertexShaderCode() && (r = this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(), this._compilationError, !1),
            f = r[0],
            c = r[1],
            f && (Logger$2.Error("Vertex code:"),
            Logger$2.Error(f))),
            !((a = this._pipelineContext) === null || a === void 0) && a._getFragmentShaderCode() && (n = this._getShaderCodeAndErrorLine((s = this._pipelineContext) === null || s === void 0 ? void 0 : s._getFragmentShaderCode(), this._compilationError, !0),
            f = n[0],
            h = n[1],
            f && (Logger$2.Error("Fragment code:"),
            Logger$2.Error(f))),
            c && Logger$2.Error(c),
            h && Logger$2.Error(h)
        }
        Logger$2.Error("Error: " + this._compilationError),
        t && (this._pipelineContext = t,
        this._isReady = !0,
        this.onError && this.onError(this, this._compilationError),
        this.onErrorObservable.notifyObservers(this)),
        u ? (this._pipelineContext = null,
        u.hasMoreFallbacks ? (this._allFallbacksProcessed = !1,
        Logger$2.Error("Trying next fallback."),
        this.defines = u.reduce(this.defines, this),
        this._prepareEffect()) : (this._allFallbacksProcessed = !0,
        this.onError && this.onError(this, this._compilationError),
        this.onErrorObservable.notifyObservers(this),
        this.onErrorObservable.clear(),
        this._fallbacks && this._fallbacks.unBindMesh())) : this._allFallbacksProcessed = !0
    }
    ,
    Object.defineProperty(i.prototype, "isSupported", {
        get: function() {
            return this._compilationError === ""
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype._bindTexture = function(e, t) {
        this._engine._bindTexture(this._samplers[e], t, e)
    }
    ,
    i.prototype.setTexture = function(e, t) {
        this._engine.setTexture(this._samplers[e], this._uniforms[e], t, e)
    }
    ,
    i.prototype.setDepthStencilTexture = function(e, t) {
        this._engine.setDepthStencilTexture(this._samplers[e], this._uniforms[e], t, e)
    }
    ,
    i.prototype.setTextureArray = function(e, t) {
        var r = e + "Ex";
        if (this._samplerList.indexOf(r + "0") === -1) {
            for (var n = this._samplerList.indexOf(e), o = 1; o < t.length; o++) {
                var a = r + (o - 1).toString();
                this._samplerList.splice(n + o, 0, a)
            }
            for (var s = 0, l = 0, u = this._samplerList; l < u.length; l++) {
                var c = u[l];
                this._samplers[c] = s,
                s += 1
            }
        }
        this._engine.setTextureArray(this._samplers[e], this._uniforms[e], t, e)
    }
    ,
    i.prototype.setTextureFromPostProcess = function(e, t) {
        this._engine.setTextureFromPostProcess(this._samplers[e], t, e)
    }
    ,
    i.prototype.setTextureFromPostProcessOutput = function(e, t) {
        this._engine.setTextureFromPostProcessOutput(this._samplers[e], t, e)
    }
    ,
    i.prototype.bindUniformBuffer = function(e, t) {
        var r = this._uniformBuffersNames[t];
        r === void 0 || i._baseCache[r] === e && this._engine._features.useUBOBindingCache || (i._baseCache[r] = e,
        this._engine.bindUniformBufferBase(e, r, t))
    }
    ,
    i.prototype.bindUniformBlock = function(e, t) {
        this._engine.bindUniformBlock(this._pipelineContext, e, t)
    }
    ,
    i.prototype.setInt = function(e, t) {
        return this._pipelineContext.setInt(e, t),
        this
    }
    ,
    i.prototype.setInt2 = function(e, t, r) {
        return this._pipelineContext.setInt2(e, t, r),
        this
    }
    ,
    i.prototype.setInt3 = function(e, t, r, n) {
        return this._pipelineContext.setInt3(e, t, r, n),
        this
    }
    ,
    i.prototype.setInt4 = function(e, t, r, n, o) {
        return this._pipelineContext.setInt4(e, t, r, n, o),
        this
    }
    ,
    i.prototype.setIntArray = function(e, t) {
        return this._pipelineContext.setIntArray(e, t),
        this
    }
    ,
    i.prototype.setIntArray2 = function(e, t) {
        return this._pipelineContext.setIntArray2(e, t),
        this
    }
    ,
    i.prototype.setIntArray3 = function(e, t) {
        return this._pipelineContext.setIntArray3(e, t),
        this
    }
    ,
    i.prototype.setIntArray4 = function(e, t) {
        return this._pipelineContext.setIntArray4(e, t),
        this
    }
    ,
    i.prototype.setFloatArray = function(e, t) {
        return this._pipelineContext.setArray(e, t),
        this
    }
    ,
    i.prototype.setFloatArray2 = function(e, t) {
        return this._pipelineContext.setArray2(e, t),
        this
    }
    ,
    i.prototype.setFloatArray3 = function(e, t) {
        return this._pipelineContext.setArray3(e, t),
        this
    }
    ,
    i.prototype.setFloatArray4 = function(e, t) {
        return this._pipelineContext.setArray4(e, t),
        this
    }
    ,
    i.prototype.setArray = function(e, t) {
        return this._pipelineContext.setArray(e, t),
        this
    }
    ,
    i.prototype.setArray2 = function(e, t) {
        return this._pipelineContext.setArray2(e, t),
        this
    }
    ,
    i.prototype.setArray3 = function(e, t) {
        return this._pipelineContext.setArray3(e, t),
        this
    }
    ,
    i.prototype.setArray4 = function(e, t) {
        return this._pipelineContext.setArray4(e, t),
        this
    }
    ,
    i.prototype.setMatrices = function(e, t) {
        return this._pipelineContext.setMatrices(e, t),
        this
    }
    ,
    i.prototype.setMatrix = function(e, t) {
        return this._pipelineContext.setMatrix(e, t),
        this
    }
    ,
    i.prototype.setMatrix3x3 = function(e, t) {
        return this._pipelineContext.setMatrix3x3(e, t),
        this
    }
    ,
    i.prototype.setMatrix2x2 = function(e, t) {
        return this._pipelineContext.setMatrix2x2(e, t),
        this
    }
    ,
    i.prototype.setFloat = function(e, t) {
        return this._pipelineContext.setFloat(e, t),
        this
    }
    ,
    i.prototype.setBool = function(e, t) {
        return this._pipelineContext.setInt(e, t ? 1 : 0),
        this
    }
    ,
    i.prototype.setVector2 = function(e, t) {
        return this._pipelineContext.setVector2(e, t),
        this
    }
    ,
    i.prototype.setFloat2 = function(e, t, r) {
        return this._pipelineContext.setFloat2(e, t, r),
        this
    }
    ,
    i.prototype.setVector3 = function(e, t) {
        return this._pipelineContext.setVector3(e, t),
        this
    }
    ,
    i.prototype.setFloat3 = function(e, t, r, n) {
        return this._pipelineContext.setFloat3(e, t, r, n),
        this
    }
    ,
    i.prototype.setVector4 = function(e, t) {
        return this._pipelineContext.setVector4(e, t),
        this
    }
    ,
    i.prototype.setFloat4 = function(e, t, r, n, o) {
        return this._pipelineContext.setFloat4(e, t, r, n, o),
        this
    }
    ,
    i.prototype.setColor3 = function(e, t) {
        return this._pipelineContext.setColor3(e, t),
        this
    }
    ,
    i.prototype.setColor4 = function(e, t, r) {
        return this._pipelineContext.setColor4(e, t, r),
        this
    }
    ,
    i.prototype.setDirectColor4 = function(e, t) {
        return this._pipelineContext.setDirectColor4(e, t),
        this
    }
    ,
    i.prototype.dispose = function() {
        this._pipelineContext && this._pipelineContext.dispose(),
        this._engine._releaseEffect(this)
    }
    ,
    i.RegisterShader = function(e, t, r, n) {
        n === void 0 && (n = ShaderLanguage.GLSL),
        t && (ShaderStore.GetShadersStore(n)[e + "PixelShader"] = t),
        r && (ShaderStore.GetShadersStore(n)[e + "VertexShader"] = r)
    }
    ,
    i.ResetCache = function() {
        i._baseCache = {}
    }
    ,
    i.LogShaderCodeOnCompilationError = !0,
    i._uniqueIdSeed = 0,
    i._baseCache = {},
    i.ShadersStore = ShaderStore.ShadersStore,
    i.IncludesShadersStore = ShaderStore.IncludesShadersStore,
    i
}(), DepthCullingState = function() {
    function i(e) {
        e === void 0 && (e = !0),
        this._isDepthTestDirty = !1,
        this._isDepthMaskDirty = !1,
        this._isDepthFuncDirty = !1,
        this._isCullFaceDirty = !1,
        this._isCullDirty = !1,
        this._isZOffsetDirty = !1,
        this._isFrontFaceDirty = !1,
        e && this.reset()
    }
    return Object.defineProperty(i.prototype, "isDirty", {
        get: function() {
            return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "zOffset", {
        get: function() {
            return this._zOffset
        },
        set: function(e) {
            this._zOffset !== e && (this._zOffset = e,
            this._isZOffsetDirty = !0)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "zOffsetUnits", {
        get: function() {
            return this._zOffsetUnits
        },
        set: function(e) {
            this._zOffsetUnits !== e && (this._zOffsetUnits = e,
            this._isZOffsetDirty = !0)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "cullFace", {
        get: function() {
            return this._cullFace
        },
        set: function(e) {
            this._cullFace !== e && (this._cullFace = e,
            this._isCullFaceDirty = !0)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "cull", {
        get: function() {
            return this._cull
        },
        set: function(e) {
            this._cull !== e && (this._cull = e,
            this._isCullDirty = !0)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "depthFunc", {
        get: function() {
            return this._depthFunc
        },
        set: function(e) {
            this._depthFunc !== e && (this._depthFunc = e,
            this._isDepthFuncDirty = !0)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "depthMask", {
        get: function() {
            return this._depthMask
        },
        set: function(e) {
            this._depthMask !== e && (this._depthMask = e,
            this._isDepthMaskDirty = !0)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "depthTest", {
        get: function() {
            return this._depthTest
        },
        set: function(e) {
            this._depthTest !== e && (this._depthTest = e,
            this._isDepthTestDirty = !0)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "frontFace", {
        get: function() {
            return this._frontFace
        },
        set: function(e) {
            this._frontFace !== e && (this._frontFace = e,
            this._isFrontFaceDirty = !0)
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.reset = function() {
        this._depthMask = !0,
        this._depthTest = !0,
        this._depthFunc = null,
        this._cullFace = null,
        this._cull = null,
        this._zOffset = 0,
        this._zOffsetUnits = 0,
        this._frontFace = null,
        this._isDepthTestDirty = !0,
        this._isDepthMaskDirty = !0,
        this._isDepthFuncDirty = !1,
        this._isCullFaceDirty = !1,
        this._isCullDirty = !1,
        this._isZOffsetDirty = !0,
        this._isFrontFaceDirty = !1
    }
    ,
    i.prototype.apply = function(e) {
        !this.isDirty || (this._isCullDirty && (this.cull ? e.enable(e.CULL_FACE) : e.disable(e.CULL_FACE),
        this._isCullDirty = !1),
        this._isCullFaceDirty && (e.cullFace(this.cullFace),
        this._isCullFaceDirty = !1),
        this._isDepthMaskDirty && (e.depthMask(this.depthMask),
        this._isDepthMaskDirty = !1),
        this._isDepthTestDirty && (this.depthTest ? e.enable(e.DEPTH_TEST) : e.disable(e.DEPTH_TEST),
        this._isDepthTestDirty = !1),
        this._isDepthFuncDirty && (e.depthFunc(this.depthFunc),
        this._isDepthFuncDirty = !1),
        this._isZOffsetDirty && (this.zOffset || this.zOffsetUnits ? (e.enable(e.POLYGON_OFFSET_FILL),
        e.polygonOffset(this.zOffset, this.zOffsetUnits)) : e.disable(e.POLYGON_OFFSET_FILL),
        this._isZOffsetDirty = !1),
        this._isFrontFaceDirty && (e.frontFace(this.frontFace),
        this._isFrontFaceDirty = !1))
    }
    ,
    i
}(), StencilState = function() {
    function i() {
        this.reset()
    }
    return i.prototype.reset = function() {
        this.enabled = !1,
        this.mask = 255,
        this.func = i.ALWAYS,
        this.funcRef = 1,
        this.funcMask = 255,
        this.opStencilFail = i.KEEP,
        this.opDepthFail = i.KEEP,
        this.opStencilDepthPass = i.REPLACE
    }
    ,
    Object.defineProperty(i.prototype, "stencilFunc", {
        get: function() {
            return this.func
        },
        set: function(e) {
            this.func = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "stencilFuncRef", {
        get: function() {
            return this.funcRef
        },
        set: function(e) {
            this.funcRef = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "stencilFuncMask", {
        get: function() {
            return this.funcMask
        },
        set: function(e) {
            this.funcMask = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "stencilOpStencilFail", {
        get: function() {
            return this.opStencilFail
        },
        set: function(e) {
            this.opStencilFail = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "stencilOpDepthFail", {
        get: function() {
            return this.opDepthFail
        },
        set: function(e) {
            this.opDepthFail = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "stencilOpStencilDepthPass", {
        get: function() {
            return this.opStencilDepthPass
        },
        set: function(e) {
            this.opStencilDepthPass = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "stencilMask", {
        get: function() {
            return this.mask
        },
        set: function(e) {
            this.mask = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "stencilTest", {
        get: function() {
            return this.enabled
        },
        set: function(e) {
            this.enabled = e
        },
        enumerable: !1,
        configurable: !0
    }),
    i.ALWAYS = 519,
    i.KEEP = 7680,
    i.REPLACE = 7681,
    i
}(), AlphaState = function() {
    function i() {
        this._blendFunctionParameters = new Array(4),
        this._blendEquationParameters = new Array(2),
        this._blendConstants = new Array(4),
        this._isBlendConstantsDirty = !1,
        this._alphaBlend = !1,
        this._isAlphaBlendDirty = !1,
        this._isBlendFunctionParametersDirty = !1,
        this._isBlendEquationParametersDirty = !1,
        this.reset()
    }
    return Object.defineProperty(i.prototype, "isDirty", {
        get: function() {
            return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty || this._isBlendEquationParametersDirty
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "alphaBlend", {
        get: function() {
            return this._alphaBlend
        },
        set: function(e) {
            this._alphaBlend !== e && (this._alphaBlend = e,
            this._isAlphaBlendDirty = !0)
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.setAlphaBlendConstants = function(e, t, r, n) {
        this._blendConstants[0] === e && this._blendConstants[1] === t && this._blendConstants[2] === r && this._blendConstants[3] === n || (this._blendConstants[0] = e,
        this._blendConstants[1] = t,
        this._blendConstants[2] = r,
        this._blendConstants[3] = n,
        this._isBlendConstantsDirty = !0)
    }
    ,
    i.prototype.setAlphaBlendFunctionParameters = function(e, t, r, n) {
        this._blendFunctionParameters[0] === e && this._blendFunctionParameters[1] === t && this._blendFunctionParameters[2] === r && this._blendFunctionParameters[3] === n || (this._blendFunctionParameters[0] = e,
        this._blendFunctionParameters[1] = t,
        this._blendFunctionParameters[2] = r,
        this._blendFunctionParameters[3] = n,
        this._isBlendFunctionParametersDirty = !0)
    }
    ,
    i.prototype.setAlphaEquationParameters = function(e, t) {
        this._blendEquationParameters[0] === e && this._blendEquationParameters[1] === t || (this._blendEquationParameters[0] = e,
        this._blendEquationParameters[1] = t,
        this._isBlendEquationParametersDirty = !0)
    }
    ,
    i.prototype.reset = function() {
        this._alphaBlend = !1,
        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 = !0,
        this._isBlendFunctionParametersDirty = !1,
        this._isBlendEquationParametersDirty = !1,
        this._isBlendConstantsDirty = !1
    }
    ,
    i.prototype.apply = function(e) {
        !this.isDirty || (this._isAlphaBlendDirty && (this._alphaBlend ? e.enable(e.BLEND) : e.disable(e.BLEND),
        this._isAlphaBlendDirty = !1),
        this._isBlendFunctionParametersDirty && (e.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]),
        this._isBlendFunctionParametersDirty = !1),
        this._isBlendEquationParametersDirty && (e.blendEquationSeparate(this._blendEquationParameters[0], this._blendEquationParameters[1]),
        this._isBlendEquationParametersDirty = !1),
        this._isBlendConstantsDirty && (e.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]),
        this._isBlendConstantsDirty = !1))
    }
    ,
    i
}(), TextureSampler = function() {
    function i() {
        this.samplingMode = -1,
        this._useMipMaps = !0,
        this._cachedWrapU = null,
        this._cachedWrapV = null,
        this._cachedWrapR = null,
        this._cachedAnisotropicFilteringLevel = null,
        this._comparisonFunction = 0
    }
    return Object.defineProperty(i.prototype, "wrapU", {
        get: function() {
            return this._cachedWrapU
        },
        set: function(e) {
            this._cachedWrapU = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "wrapV", {
        get: function() {
            return this._cachedWrapV
        },
        set: function(e) {
            this._cachedWrapV = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "wrapR", {
        get: function() {
            return this._cachedWrapR
        },
        set: function(e) {
            this._cachedWrapR = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "anisotropicFilteringLevel", {
        get: function() {
            return this._cachedAnisotropicFilteringLevel
        },
        set: function(e) {
            this._cachedAnisotropicFilteringLevel = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "comparisonFunction", {
        get: function() {
            return this._comparisonFunction
        },
        set: function(e) {
            this._comparisonFunction = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "useMipMaps", {
        get: function() {
            return this._useMipMaps
        },
        set: function(e) {
            this._useMipMaps = e
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.setParameters = function(e, t, r, n, o, a) {
        return e === void 0 && (e = 1),
        t === void 0 && (t = 1),
        r === void 0 && (r = 1),
        n === void 0 && (n = 1),
        o === void 0 && (o = 2),
        a === void 0 && (a = 0),
        this._cachedWrapU = e,
        this._cachedWrapV = t,
        this._cachedWrapR = r,
        this._cachedAnisotropicFilteringLevel = n,
        this.samplingMode = o,
        this._comparisonFunction = a,
        this
    }
    ,
    i.prototype.compareSampler = function(e) {
        return this._cachedWrapU === e._cachedWrapU && this._cachedWrapV === e._cachedWrapV && this._cachedWrapR === e._cachedWrapR && this._cachedAnisotropicFilteringLevel === e._cachedAnisotropicFilteringLevel && this.samplingMode === e.samplingMode && this._comparisonFunction === e._comparisonFunction && this._useMipMaps === e._useMipMaps
    }
    ,
    i
}(), InternalTextureSource;
(function(i) {
    i[i.Unknown = 0] = "Unknown",
    i[i.Url = 1] = "Url",
    i[i.Temp = 2] = "Temp",
    i[i.Raw = 3] = "Raw",
    i[i.Dynamic = 4] = "Dynamic",
    i[i.RenderTarget = 5] = "RenderTarget",
    i[i.MultiRenderTarget = 6] = "MultiRenderTarget",
    i[i.Cube = 7] = "Cube",
    i[i.CubeRaw = 8] = "CubeRaw",
    i[i.CubePrefiltered = 9] = "CubePrefiltered",
    i[i.Raw3D = 10] = "Raw3D",
    i[i.Raw2DArray = 11] = "Raw2DArray",
    i[i.DepthStencil = 12] = "DepthStencil",
    i[i.CubeRawRGBD = 13] = "CubeRawRGBD",
    i[i.Depth = 14] = "Depth"
}
)(InternalTextureSource || (InternalTextureSource = {}));
var InternalTexture = function(i) {
    __extends(e, i);
    function e(t, r, n) {
        n === void 0 && (n = !1);
        var o = i.call(this) || this;
        return o.isReady = !1,
        o.isCube = !1,
        o.is3D = !1,
        o.is2DArray = !1,
        o.isMultiview = !1,
        o.url = "",
        o.generateMipMaps = !1,
        o.samples = 0,
        o.type = -1,
        o.format = -1,
        o.onLoadedObservable = new Observable,
        o.onErrorObservable = new Observable,
        o.onRebuildCallback = null,
        o.width = 0,
        o.height = 0,
        o.depth = 0,
        o.baseWidth = 0,
        o.baseHeight = 0,
        o.baseDepth = 0,
        o.invertY = !1,
        o._invertVScale = !1,
        o._associatedChannel = -1,
        o._source = InternalTextureSource.Unknown,
        o._buffer = null,
        o._bufferView = null,
        o._bufferViewArray = null,
        o._bufferViewArrayArray = null,
        o._size = 0,
        o._extension = "",
        o._files = null,
        o._workingCanvas = null,
        o._workingContext = null,
        o._cachedCoordinatesMode = null,
        o._isDisabled = !1,
        o._compression = null,
        o._sphericalPolynomial = null,
        o._sphericalPolynomialPromise = null,
        o._sphericalPolynomialComputed = !1,
        o._lodGenerationScale = 0,
        o._lodGenerationOffset = 0,
        o._useSRGBBuffer = !1,
        o._lodTextureHigh = null,
        o._lodTextureMid = null,
        o._lodTextureLow = null,
        o._isRGBD = !1,
        o._linearSpecularLOD = !1,
        o._irradianceTexture = null,
        o._hardwareTexture = null,
        o._references = 1,
        o._gammaSpace = null,
        o._engine = t,
        o._source = r,
        o._uniqueId = e._Counter++,
        n || (o._hardwareTexture = t._createHardwareTexture()),
        o
    }
    return Object.defineProperty(e.prototype, "useMipMaps", {
        get: function() {
            return this.generateMipMaps
        },
        set: function(t) {
            this.generateMipMaps = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "uniqueId", {
        get: function() {
            return this._uniqueId
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getEngine = function() {
        return this._engine
    }
    ,
    Object.defineProperty(e.prototype, "source", {
        get: function() {
            return this._source
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.incrementReferences = function() {
        this._references++
    }
    ,
    e.prototype.updateSize = function(t, r, n) {
        n === void 0 && (n = 1),
        this._engine.updateTextureDimensions(this, t, r, n),
        this.width = t,
        this.height = r,
        this.depth = n,
        this.baseWidth = t,
        this.baseHeight = r,
        this.baseDepth = n,
        this._size = t * r * n
    }
    ,
    e.prototype._rebuild = function() {
        var t = this, r;
        if (this.isReady = !1,
        this._cachedCoordinatesMode = null,
        this._cachedWrapU = null,
        this._cachedWrapV = null,
        this._cachedWrapR = null,
        this._cachedAnisotropicFilteringLevel = null,
        this.onRebuildCallback) {
            var n = this.onRebuildCallback(this)
              , o = function(s) {
                s._swapAndDie(t, !1),
                t.isReady = n.isReady
            };
            n.isAsync ? n.proxy.then(o) : o(n.proxy);
            return
        }
        var a;
        switch (this.source) {
        case InternalTextureSource.Temp:
            break;
        case InternalTextureSource.Url:
            a = this._engine.createTexture((r = this._originalUrl) !== null && r !== void 0 ? r : this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function() {
                a._swapAndDie(t, !1),
                t.isReady = !0
            }, null, this._buffer, void 0, this.format, this._extension, void 0, void 0, void 0, this._useSRGBBuffer);
            return;
        case InternalTextureSource.Raw:
            a = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression, this.type),
            a._swapAndDie(this, !1),
            this.isReady = !0;
            break;
        case InternalTextureSource.Raw3D:
            a = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression, this.type),
            a._swapAndDie(this, !1),
            this.isReady = !0;
            break;
        case InternalTextureSource.Raw2DArray:
            a = this._engine.createRawTexture2DArray(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression, this.type),
            a._swapAndDie(this, !1),
            this.isReady = !0;
            break;
        case InternalTextureSource.Dynamic:
            a = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode),
            a._swapAndDie(this, !1),
            this._engine.updateDynamicTexture(this, this._engine.getRenderingCanvas(), this.invertY, void 0, void 0, !0);
            break;
        case InternalTextureSource.Cube:
            a = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function() {
                a._swapAndDie(t, !1),
                t.isReady = !0
            }, null, this.format, this._extension, !1, 0, 0, null, void 0, this._useSRGBBuffer);
            return;
        case InternalTextureSource.CubeRaw:
            a = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression),
            a._swapAndDie(this, !1),
            this.isReady = !0;
            break;
        case InternalTextureSource.CubeRawRGBD:
            return;
        case InternalTextureSource.CubePrefiltered:
            a = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function(s) {
                s && s._swapAndDie(t, !1),
                t.isReady = !0
            }, null, this.format, this._extension),
            a._sphericalPolynomial = this._sphericalPolynomial;
            return
        }
    }
    ,
    e.prototype._swapAndDie = function(t, r) {
        var n;
        r === void 0 && (r = !0),
        (n = this._hardwareTexture) === null || n === void 0 || n.setUsage(t._source, this.generateMipMaps, this.isCube, this.width, this.height),
        t._hardwareTexture = this._hardwareTexture,
        r && (t._isRGBD = this._isRGBD),
        this._lodTextureHigh && (t._lodTextureHigh && t._lodTextureHigh.dispose(),
        t._lodTextureHigh = this._lodTextureHigh),
        this._lodTextureMid && (t._lodTextureMid && t._lodTextureMid.dispose(),
        t._lodTextureMid = this._lodTextureMid),
        this._lodTextureLow && (t._lodTextureLow && t._lodTextureLow.dispose(),
        t._lodTextureLow = this._lodTextureLow),
        this._irradianceTexture && (t._irradianceTexture && t._irradianceTexture.dispose(),
        t._irradianceTexture = this._irradianceTexture);
        var o = this._engine.getLoadedTexturesCache()
          , a = o.indexOf(this);
        a !== -1 && o.splice(a, 1);
        var a = o.indexOf(t);
        a === -1 && o.push(t)
    }
    ,
    e.prototype.dispose = function() {
        this._references--,
        this.onLoadedObservable.clear(),
        this.onErrorObservable.clear(),
        this._references === 0 && (this._engine._releaseTexture(this),
        this._hardwareTexture = null)
    }
    ,
    e._Counter = 0,
    e
}(TextureSampler), WebGLShaderProcessor = function() {
    function i() {
        this.shaderLanguage = ShaderLanguage.GLSL
    }
    return i.prototype.postProcessor = function(e, t, r, n, o) {
        if (!o.getCaps().drawBuffersExtension) {
            var a = /#extension.+GL_EXT_draw_buffers.+(enable|require)/g;
            e = e.replace(a, "")
        }
        return e
    }
    ,
    i
}(), WebGL2ShaderProcessor = function() {
    function i() {
        this.shaderLanguage = ShaderLanguage.GLSL
    }
    return i.prototype.attributeProcessor = function(e) {
        return e.replace("attribute", "in")
    }
    ,
    i.prototype.varyingProcessor = function(e, t) {
        return e.replace("varying", t ? "in" : "out")
    }
    ,
    i.prototype.postProcessor = function(e, t, r, n, o) {
        var a = e.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1
          , s = /#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
        if (e = e.replace(s, ""),
        e = e.replace(/texture2D\s*\(/g, "texture("),
        r)
            e = e.replace(/texture2DLodEXT\s*\(/g, "textureLod("),
            e = e.replace(/textureCubeLodEXT\s*\(/g, "textureLod("),
            e = e.replace(/textureCube\s*\(/g, "texture("),
            e = e.replace(/gl_FragDepthEXT/g, "gl_FragDepth"),
            e = e.replace(/gl_FragColor/g, "glFragColor"),
            e = e.replace(/gl_FragData/g, "glFragData"),
            e = e.replace(/void\s+?main\s*\(/g, (a ? "" : `out vec4 glFragColor;
`) + "void main(");
        else {
            var l = t.indexOf("#define MULTIVIEW") !== -1;
            if (l)
                return `#extension GL_OVR_multiview2 : require
layout (num_views = 2) in;
` + e
        }
        return e
    }
    ,
    i
}(), DataBuffer = function() {
    function i() {
        this.references = 0,
        this.capacity = 0,
        this.is32Bits = !1,
        this.uniqueId = i._Counter++
    }
    return Object.defineProperty(i.prototype, "underlyingResource", {
        get: function() {
            return null
        },
        enumerable: !1,
        configurable: !0
    }),
    i._Counter = 0,
    i
}(), WebGLDataBuffer = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this) || this;
        return r._buffer = t,
        r
    }
    return Object.defineProperty(e.prototype, "underlyingResource", {
        get: function() {
            return this._buffer
        },
        enumerable: !1,
        configurable: !0
    }),
    e
}(DataBuffer), WebGLPipelineContext = function() {
    function i() {
        this._valueCache = {},
        this.vertexCompilationError = null,
        this.fragmentCompilationError = null,
        this.programLinkError = null,
        this.programValidationError = null
    }
    return Object.defineProperty(i.prototype, "isAsync", {
        get: function() {
            return this.isParallelCompiled
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "isReady", {
        get: function() {
            return this.program ? this.isParallelCompiled ? this.engine._isRenderingStateCompiled(this) : !0 : !1
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype._handlesSpectorRebuildCallback = function(e) {
        e && this.program && e(this.program)
    }
    ,
    i.prototype._fillEffectInformation = function(e, t, r, n, o, a, s, l) {
        var u = this.engine;
        if (u.supportsUniformBuffers)
            for (var c in t)
                e.bindUniformBlock(c, t[c]);
        var h = this.engine.getUniforms(this, r);
        h.forEach(function(v, y) {
            n[r[y]] = v
        }),
        this._uniforms = n;
        var f;
        for (f = 0; f < o.length; f++) {
            var d = e.getUniform(o[f]);
            d == null && (o.splice(f, 1),
            f--)
        }
        o.forEach(function(v, y) {
            a[v] = y
        });
        for (var _ = 0, g = u.getAttributes(this, s); _ < g.length; _++) {
            var m = g[_];
            l.push(m)
        }
    }
    ,
    i.prototype.dispose = function() {
        this._uniforms = {}
    }
    ,
    i.prototype._cacheMatrix = function(e, t) {
        var r = this._valueCache[e]
          , n = t.updateFlag;
        return r !== void 0 && r === n ? !1 : (this._valueCache[e] = n,
        !0)
    }
    ,
    i.prototype._cacheFloat2 = function(e, t, r) {
        var n = this._valueCache[e];
        if (!n || n.length !== 2)
            return n = [t, r],
            this._valueCache[e] = n,
            !0;
        var o = !1;
        return n[0] !== t && (n[0] = t,
        o = !0),
        n[1] !== r && (n[1] = r,
        o = !0),
        o
    }
    ,
    i.prototype._cacheFloat3 = function(e, t, r, n) {
        var o = this._valueCache[e];
        if (!o || o.length !== 3)
            return o = [t, r, n],
            this._valueCache[e] = o,
            !0;
        var a = !1;
        return o[0] !== t && (o[0] = t,
        a = !0),
        o[1] !== r && (o[1] = r,
        a = !0),
        o[2] !== n && (o[2] = n,
        a = !0),
        a
    }
    ,
    i.prototype._cacheFloat4 = function(e, t, r, n, o) {
        var a = this._valueCache[e];
        if (!a || a.length !== 4)
            return a = [t, r, n, o],
            this._valueCache[e] = a,
            !0;
        var s = !1;
        return a[0] !== t && (a[0] = t,
        s = !0),
        a[1] !== r && (a[1] = r,
        s = !0),
        a[2] !== n && (a[2] = n,
        s = !0),
        a[3] !== o && (a[3] = o,
        s = !0),
        s
    }
    ,
    i.prototype.setInt = function(e, t) {
        var r = this._valueCache[e];
        r !== void 0 && r === t || this.engine.setInt(this._uniforms[e], t) && (this._valueCache[e] = t)
    }
    ,
    i.prototype.setInt2 = function(e, t, r) {
        this._cacheFloat2(e, t, r) && (this.engine.setInt2(this._uniforms[e], t, r) || (this._valueCache[e] = null))
    }
    ,
    i.prototype.setInt3 = function(e, t, r, n) {
        this._cacheFloat3(e, t, r, n) && (this.engine.setInt3(this._uniforms[e], t, r, n) || (this._valueCache[e] = null))
    }
    ,
    i.prototype.setInt4 = function(e, t, r, n, o) {
        this._cacheFloat4(e, t, r, n, o) && (this.engine.setInt4(this._uniforms[e], t, r, n, o) || (this._valueCache[e] = null))
    }
    ,
    i.prototype.setIntArray = function(e, t) {
        this._valueCache[e] = null,
        this.engine.setIntArray(this._uniforms[e], t)
    }
    ,
    i.prototype.setIntArray2 = function(e, t) {
        this._valueCache[e] = null,
        this.engine.setIntArray2(this._uniforms[e], t)
    }
    ,
    i.prototype.setIntArray3 = function(e, t) {
        this._valueCache[e] = null,
        this.engine.setIntArray3(this._uniforms[e], t)
    }
    ,
    i.prototype.setIntArray4 = function(e, t) {
        this._valueCache[e] = null,
        this.engine.setIntArray4(this._uniforms[e], t)
    }
    ,
    i.prototype.setArray = function(e, t) {
        this._valueCache[e] = null,
        this.engine.setArray(this._uniforms[e], t)
    }
    ,
    i.prototype.setArray2 = function(e, t) {
        this._valueCache[e] = null,
        this.engine.setArray2(this._uniforms[e], t)
    }
    ,
    i.prototype.setArray3 = function(e, t) {
        this._valueCache[e] = null,
        this.engine.setArray3(this._uniforms[e], t)
    }
    ,
    i.prototype.setArray4 = function(e, t) {
        this._valueCache[e] = null,
        this.engine.setArray4(this._uniforms[e], t)
    }
    ,
    i.prototype.setMatrices = function(e, t) {
        !t || (this._valueCache[e] = null,
        this.engine.setMatrices(this._uniforms[e], t))
    }
    ,
    i.prototype.setMatrix = function(e, t) {
        this._cacheMatrix(e, t) && (this.engine.setMatrices(this._uniforms[e], t.toArray()) || (this._valueCache[e] = null))
    }
    ,
    i.prototype.setMatrix3x3 = function(e, t) {
        this._valueCache[e] = null,
        this.engine.setMatrix3x3(this._uniforms[e], t)
    }
    ,
    i.prototype.setMatrix2x2 = function(e, t) {
        this._valueCache[e] = null,
        this.engine.setMatrix2x2(this._uniforms[e], t)
    }
    ,
    i.prototype.setFloat = function(e, t) {
        var r = this._valueCache[e];
        r !== void 0 && r === t || this.engine.setFloat(this._uniforms[e], t) && (this._valueCache[e] = t)
    }
    ,
    i.prototype.setVector2 = function(e, t) {
        this._cacheFloat2(e, t.x, t.y) && (this.engine.setFloat2(this._uniforms[e], t.x, t.y) || (this._valueCache[e] = null))
    }
    ,
    i.prototype.setFloat2 = function(e, t, r) {
        this._cacheFloat2(e, t, r) && (this.engine.setFloat2(this._uniforms[e], t, r) || (this._valueCache[e] = null))
    }
    ,
    i.prototype.setVector3 = function(e, t) {
        this._cacheFloat3(e, t.x, t.y, t.z) && (this.engine.setFloat3(this._uniforms[e], t.x, t.y, t.z) || (this._valueCache[e] = null))
    }
    ,
    i.prototype.setFloat3 = function(e, t, r, n) {
        this._cacheFloat3(e, t, r, n) && (this.engine.setFloat3(this._uniforms[e], t, r, n) || (this._valueCache[e] = null))
    }
    ,
    i.prototype.setVector4 = function(e, t) {
        this._cacheFloat4(e, t.x, t.y, t.z, t.w) && (this.engine.setFloat4(this._uniforms[e], t.x, t.y, t.z, t.w) || (this._valueCache[e] = null))
    }
    ,
    i.prototype.setFloat4 = function(e, t, r, n, o) {
        this._cacheFloat4(e, t, r, n, o) && (this.engine.setFloat4(this._uniforms[e], t, r, n, o) || (this._valueCache[e] = null))
    }
    ,
    i.prototype.setColor3 = function(e, t) {
        this._cacheFloat3(e, t.r, t.g, t.b) && (this.engine.setFloat3(this._uniforms[e], t.r, t.g, t.b) || (this._valueCache[e] = null))
    }
    ,
    i.prototype.setColor4 = function(e, t, r) {
        this._cacheFloat4(e, t.r, t.g, t.b, r) && (this.engine.setFloat4(this._uniforms[e], t.r, t.g, t.b, r) || (this._valueCache[e] = null))
    }
    ,
    i.prototype.setDirectColor4 = function(e, t) {
        this._cacheFloat4(e, t.r, t.g, t.b, t.a) && (this.engine.setFloat4(this._uniforms[e], t.r, t.g, t.b, t.a) || (this._valueCache[e] = null))
    }
    ,
    i.prototype._getVertexShaderCode = function() {
        return this.vertexShader ? this.engine._getShaderSource(this.vertexShader) : null
    }
    ,
    i.prototype._getFragmentShaderCode = function() {
        return this.fragmentShader ? this.engine._getShaderSource(this.fragmentShader) : null
    }
    ,
    i
}(), PerformanceConfigurator = function() {
    function i() {}
    return i.SetMatrixPrecision = function(e) {
        if (i.MatrixTrackPrecisionChange = !1,
        e && !i.MatrixUse64Bits && i.MatrixTrackedMatrices)
            for (var t = 0; t < i.MatrixTrackedMatrices.length; ++t) {
                var r = i.MatrixTrackedMatrices[t]
                  , n = r._m;
                r._m = new Array(16);
                for (var o = 0; o < 16; ++o)
                    r._m[o] = n[o]
            }
        i.MatrixUse64Bits = e,
        i.MatrixCurrentType = i.MatrixUse64Bits ? Array : Float32Array,
        i.MatrixTrackedMatrices = null
    }
    ,
    i.MatrixUse64Bits = !1,
    i.MatrixTrackPrecisionChange = !0,
    i.MatrixCurrentType = Float32Array,
    i.MatrixTrackedMatrices = [],
    i
}(), WebGLHardwareTexture = function() {
    function i(e, t) {
        if (e === void 0 && (e = null),
        this._MSAARenderBuffer = null,
        this._context = t,
        !e && (e = t.createTexture(),
        !e))
            throw new Error("Unable to create webGL texture");
        this.set(e)
    }
    return Object.defineProperty(i.prototype, "underlyingResource", {
        get: function() {
            return this._webGLTexture
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.setUsage = function(e, t, r, n, o) {}
    ,
    i.prototype.set = function(e) {
        this._webGLTexture = e
    }
    ,
    i.prototype.reset = function() {
        this._webGLTexture = null,
        this._MSAARenderBuffer = null
    }
    ,
    i.prototype.release = function() {
        this._MSAARenderBuffer && (this._context.deleteRenderbuffer(this._MSAARenderBuffer),
        this._MSAARenderBuffer = null),
        this._webGLTexture && this._context.deleteTexture(this._webGLTexture),
        this.reset()
    }
    ,
    i
}(), DrawWrapper = function() {
    function i(e, t) {
        t === void 0 && (t = !0),
        this.effect = null,
        this.defines = null,
        this.drawContext = e.createDrawContext(),
        t && (this.materialContext = e.createMaterialContext())
    }
    return i.IsWrapper = function(e) {
        return e.getPipelineContext === void 0
    }
    ,
    i.GetEffect = function(e) {
        return e.getPipelineContext === void 0 ? e.effect : e
    }
    ,
    i.prototype.setEffect = function(e, t, r) {
        var n;
        r === void 0 && (r = !0),
        this.effect = e,
        t !== void 0 && (this.defines = t),
        r && ((n = this.drawContext) === null || n === void 0 || n.reset())
    }
    ,
    i.prototype.dispose = function() {
        var e;
        (e = this.drawContext) === null || e === void 0 || e.dispose()
    }
    ,
    i
}(), StencilStateComposer = function() {
    function i(e) {
        e === void 0 && (e = !0),
        this._isStencilTestDirty = !1,
        this._isStencilMaskDirty = !1,
        this._isStencilFuncDirty = !1,
        this._isStencilOpDirty = !1,
        this.useStencilGlobalOnly = !1,
        e && this.reset()
    }
    return Object.defineProperty(i.prototype, "isDirty", {
        get: function() {
            return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "func", {
        get: function() {
            return this._func
        },
        set: function(e) {
            this._func !== e && (this._func = e,
            this._isStencilFuncDirty = !0)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "funcRef", {
        get: function() {
            return this._funcRef
        },
        set: function(e) {
            this._funcRef !== e && (this._funcRef = e,
            this._isStencilFuncDirty = !0)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "funcMask", {
        get: function() {
            return this._funcMask
        },
        set: function(e) {
            this._funcMask !== e && (this._funcMask = e,
            this._isStencilFuncDirty = !0)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "opStencilFail", {
        get: function() {
            return this._opStencilFail
        },
        set: function(e) {
            this._opStencilFail !== e && (this._opStencilFail = e,
            this._isStencilOpDirty = !0)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "opDepthFail", {
        get: function() {
            return this._opDepthFail
        },
        set: function(e) {
            this._opDepthFail !== e && (this._opDepthFail = e,
            this._isStencilOpDirty = !0)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "opStencilDepthPass", {
        get: function() {
            return this._opStencilDepthPass
        },
        set: function(e) {
            this._opStencilDepthPass !== e && (this._opStencilDepthPass = e,
            this._isStencilOpDirty = !0)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "mask", {
        get: function() {
            return this._mask
        },
        set: function(e) {
            this._mask !== e && (this._mask = e,
            this._isStencilMaskDirty = !0)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "enabled", {
        get: function() {
            return this._enabled
        },
        set: function(e) {
            this._enabled !== e && (this._enabled = e,
            this._isStencilTestDirty = !0)
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.reset = function() {
        var e;
        this.stencilMaterial = void 0,
        (e = this.stencilGlobal) === null || e === void 0 || e.reset(),
        this._isStencilTestDirty = !0,
        this._isStencilMaskDirty = !0,
        this._isStencilFuncDirty = !0,
        this._isStencilOpDirty = !0
    }
    ,
    i.prototype.apply = function(e) {
        var t;
        if (!!e) {
            var r = !this.useStencilGlobalOnly && !!(!((t = this.stencilMaterial) === null || t === void 0) && t.enabled);
            this.enabled = r ? this.stencilMaterial.enabled : this.stencilGlobal.enabled,
            this.func = r ? this.stencilMaterial.func : this.stencilGlobal.func,
            this.funcRef = r ? this.stencilMaterial.funcRef : this.stencilGlobal.funcRef,
            this.funcMask = r ? this.stencilMaterial.funcMask : this.stencilGlobal.funcMask,
            this.opStencilFail = r ? this.stencilMaterial.opStencilFail : this.stencilGlobal.opStencilFail,
            this.opDepthFail = r ? this.stencilMaterial.opDepthFail : this.stencilGlobal.opDepthFail,
            this.opStencilDepthPass = r ? this.stencilMaterial.opStencilDepthPass : this.stencilGlobal.opStencilDepthPass,
            this.mask = r ? this.stencilMaterial.mask : this.stencilGlobal.mask,
            this.isDirty && (this._isStencilTestDirty && (this.enabled ? e.enable(e.STENCIL_TEST) : e.disable(e.STENCIL_TEST),
            this._isStencilTestDirty = !1),
            this._isStencilMaskDirty && (e.stencilMask(this.mask),
            this._isStencilMaskDirty = !1),
            this._isStencilFuncDirty && (e.stencilFunc(this.func, this.funcRef, this.funcMask),
            this._isStencilFuncDirty = !1),
            this._isStencilOpDirty && (e.stencilOp(this.opStencilFail, this.opDepthFail, this.opStencilDepthPass),
            this._isStencilOpDirty = !1))
        }
    }
    ,
    i
}(), BufferPointer = function() {
    function i() {}
    return i
}(), ThinEngine = function() {
    function i(e, t, r, n) {
        var o = this;
        this.forcePOTTextures = !1,
        this.isFullscreen = !1,
        this.cullBackFaces = null,
        this.renderEvenInBackground = !0,
        this.preventCacheWipeBetweenFrames = !1,
        this.validateShaderPrograms = !1,
        this._useReverseDepthBuffer = !1,
        this.isNDCHalfZRange = !1,
        this.hasOriginBottomLeft = !0,
        this.disableUniformBuffers = !1,
        this.onDisposeObservable = new Observable,
        this._frameId = 0,
        this._uniformBuffers = new Array,
        this._storageBuffers = new Array,
        this._webGLVersion = 1,
        this._windowIsBackground = !1,
        this._highPrecisionShadersAllowed = !0,
        this._badOS = !1,
        this._badDesktopOS = !1,
        this._renderingQueueLaunched = !1,
        this._activeRenderLoops = new Array,
        this.onContextLostObservable = new Observable,
        this.onContextRestoredObservable = new Observable,
        this._contextWasLost = !1,
        this._doNotHandleContextLost = !1,
        this.disableVertexArrayObjects = !1,
        this._colorWrite = !0,
        this._colorWriteChanged = !0,
        this._depthCullingState = new DepthCullingState,
        this._stencilStateComposer = new StencilStateComposer,
        this._stencilState = new StencilState,
        this._alphaState = new AlphaState,
        this._alphaMode = 1,
        this._alphaEquation = 0,
        this._internalTexturesCache = new Array,
        this._renderTargetWrapperCache = new Array,
        this._activeChannel = 0,
        this._currentTextureChannel = -1,
        this._boundTexturesCache = {},
        this._compiledEffects = {},
        this._vertexAttribArraysEnabled = [],
        this._uintIndicesCurrentlySet = !1,
        this._currentBoundBuffer = new Array,
        this._currentFramebuffer = null,
        this._dummyFramebuffer = null,
        this._currentBufferPointers = new Array,
        this._currentInstanceLocations = new Array,
        this._currentInstanceBuffers = new Array,
        this._vaoRecordInProgress = !1,
        this._mustWipeVertexAttributes = !1,
        this._nextFreeTextureSlots = new Array,
        this._maxSimultaneousTextures = 0,
        this._activeRequests = new Array,
        this._transformTextureUrl = null,
        this.hostInformation = {
            isMobile: !1
        },
        this.premultipliedAlpha = !0,
        this.onBeforeTextureInitObservable = new Observable,
        this._isWebGPU = !1,
        this._snapshotRenderingMode = 0,
        this._viewportCached = {
            x: 0,
            y: 0,
            z: 0,
            w: 0
        },
        this._unpackFlipYCached = null,
        this.enableUnpackFlipYCached = !0,
        this._boundUniforms = {};
        var a = null;
        if (r = r || {},
        this._stencilStateComposer.stencilGlobal = this._stencilState,
        PerformanceConfigurator.SetMatrixPrecision(!!r.useHighPrecisionMatrix),
        !!e) {
            if (n = n || r.adaptToDeviceRatio || !1,
            e.getContext) {
                if (a = e,
                this._renderingCanvas = a,
                t !== void 0 && (r.antialias = t),
                r.deterministicLockstep === void 0 && (r.deterministicLockstep = !1),
                r.lockstepMaxSteps === void 0 && (r.lockstepMaxSteps = 4),
                r.timeStep === void 0 && (r.timeStep = 1 / 60),
                r.preserveDrawingBuffer === void 0 && (r.preserveDrawingBuffer = !1),
                r.audioEngine === void 0 && (r.audioEngine = !0),
                r.audioEngineOptions !== void 0 && r.audioEngineOptions.audioContext !== void 0 && (this._audioContext = r.audioEngineOptions.audioContext),
                r.audioEngineOptions !== void 0 && r.audioEngineOptions.audioDestination !== void 0 && (this._audioDestination = r.audioEngineOptions.audioDestination),
                r.stencil === void 0 && (r.stencil = !0),
                r.premultipliedAlpha === !1 && (this.premultipliedAlpha = !1),
                r.xrCompatible === void 0 && (r.xrCompatible = !0),
                this._doNotHandleContextLost = !!r.doNotHandleContextLost,
                navigator && navigator.userAgent) {
                    this._checkForMobile = function() {
                        var x = navigator.userAgent;
                        o.hostInformation.isMobile = x.indexOf("Mobile") !== -1 || x.indexOf("Mac") !== -1 && IsDocumentAvailable() && "ontouchend"in document
                    }
                    ,
                    this._checkForMobile(),
                    IsWindowObjectExist() && window.addEventListener("resize", this._checkForMobile);
                    for (var s = navigator.userAgent, l = 0, u = i.ExceptionList; l < u.length; l++) {
                        var c = u[l]
                          , h = c.key
                          , f = c.targets
                          , d = new RegExp(h);
                        if (d.test(s)) {
                            if (c.capture && c.captureConstraint) {
                                var _ = c.capture
                                  , g = c.captureConstraint
                                  , m = new RegExp(_)
                                  , v = m.exec(s);
                                if (v && v.length > 0) {
                                    var y = parseInt(v[v.length - 1]);
                                    if (y >= g)
                                        continue
                                }
                            }
                            for (var b = 0, T = f; b < T.length; b++) {
                                var C = T[b];
                                switch (C) {
                                case "uniformBuffer":
                                    this.disableUniformBuffers = !0;
                                    break;
                                case "vao":
                                    this.disableVertexArrayObjects = !0;
                                    break
                                }
                            }
                        }
                    }
                }
                if (this._doNotHandleContextLost || (this._onContextLost = function(x) {
                    x.preventDefault(),
                    o._contextWasLost = !0,
                    Logger$2.Warn("WebGL context lost."),
                    o.onContextLostObservable.notifyObservers(o)
                }
                ,
                this._onContextRestored = function() {
                    o._restoreEngineAfterContextLost(o._initGLContext.bind(o))
                }
                ,
                a.addEventListener("webglcontextlost", this._onContextLost, !1),
                a.addEventListener("webglcontextrestored", this._onContextRestored, !1),
                r.powerPreference = "high-performance"),
                this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent),
                this._badDesktopOS && (r.xrCompatible = !1),
                !r.disableWebGL2Support)
                    try {
                        this._gl = a.getContext("webgl2", r) || a.getContext("experimental-webgl2", r),
                        this._gl && (this._webGLVersion = 2,
                        this._shaderPlatformName = "WEBGL2",
                        this._gl.deleteQuery || (this._webGLVersion = 1,
                        this._shaderPlatformName = "WEBGL1"))
                    } catch {}
                if (!this._gl) {
                    if (!a)
                        throw new Error("The provided canvas is null or undefined.");
                    try {
                        this._gl = a.getContext("webgl", r) || a.getContext("experimental-webgl", r)
                    } catch {
                        throw new Error("WebGL not supported")
                    }
                }
                if (!this._gl)
                    throw new Error("WebGL not supported")
            } else {
                this._gl = e,
                this._renderingCanvas = this._gl.canvas,
                this._gl.renderbufferStorageMultisample ? (this._webGLVersion = 2,
                this._shaderPlatformName = "WEBGL2") : this._shaderPlatformName = "WEBGL1";
                var A = this._gl.getContextAttributes();
                A && (r.stencil = A.stencil)
            }
            this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, this._gl.NONE),
            r.useHighPrecisionFloats !== void 0 && (this._highPrecisionShadersAllowed = r.useHighPrecisionFloats);
            var S = IsWindowObjectExist() && window.devicePixelRatio || 1
              , P = r.limitDeviceRatio || S;
            this._hardwareScalingLevel = n ? 1 / Math.min(P, S) : 1,
            this.resize(),
            this._isStencilEnable = !!r.stencil,
            this._initGLContext(),
            this._initFeatures();
            for (var R = 0; R < this._caps.maxVertexAttribs; R++)
                this._currentBufferPointers[R] = new BufferPointer;
            this._shaderProcessor = this.webGLVersion > 1 ? new WebGL2ShaderProcessor : new WebGLShaderProcessor,
            this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent),
            this._creationOptions = r;
            var M = "Babylon.js v" + i.Version;
            console.log(M + (" - " + this.description)),
            this._renderingCanvas && this._renderingCanvas.setAttribute && this._renderingCanvas.setAttribute("data-engine", M)
        }
    }
    return Object.defineProperty(i, "NpmPackage", {
        get: function() {
            return "babylonjs@5.0.0-alpha.63"
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i, "Version", {
        get: function() {
            return "5.0.0-alpha.63"
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "description", {
        get: function() {
            var e = this.name + this.webGLVersion;
            return this._caps.parallelShaderCompile && (e += " - Parallel shader compilation"),
            e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "name", {
        get: function() {
            return "WebGL"
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "version", {
        get: function() {
            return this._webGLVersion
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i, "ShadersRepository", {
        get: function() {
            return Effect.ShadersRepository
        },
        set: function(e) {
            Effect.ShadersRepository = e
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype._getShaderProcessor = function(e) {
        return this._shaderProcessor
    }
    ,
    Object.defineProperty(i.prototype, "useReverseDepthBuffer", {
        get: function() {
            return this._useReverseDepthBuffer
        },
        set: function(e) {
            e !== this._useReverseDepthBuffer && (this._useReverseDepthBuffer = e,
            e ? this._depthCullingState.depthFunc = 518 : this._depthCullingState.depthFunc = 515)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "frameId", {
        get: function() {
            return this._frameId
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "supportsUniformBuffers", {
        get: function() {
            return this.webGLVersion > 1 && !this.disableUniformBuffers
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "_shouldUseHighPrecisionShader", {
        get: function() {
            return !!(this._caps.highPrecisionShaderSupported && this._highPrecisionShadersAllowed)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "needPOTTextures", {
        get: function() {
            return this._webGLVersion < 2 || this.forcePOTTextures
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "activeRenderLoops", {
        get: function() {
            return this._activeRenderLoops
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "doNotHandleContextLost", {
        get: function() {
            return this._doNotHandleContextLost
        },
        set: function(e) {
            this._doNotHandleContextLost = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "_supportsHardwareTextureRescaling", {
        get: function() {
            return !1
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "framebufferDimensionsObject", {
        set: function(e) {
            this._framebufferDimensionsObject = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "currentViewport", {
        get: function() {
            return this._cachedViewport
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "emptyTexture", {
        get: function() {
            return this._emptyTexture || (this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, 5, !1, !1, 1)),
            this._emptyTexture
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "emptyTexture3D", {
        get: function() {
            return this._emptyTexture3D || (this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, 5, !1, !1, 1)),
            this._emptyTexture3D
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "emptyTexture2DArray", {
        get: function() {
            return this._emptyTexture2DArray || (this._emptyTexture2DArray = this.createRawTexture2DArray(new Uint8Array(4), 1, 1, 1, 5, !1, !1, 1)),
            this._emptyTexture2DArray
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "emptyCubeTexture", {
        get: function() {
            if (!this._emptyCubeTexture) {
                var e = new Uint8Array(4)
                  , t = [e, e, e, e, e, e];
                this._emptyCubeTexture = this.createRawCubeTexture(t, 1, 5, 0, !1, !1, 1)
            }
            return this._emptyCubeTexture
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "isWebGPU", {
        get: function() {
            return this._isWebGPU
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "shaderPlatformName", {
        get: function() {
            return this._shaderPlatformName
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "snapshotRendering", {
        get: function() {
            return !1
        },
        set: function(e) {},
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "snapshotRenderingMode", {
        get: function() {
            return this._snapshotRenderingMode
        },
        set: function(e) {
            this._snapshotRenderingMode = e
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.snapshotRenderingReset = function() {
        this.snapshotRendering = !1
    }
    ,
    i._createCanvas = function(e, t) {
        if (typeof document == "undefined")
            return new OffscreenCanvas(e,t);
        var r = document.createElement("canvas");
        return r.width = e,
        r.height = t,
        r
    }
    ,
    i.prototype.createCanvas = function(e, t) {
        return i._createCanvas(e, t)
    }
    ,
    i.prototype.createCanvasImage = function() {
        return document.createElement("img")
    }
    ,
    i.prototype._restoreEngineAfterContextLost = function(e) {
        var t = this;
        setTimeout(function() {
            return __awaiter(t, void 0, void 0, function() {
                var r, n, o, a, s;
                return __generator(this, function(l) {
                    switch (l.label) {
                    case 0:
                        return this._dummyFramebuffer = null,
                        r = this._depthCullingState.depthTest,
                        n = this._depthCullingState.depthFunc,
                        o = this._depthCullingState.depthMask,
                        a = this._stencilState.stencilTest,
                        [4, e()];
                    case 1:
                        return l.sent(),
                        this._rebuildEffects(),
                        (s = this._rebuildComputeEffects) === null || s === void 0 || s.call(this),
                        this._rebuildInternalTextures(),
                        this._rebuildRenderTargetWrappers(),
                        this._rebuildBuffers(),
                        this.wipeCaches(!0),
                        this._depthCullingState.depthTest = r,
                        this._depthCullingState.depthFunc = n,
                        this._depthCullingState.depthMask = o,
                        this._stencilState.stencilTest = a,
                        Logger$2.Warn(this.name + " context successfully restored."),
                        this.onContextRestoredObservable.notifyObservers(this),
                        this._contextWasLost = !1,
                        [2]
                    }
                })
            })
        }, 0)
    }
    ,
    i.prototype._sharedInit = function(e, t, r) {
        this._renderingCanvas = e
    }
    ,
    i.prototype._getShaderProcessingContext = function(e) {
        return null
    }
    ,
    i.prototype._rebuildInternalTextures = function() {
        for (var e = this._internalTexturesCache.slice(), t = 0, r = e; t < r.length; t++) {
            var n = r[t];
            n._rebuild()
        }
    }
    ,
    i.prototype._rebuildRenderTargetWrappers = function() {
        for (var e = this._renderTargetWrapperCache.slice(), t = 0, r = e; t < r.length; t++) {
            var n = r[t];
            n._rebuild()
        }
    }
    ,
    i.prototype._rebuildEffects = function() {
        for (var e in this._compiledEffects) {
            var t = this._compiledEffects[e];
            t._pipelineContext = null,
            t._wasPreviouslyReady = !1,
            t._prepareEffect()
        }
        Effect.ResetCache()
    }
    ,
    i.prototype.areAllEffectsReady = function() {
        for (var e in this._compiledEffects) {
            var t = this._compiledEffects[e];
            if (!t.isReady())
                return !1
        }
        return !0
    }
    ,
    i.prototype._rebuildBuffers = function() {
        for (var e = 0, t = this._uniformBuffers; e < t.length; e++) {
            var r = t[e];
            r._rebuild()
        }
        for (var n = 0, o = this._storageBuffers; n < o.length; n++) {
            var a = o[n];
            a._rebuild()
        }
    }
    ,
    i.prototype._initGLContext = function() {
        this._caps = {
            maxTexturesImageUnits: this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS),
            maxCombinedTexturesImageUnits: this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS),
            maxVertexTextureImageUnits: this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS),
            maxTextureSize: this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE),
            maxSamples: this._webGLVersion > 1 ? this._gl.getParameter(this._gl.MAX_SAMPLES) : 1,
            maxCubemapTextureSize: this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE),
            maxRenderTextureSize: this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE),
            maxVertexAttribs: this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS),
            maxVaryingVectors: this._gl.getParameter(this._gl.MAX_VARYING_VECTORS),
            maxFragmentUniformVectors: this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS),
            maxVertexUniformVectors: this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS),
            parallelShaderCompile: this._gl.getExtension("KHR_parallel_shader_compile") || void 0,
            standardDerivatives: this._webGLVersion > 1 || this._gl.getExtension("OES_standard_derivatives") !== null,
            maxAnisotropy: 1,
            astc: this._gl.getExtension("WEBGL_compressed_texture_astc") || this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_astc"),
            bptc: this._gl.getExtension("EXT_texture_compression_bptc") || this._gl.getExtension("WEBKIT_EXT_texture_compression_bptc"),
            s3tc: this._gl.getExtension("WEBGL_compressed_texture_s3tc") || this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"),
            s3tc_srgb: this._gl.getExtension("WEBGL_compressed_texture_s3tc_srgb") || this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc_srgb"),
            pvrtc: this._gl.getExtension("WEBGL_compressed_texture_pvrtc") || this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),
            etc1: this._gl.getExtension("WEBGL_compressed_texture_etc1") || this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc1"),
            etc2: this._gl.getExtension("WEBGL_compressed_texture_etc") || this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc") || this._gl.getExtension("WEBGL_compressed_texture_es3_0"),
            textureAnisotropicFilterExtension: this._gl.getExtension("EXT_texture_filter_anisotropic") || this._gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic") || this._gl.getExtension("MOZ_EXT_texture_filter_anisotropic"),
            uintIndices: this._webGLVersion > 1 || this._gl.getExtension("OES_element_index_uint") !== null,
            fragmentDepthSupported: this._webGLVersion > 1 || this._gl.getExtension("EXT_frag_depth") !== null,
            highPrecisionShaderSupported: !1,
            timerQuery: this._gl.getExtension("EXT_disjoint_timer_query_webgl2") || this._gl.getExtension("EXT_disjoint_timer_query"),
            supportOcclusionQuery: this._webGLVersion > 1,
            canUseTimestampForTimerQuery: !1,
            drawBuffersExtension: !1,
            maxMSAASamples: 1,
            colorBufferFloat: !!(this._webGLVersion > 1 && this._gl.getExtension("EXT_color_buffer_float")),
            textureFloat: !!(this._webGLVersion > 1 || this._gl.getExtension("OES_texture_float")),
            textureHalfFloat: !!(this._webGLVersion > 1 || this._gl.getExtension("OES_texture_half_float")),
            textureHalfFloatRender: !1,
            textureFloatLinearFiltering: !1,
            textureFloatRender: !1,
            textureHalfFloatLinearFiltering: !1,
            vertexArrayObject: !1,
            instancedArrays: !1,
            textureLOD: !!(this._webGLVersion > 1 || this._gl.getExtension("EXT_shader_texture_lod")),
            blendMinMax: !1,
            multiview: this._gl.getExtension("OVR_multiview2"),
            oculusMultiview: this._gl.getExtension("OCULUS_multiview"),
            depthTextureExtension: !1,
            canUseGLInstanceID: this._webGLVersion > 1,
            canUseGLVertexID: this._webGLVersion > 1,
            supportComputeShaders: !1,
            supportSRGBBuffers: !1
        },
        this._glVersion = this._gl.getParameter(this._gl.VERSION);
        var e = this._gl.getExtension("WEBGL_debug_renderer_info");
        if (e != null && (this._glRenderer = this._gl.getParameter(e.UNMASKED_RENDERER_WEBGL),
        this._glVendor = this._gl.getParameter(e.UNMASKED_VENDOR_WEBGL)),
        this._glVendor || (this._glVendor = "Unknown vendor"),
        this._glRenderer || (this._glRenderer = "Unknown renderer"),
        this._gl.HALF_FLOAT_OES !== 36193 && (this._gl.HALF_FLOAT_OES = 36193),
        this._gl.RGBA16F !== 34842 && (this._gl.RGBA16F = 34842),
        this._gl.RGBA32F !== 34836 && (this._gl.RGBA32F = 34836),
        this._gl.DEPTH24_STENCIL8 !== 35056 && (this._gl.DEPTH24_STENCIL8 = 35056),
        this._caps.timerQuery && (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),
        this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0,
        this._caps.textureFloatLinearFiltering = !!(this._caps.textureFloat && this._gl.getExtension("OES_texture_float_linear")),
        this._caps.textureFloatRender = !!(this._caps.textureFloat && this._canRenderToFloatFramebuffer()),
        this._caps.textureHalfFloatLinearFiltering = !!(this._webGLVersion > 1 || this._caps.textureHalfFloat && this._gl.getExtension("OES_texture_half_float_linear")),
        this._caps.astc && (this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR = this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR),
        this._caps.bptc && (this._gl.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT = this._caps.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT),
        this._caps.s3tc_srgb && (this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT = this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,
        this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT = this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT),
        this._webGLVersion > 1 && this._gl.HALF_FLOAT_OES !== 5131 && (this._gl.HALF_FLOAT_OES = 5131),
        this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer(),
        this._webGLVersion > 1)
            this._caps.drawBuffersExtension = !0,
            this._caps.maxMSAASamples = this._gl.getParameter(this._gl.MAX_SAMPLES);
        else {
            var t = this._gl.getExtension("WEBGL_draw_buffers");
            if (t !== null) {
                this._caps.drawBuffersExtension = !0,
                this._gl.drawBuffers = t.drawBuffersWEBGL.bind(t),
                this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
                for (var r = 0; r < 16; r++)
                    this._gl["COLOR_ATTACHMENT" + r + "_WEBGL"] = t["COLOR_ATTACHMENT" + r + "_WEBGL"]
            }
        }
        if (this._webGLVersion > 1)
            this._caps.depthTextureExtension = !0;
        else {
            var n = this._gl.getExtension("WEBGL_depth_texture");
            n != null && (this._caps.depthTextureExtension = !0,
            this._gl.UNSIGNED_INT_24_8 = n.UNSIGNED_INT_24_8_WEBGL)
        }
        if (this.disableVertexArrayObjects)
            this._caps.vertexArrayObject = !1;
        else if (this._webGLVersion > 1)
            this._caps.vertexArrayObject = !0;
        else {
            var o = this._gl.getExtension("OES_vertex_array_object");
            o != null && (this._caps.vertexArrayObject = !0,
            this._gl.createVertexArray = o.createVertexArrayOES.bind(o),
            this._gl.bindVertexArray = o.bindVertexArrayOES.bind(o),
            this._gl.deleteVertexArray = o.deleteVertexArrayOES.bind(o))
        }
        if (this._webGLVersion > 1)
            this._caps.instancedArrays = !0;
        else {
            var a = this._gl.getExtension("ANGLE_instanced_arrays");
            a != null ? (this._caps.instancedArrays = !0,
            this._gl.drawArraysInstanced = a.drawArraysInstancedANGLE.bind(a),
            this._gl.drawElementsInstanced = a.drawElementsInstancedANGLE.bind(a),
            this._gl.vertexAttribDivisor = a.vertexAttribDivisorANGLE.bind(a)) : this._caps.instancedArrays = !1
        }
        if (this._gl.getShaderPrecisionFormat) {
            var s = this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER, this._gl.HIGH_FLOAT)
              , l = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
            s && l && (this._caps.highPrecisionShaderSupported = s.precision !== 0 && l.precision !== 0)
        }
        if (this._webGLVersion > 1)
            this._caps.blendMinMax = !0;
        else {
            var u = this._gl.getExtension("EXT_blend_minmax");
            u != null && (this._caps.blendMinMax = !0,
            this._gl.MAX = u.MAX_EXT,
            this._gl.MIN = u.MIN_EXT)
        }
        if (this._webGLVersion > 1)
            this._caps.supportSRGBBuffers = !0;
        else {
            var c = this._gl.getExtension("EXT_sRGB");
            c != null && (this._caps.supportSRGBBuffers = !0,
            this._gl.SRGB = c.SRGB_EXT,
            this._gl.SRGB8 = c.SRGB_ALPHA_EXT,
            this._gl.SRGB8_ALPHA8 = c.SRGB_ALPHA_EXT)
        }
        this._depthCullingState.depthTest = !0,
        this._depthCullingState.depthFunc = this._gl.LEQUAL,
        this._depthCullingState.depthMask = !0,
        this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
        for (var h = 0; h < this._maxSimultaneousTextures; h++)
            this._nextFreeTextureSlots.push(h)
    }
    ,
    i.prototype._initFeatures = function() {
        this._features = {
            forceBitmapOverHTMLImageElement: !1,
            supportRenderAndCopyToLodForFloatTextures: this._webGLVersion !== 1,
            supportDepthStencilTexture: this._webGLVersion !== 1,
            supportShadowSamplers: this._webGLVersion !== 1,
            uniformBufferHardCheckMatrix: !1,
            allowTexturePrefiltering: this._webGLVersion !== 1,
            trackUbosInFrame: !1,
            checkUbosContentBeforeUpload: !1,
            supportCSM: this._webGLVersion !== 1,
            basisNeedsPOT: this._webGLVersion === 1,
            support3DTextures: this._webGLVersion !== 1,
            needTypeSuffixInShaderConstants: this._webGLVersion !== 1,
            supportMSAA: this._webGLVersion !== 1,
            supportSSAO2: this._webGLVersion !== 1,
            supportExtendedTextureFormats: this._webGLVersion !== 1,
            supportSwitchCaseInShader: this._webGLVersion !== 1,
            supportSyncTextureRead: !0,
            needsInvertingBitmap: !0,
            useUBOBindingCache: !0,
            needShaderCodeInlining: !1,
            needToAlwaysBindUniformBuffers: !1,
            supportRenderPasses: !1,
            _collectUbosUpdatedInFrame: !1
        }
    }
    ,
    Object.defineProperty(i.prototype, "webGLVersion", {
        get: function() {
            return this._webGLVersion
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.getClassName = function() {
        return "ThinEngine"
    }
    ,
    Object.defineProperty(i.prototype, "isStencilEnable", {
        get: function() {
            return this._isStencilEnable
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype._prepareWorkingCanvas = function() {
        if (!this._workingCanvas) {
            this._workingCanvas = this.createCanvas(1, 1);
            var e = this._workingCanvas.getContext("2d");
            e && (this._workingContext = e)
        }
    }
    ,
    i.prototype.resetTextureCache = function() {
        for (var e in this._boundTexturesCache)
            !this._boundTexturesCache.hasOwnProperty(e) || (this._boundTexturesCache[e] = null);
        this._currentTextureChannel = -1
    }
    ,
    i.prototype.getInfo = function() {
        return this.getGlInfo()
    }
    ,
    i.prototype.getGlInfo = function() {
        return {
            vendor: this._glVendor,
            renderer: this._glRenderer,
            version: this._glVersion
        }
    }
    ,
    i.prototype.setHardwareScalingLevel = function(e) {
        this._hardwareScalingLevel = e,
        this.resize()
    }
    ,
    i.prototype.getHardwareScalingLevel = function() {
        return this._hardwareScalingLevel
    }
    ,
    i.prototype.getLoadedTexturesCache = function() {
        return this._internalTexturesCache
    }
    ,
    i.prototype.getCaps = function() {
        return this._caps
    }
    ,
    i.prototype.stopRenderLoop = function(e) {
        if (!e) {
            this._activeRenderLoops = [];
            return
        }
        var t = this._activeRenderLoops.indexOf(e);
        t >= 0 && this._activeRenderLoops.splice(t, 1)
    }
    ,
    i.prototype._renderLoop = function() {
        if (!this._contextWasLost) {
            var e = !0;
            if (!this.renderEvenInBackground && this._windowIsBackground && (e = !1),
            e) {
                this.beginFrame();
                for (var t = 0; t < this._activeRenderLoops.length; t++) {
                    var r = this._activeRenderLoops[t];
                    r()
                }
                this.endFrame()
            }
        }
        this._activeRenderLoops.length > 0 ? this._frameHandler = this._queueNewFrame(this._boundRenderFunction, this.getHostWindow()) : this._renderingQueueLaunched = !1
    }
    ,
    i.prototype.getRenderingCanvas = function() {
        return this._renderingCanvas
    }
    ,
    i.prototype.getAudioContext = function() {
        return this._audioContext
    }
    ,
    i.prototype.getAudioDestination = function() {
        return this._audioDestination
    }
    ,
    i.prototype.getHostWindow = function() {
        return IsWindowObjectExist() ? this._renderingCanvas && this._renderingCanvas.ownerDocument && this._renderingCanvas.ownerDocument.defaultView ? this._renderingCanvas.ownerDocument.defaultView : window : null
    }
    ,
    i.prototype.getRenderWidth = function(e) {
        return e === void 0 && (e = !1),
        !e && this._currentRenderTarget ? this._currentRenderTarget.width : this._framebufferDimensionsObject ? this._framebufferDimensionsObject.framebufferWidth : this._gl.drawingBufferWidth
    }
    ,
    i.prototype.getRenderHeight = function(e) {
        return e === void 0 && (e = !1),
        !e && this._currentRenderTarget ? this._currentRenderTarget.height : this._framebufferDimensionsObject ? this._framebufferDimensionsObject.framebufferHeight : this._gl.drawingBufferHeight
    }
    ,
    i.prototype._queueNewFrame = function(e, t) {
        return i.QueueNewFrame(e, t)
    }
    ,
    i.prototype.runRenderLoop = function(e) {
        this._activeRenderLoops.indexOf(e) === -1 && (this._activeRenderLoops.push(e),
        this._renderingQueueLaunched || (this._renderingQueueLaunched = !0,
        this._boundRenderFunction = this._renderLoop.bind(this),
        this._frameHandler = this._queueNewFrame(this._boundRenderFunction, this.getHostWindow())))
    }
    ,
    i.prototype.clear = function(e, t, r, n) {
        n === void 0 && (n = !1);
        var o = this.stencilStateComposer.useStencilGlobalOnly;
        this.stencilStateComposer.useStencilGlobalOnly = !0,
        this.applyStates(),
        this.stencilStateComposer.useStencilGlobalOnly = o;
        var a = 0;
        t && e && (this._gl.clearColor(e.r, e.g, e.b, e.a !== void 0 ? e.a : 1),
        a |= this._gl.COLOR_BUFFER_BIT),
        r && (this.useReverseDepthBuffer ? (this._depthCullingState.depthFunc = this._gl.GEQUAL,
        this._gl.clearDepth(0)) : this._gl.clearDepth(1),
        a |= this._gl.DEPTH_BUFFER_BIT),
        n && (this._gl.clearStencil(0),
        a |= this._gl.STENCIL_BUFFER_BIT),
        this._gl.clear(a)
    }
    ,
    i.prototype._viewport = function(e, t, r, n) {
        (e !== this._viewportCached.x || t !== this._viewportCached.y || r !== this._viewportCached.z || n !== this._viewportCached.w) && (this._viewportCached.x = e,
        this._viewportCached.y = t,
        this._viewportCached.z = r,
        this._viewportCached.w = n,
        this._gl.viewport(e, t, r, n))
    }
    ,
    i.prototype.setViewport = function(e, t, r) {
        var n = t || this.getRenderWidth()
          , o = r || this.getRenderHeight()
          , a = e.x || 0
          , s = e.y || 0;
        this._cachedViewport = e,
        this._viewport(a * n, s * o, n * e.width, o * e.height)
    }
    ,
    i.prototype.beginFrame = function() {}
    ,
    i.prototype.endFrame = function() {
        this._badOS && this.flushFramebuffer(),
        this._frameId++
    }
    ,
    i.prototype.resize = function(e) {
        e === void 0 && (e = !1);
        var t, r;
        IsWindowObjectExist() ? (t = this._renderingCanvas ? this._renderingCanvas.clientWidth || this._renderingCanvas.width : window.innerWidth,
        r = this._renderingCanvas ? this._renderingCanvas.clientHeight || this._renderingCanvas.height : window.innerHeight) : (t = this._renderingCanvas ? this._renderingCanvas.width : 100,
        r = this._renderingCanvas ? this._renderingCanvas.height : 100),
        this.setSize(t / this._hardwareScalingLevel, r / this._hardwareScalingLevel, e)
    }
    ,
    i.prototype.setSize = function(e, t, r) {
        return r === void 0 && (r = !1),
        !this._renderingCanvas || (e = e | 0,
        t = t | 0,
        !r && this._renderingCanvas.width === e && this._renderingCanvas.height === t) ? !1 : (this._renderingCanvas.width = e,
        this._renderingCanvas.height = t,
        !0)
    }
    ,
    i.prototype.bindFramebuffer = function(e, t, r, n, o, a, s) {
        var l, u, c, h, f;
        t === void 0 && (t = 0),
        a === void 0 && (a = 0),
        s === void 0 && (s = 0);
        var d = e;
        this._currentRenderTarget && this.unBindFramebuffer(this._currentRenderTarget),
        this._currentRenderTarget = e,
        this._bindUnboundFramebuffer(d._MSAAFramebuffer ? d._MSAAFramebuffer : d._framebuffer);
        var _ = this._gl;
        e.is2DArray ? _.framebufferTextureLayer(_.FRAMEBUFFER, _.COLOR_ATTACHMENT0, (l = e.texture._hardwareTexture) === null || l === void 0 ? void 0 : l.underlyingResource, a, s) : e.isCube && _.framebufferTexture2D(_.FRAMEBUFFER, _.COLOR_ATTACHMENT0, _.TEXTURE_CUBE_MAP_POSITIVE_X + t, (u = e.texture._hardwareTexture) === null || u === void 0 ? void 0 : u.underlyingResource, a);
        var g = e._depthStencilTexture;
        if (g) {
            var m = e._depthStencilTextureWithStencil ? _.DEPTH_STENCIL_ATTACHMENT : _.DEPTH_ATTACHMENT;
            e.is2DArray ? _.framebufferTextureLayer(_.FRAMEBUFFER, m, (c = g._hardwareTexture) === null || c === void 0 ? void 0 : c.underlyingResource, a, s) : e.isCube ? _.framebufferTexture2D(_.FRAMEBUFFER, m, _.TEXTURE_CUBE_MAP_POSITIVE_X + t, (h = g._hardwareTexture) === null || h === void 0 ? void 0 : h.underlyingResource, a) : _.framebufferTexture2D(_.FRAMEBUFFER, m, _.TEXTURE_2D, (f = g._hardwareTexture) === null || f === void 0 ? void 0 : f.underlyingResource, a)
        }
        this._cachedViewport && !o ? this.setViewport(this._cachedViewport, r, n) : (r || (r = e.width,
        a && (r = r / Math.pow(2, a))),
        n || (n = e.height,
        a && (n = n / Math.pow(2, a))),
        this._viewport(0, 0, r, n)),
        this.wipeCaches()
    }
    ,
    i.prototype.setState = function(e, t, r, n, o, a, s) {
        var l, u;
        t === void 0 && (t = 0),
        n === void 0 && (n = !1),
        s === void 0 && (s = 0),
        (this._depthCullingState.cull !== e || r) && (this._depthCullingState.cull = e);
        var c = !((u = (l = this.cullBackFaces) !== null && l !== void 0 ? l : o) !== null && u !== void 0) || u ? this._gl.BACK : this._gl.FRONT;
        (this._depthCullingState.cullFace !== c || r) && (this._depthCullingState.cullFace = c),
        this.setZOffset(t),
        this.setZOffsetUnits(s);
        var h = n ? this._gl.CW : this._gl.CCW;
        (this._depthCullingState.frontFace !== h || r) && (this._depthCullingState.frontFace = h),
        this._stencilStateComposer.stencilMaterial = a
    }
    ,
    i.prototype.setZOffset = function(e) {
        this._depthCullingState.zOffset = this.useReverseDepthBuffer ? -e : e
    }
    ,
    i.prototype.getZOffset = function() {
        var e = this._depthCullingState.zOffset;
        return this.useReverseDepthBuffer ? -e : e
    }
    ,
    i.prototype.setZOffsetUnits = function(e) {
        this._depthCullingState.zOffsetUnits = this.useReverseDepthBuffer ? -e : e
    }
    ,
    i.prototype.getZOffsetUnits = function() {
        var e = this._depthCullingState.zOffsetUnits;
        return this.useReverseDepthBuffer ? -e : e
    }
    ,
    i.prototype._bindUnboundFramebuffer = function(e) {
        this._currentFramebuffer !== e && (this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, e),
        this._currentFramebuffer = e)
    }
    ,
    i.prototype._currentFrameBufferIsDefaultFrameBuffer = function() {
        return this._currentFramebuffer === null
    }
    ,
    i.prototype.generateMipmaps = function(e) {
        this._bindTextureDirectly(this._gl.TEXTURE_2D, e, !0),
        this._gl.generateMipmap(this._gl.TEXTURE_2D),
        this._bindTextureDirectly(this._gl.TEXTURE_2D, null)
    }
    ,
    i.prototype.unBindFramebuffer = function(e, t, r) {
        var n;
        t === void 0 && (t = !1);
        var o = e;
        this._currentRenderTarget = null;
        var a = this._gl;
        if (o._MSAAFramebuffer) {
            if (e.isMulti) {
                this.unBindMultiColorAttachmentFramebuffer(e, t, r);
                return
            }
            a.bindFramebuffer(a.READ_FRAMEBUFFER, o._MSAAFramebuffer),
            a.bindFramebuffer(a.DRAW_FRAMEBUFFER, o._framebuffer),
            a.blitFramebuffer(0, 0, e.width, e.height, 0, 0, e.width, e.height, a.COLOR_BUFFER_BIT, a.NEAREST)
        }
        ((n = e.texture) === null || n === void 0 ? void 0 : n.generateMipMaps) && !t && !e.isCube && this.generateMipmaps(e.texture),
        r && (o._MSAAFramebuffer && this._bindUnboundFramebuffer(o._framebuffer),
        r()),
        this._bindUnboundFramebuffer(null)
    }
    ,
    i.prototype.flushFramebuffer = function() {
        this._gl.flush()
    }
    ,
    i.prototype.restoreDefaultFramebuffer = function() {
        this._currentRenderTarget ? this.unBindFramebuffer(this._currentRenderTarget) : this._bindUnboundFramebuffer(null),
        this._cachedViewport && this.setViewport(this._cachedViewport),
        this.wipeCaches()
    }
    ,
    i.prototype._resetVertexBufferBinding = function() {
        this.bindArrayBuffer(null),
        this._cachedVertexBuffers = null
    }
    ,
    i.prototype.createVertexBuffer = function(e) {
        return this._createVertexBuffer(e, this._gl.STATIC_DRAW)
    }
    ,
    i.prototype._createVertexBuffer = function(e, t) {
        var r = this._gl.createBuffer();
        if (!r)
            throw new Error("Unable to create vertex buffer");
        var n = new WebGLDataBuffer(r);
        return this.bindArrayBuffer(n),
        e instanceof Array ? this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(e), t) : this._gl.bufferData(this._gl.ARRAY_BUFFER, e, t),
        this._resetVertexBufferBinding(),
        n.references = 1,
        n
    }
    ,
    i.prototype.createDynamicVertexBuffer = function(e) {
        return this._createVertexBuffer(e, this._gl.DYNAMIC_DRAW)
    }
    ,
    i.prototype._resetIndexBufferBinding = function() {
        this.bindIndexBuffer(null),
        this._cachedIndexBuffer = null
    }
    ,
    i.prototype.createIndexBuffer = function(e, t) {
        var r = this._gl.createBuffer()
          , n = new WebGLDataBuffer(r);
        if (!r)
            throw new Error("Unable to create index buffer");
        this.bindIndexBuffer(n);
        var o = this._normalizeIndexData(e);
        return this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, o, t ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW),
        this._resetIndexBufferBinding(),
        n.references = 1,
        n.is32Bits = o.BYTES_PER_ELEMENT === 4,
        n
    }
    ,
    i.prototype._normalizeIndexData = function(e) {
        var t = e.BYTES_PER_ELEMENT;
        if (t === 2)
            return e;
        if (this._caps.uintIndices) {
            if (e instanceof Uint32Array)
                return e;
            for (var r = 0; r < e.length; r++)
                if (e[r] >= 65535)
                    return new Uint32Array(e);
            return new Uint16Array(e)
        }
        return new Uint16Array(e)
    }
    ,
    i.prototype.bindArrayBuffer = function(e) {
        this._vaoRecordInProgress || this._unbindVertexArrayObject(),
        this.bindBuffer(e, this._gl.ARRAY_BUFFER)
    }
    ,
    i.prototype.bindUniformBlock = function(e, t, r) {
        var n = e.program
          , o = this._gl.getUniformBlockIndex(n, t);
        this._gl.uniformBlockBinding(n, o, r)
    }
    ,
    i.prototype.bindIndexBuffer = function(e) {
        this._vaoRecordInProgress || this._unbindVertexArrayObject(),
        this.bindBuffer(e, this._gl.ELEMENT_ARRAY_BUFFER)
    }
    ,
    i.prototype.bindBuffer = function(e, t) {
        (this._vaoRecordInProgress || this._currentBoundBuffer[t] !== e) && (this._gl.bindBuffer(t, e ? e.underlyingResource : null),
        this._currentBoundBuffer[t] = e)
    }
    ,
    i.prototype.updateArrayBuffer = function(e) {
        this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, e)
    }
    ,
    i.prototype._vertexAttribPointer = function(e, t, r, n, o, a, s) {
        var l = this._currentBufferPointers[t];
        if (!!l) {
            var u = !1;
            l.active ? (l.buffer !== e && (l.buffer = e,
            u = !0),
            l.size !== r && (l.size = r,
            u = !0),
            l.type !== n && (l.type = n,
            u = !0),
            l.normalized !== o && (l.normalized = o,
            u = !0),
            l.stride !== a && (l.stride = a,
            u = !0),
            l.offset !== s && (l.offset = s,
            u = !0)) : (u = !0,
            l.active = !0,
            l.index = t,
            l.size = r,
            l.type = n,
            l.normalized = o,
            l.stride = a,
            l.offset = s,
            l.buffer = e),
            (u || this._vaoRecordInProgress) && (this.bindArrayBuffer(e),
            this._gl.vertexAttribPointer(t, r, n, o, a, s))
        }
    }
    ,
    i.prototype._bindIndexBufferWithCache = function(e) {
        e != null && this._cachedIndexBuffer !== e && (this._cachedIndexBuffer = e,
        this.bindIndexBuffer(e),
        this._uintIndicesCurrentlySet = e.is32Bits)
    }
    ,
    i.prototype._bindVertexBuffersAttributes = function(e, t, r) {
        var n = t.getAttributesNames();
        this._vaoRecordInProgress || this._unbindVertexArrayObject(),
        this.unbindAllAttributes();
        for (var o = 0; o < n.length; o++) {
            var a = t.getAttributeLocation(o);
            if (a >= 0) {
                var s = n[o]
                  , l = null;
                if (r && (l = r[s]),
                l || (l = e[s]),
                !l)
                    continue;
                this._gl.enableVertexAttribArray(a),
                this._vaoRecordInProgress || (this._vertexAttribArraysEnabled[a] = !0);
                var u = l.getBuffer();
                u && (this._vertexAttribPointer(u, a, l.getSize(), l.type, l.normalized, l.byteStride, l.byteOffset),
                l.getIsInstanced() && (this._gl.vertexAttribDivisor(a, l.getInstanceDivisor()),
                this._vaoRecordInProgress || (this._currentInstanceLocations.push(a),
                this._currentInstanceBuffers.push(u))))
            }
        }
    }
    ,
    i.prototype.recordVertexArrayObject = function(e, t, r, n) {
        var o = this._gl.createVertexArray();
        return this._vaoRecordInProgress = !0,
        this._gl.bindVertexArray(o),
        this._mustWipeVertexAttributes = !0,
        this._bindVertexBuffersAttributes(e, r, n),
        this.bindIndexBuffer(t),
        this._vaoRecordInProgress = !1,
        this._gl.bindVertexArray(null),
        o
    }
    ,
    i.prototype.bindVertexArrayObject = function(e, t) {
        this._cachedVertexArrayObject !== e && (this._cachedVertexArrayObject = e,
        this._gl.bindVertexArray(e),
        this._cachedVertexBuffers = null,
        this._cachedIndexBuffer = null,
        this._uintIndicesCurrentlySet = t != null && t.is32Bits,
        this._mustWipeVertexAttributes = !0)
    }
    ,
    i.prototype.bindBuffersDirectly = function(e, t, r, n, o) {
        if (this._cachedVertexBuffers !== e || this._cachedEffectForVertexBuffers !== o) {
            this._cachedVertexBuffers = e,
            this._cachedEffectForVertexBuffers = o;
            var a = o.getAttributesCount();
            this._unbindVertexArrayObject(),
            this.unbindAllAttributes();
            for (var s = 0, l = 0; l < a; l++)
                if (l < r.length) {
                    var u = o.getAttributeLocation(l);
                    u >= 0 && (this._gl.enableVertexAttribArray(u),
                    this._vertexAttribArraysEnabled[u] = !0,
                    this._vertexAttribPointer(e, u, r[l], this._gl.FLOAT, !1, n, s)),
                    s += r[l] * 4
                }
        }
        this._bindIndexBufferWithCache(t)
    }
    ,
    i.prototype._unbindVertexArrayObject = function() {
        !this._cachedVertexArrayObject || (this._cachedVertexArrayObject = null,
        this._gl.bindVertexArray(null))
    }
    ,
    i.prototype.bindBuffers = function(e, t, r, n) {
        (this._cachedVertexBuffers !== e || this._cachedEffectForVertexBuffers !== r) && (this._cachedVertexBuffers = e,
        this._cachedEffectForVertexBuffers = r,
        this._bindVertexBuffersAttributes(e, r, n)),
        this._bindIndexBufferWithCache(t)
    }
    ,
    i.prototype.unbindInstanceAttributes = function() {
        for (var e, t = 0, r = this._currentInstanceLocations.length; t < r; t++) {
            var n = this._currentInstanceBuffers[t];
            e != n && n.references && (e = n,
            this.bindArrayBuffer(n));
            var o = this._currentInstanceLocations[t];
            this._gl.vertexAttribDivisor(o, 0)
        }
        this._currentInstanceBuffers.length = 0,
        this._currentInstanceLocations.length = 0
    }
    ,
    i.prototype.releaseVertexArrayObject = function(e) {
        this._gl.deleteVertexArray(e)
    }
    ,
    i.prototype._releaseBuffer = function(e) {
        return e.references--,
        e.references === 0 ? (this._deleteBuffer(e),
        !0) : !1
    }
    ,
    i.prototype._deleteBuffer = function(e) {
        this._gl.deleteBuffer(e.underlyingResource)
    }
    ,
    i.prototype.updateAndBindInstancesBuffer = function(e, t, r) {
        if (this.bindArrayBuffer(e),
        t && this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, t),
        r[0].index !== void 0)
            this.bindInstancesBuffer(e, r, !0);
        else
            for (var n = 0; n < 4; n++) {
                var o = r[n];
                this._vertexAttribArraysEnabled[o] || (this._gl.enableVertexAttribArray(o),
                this._vertexAttribArraysEnabled[o] = !0),
                this._vertexAttribPointer(e, o, 4, this._gl.FLOAT, !1, 64, n * 16),
                this._gl.vertexAttribDivisor(o, 1),
                this._currentInstanceLocations.push(o),
                this._currentInstanceBuffers.push(e)
            }
    }
    ,
    i.prototype.bindInstancesBuffer = function(e, t, r) {
        r === void 0 && (r = !0),
        this.bindArrayBuffer(e);
        var n = 0;
        if (r)
            for (var o = 0; o < t.length; o++) {
                var a = t[o];
                n += a.attributeSize * 4
            }
        for (var o = 0; o < t.length; o++) {
            var a = t[o];
            a.index === void 0 && (a.index = this._currentEffect.getAttributeLocationByName(a.attributeName)),
            !(a.index < 0) && (this._vertexAttribArraysEnabled[a.index] || (this._gl.enableVertexAttribArray(a.index),
            this._vertexAttribArraysEnabled[a.index] = !0),
            this._vertexAttribPointer(e, a.index, a.attributeSize, a.attributeType || this._gl.FLOAT, a.normalized || !1, n, a.offset),
            this._gl.vertexAttribDivisor(a.index, a.divisor === void 0 ? 1 : a.divisor),
            this._currentInstanceLocations.push(a.index),
            this._currentInstanceBuffers.push(e))
        }
    }
    ,
    i.prototype.disableInstanceAttributeByName = function(e) {
        if (!!this._currentEffect) {
            var t = this._currentEffect.getAttributeLocationByName(e);
            this.disableInstanceAttribute(t)
        }
    }
    ,
    i.prototype.disableInstanceAttribute = function(e) {
        for (var t = !1, r; (r = this._currentInstanceLocations.indexOf(e)) !== -1; )
            this._currentInstanceLocations.splice(r, 1),
            this._currentInstanceBuffers.splice(r, 1),
            t = !0,
            r = this._currentInstanceLocations.indexOf(e);
        t && (this._gl.vertexAttribDivisor(e, 0),
        this.disableAttributeByIndex(e))
    }
    ,
    i.prototype.disableAttributeByIndex = function(e) {
        this._gl.disableVertexAttribArray(e),
        this._vertexAttribArraysEnabled[e] = !1,
        this._currentBufferPointers[e].active = !1
    }
    ,
    i.prototype.draw = function(e, t, r, n) {
        this.drawElementsType(e ? 0 : 1, t, r, n)
    }
    ,
    i.prototype.drawPointClouds = function(e, t, r) {
        this.drawArraysType(2, e, t, r)
    }
    ,
    i.prototype.drawUnIndexed = function(e, t, r, n) {
        this.drawArraysType(e ? 0 : 1, t, r, n)
    }
    ,
    i.prototype.drawElementsType = function(e, t, r, n) {
        this.applyStates(),
        this._reportDrawCall();
        var o = this._drawMode(e)
          , a = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT
          , s = this._uintIndicesCurrentlySet ? 4 : 2;
        n ? this._gl.drawElementsInstanced(o, r, a, t * s, n) : this._gl.drawElements(o, r, a, t * s)
    }
    ,
    i.prototype.drawArraysType = function(e, t, r, n) {
        this.applyStates(),
        this._reportDrawCall();
        var o = this._drawMode(e);
        n ? this._gl.drawArraysInstanced(o, t, r, n) : this._gl.drawArrays(o, t, r)
    }
    ,
    i.prototype._drawMode = function(e) {
        switch (e) {
        case 0:
            return this._gl.TRIANGLES;
        case 2:
            return this._gl.POINTS;
        case 1:
            return this._gl.LINES;
        case 3:
            return this._gl.POINTS;
        case 4:
            return this._gl.LINES;
        case 5:
            return this._gl.LINE_LOOP;
        case 6:
            return this._gl.LINE_STRIP;
        case 7:
            return this._gl.TRIANGLE_STRIP;
        case 8:
            return this._gl.TRIANGLE_FAN;
        default:
            return this._gl.TRIANGLES
        }
    }
    ,
    i.prototype._reportDrawCall = function() {}
    ,
    i.prototype._releaseEffect = function(e) {
        if (this._compiledEffects[e._key]) {
            delete this._compiledEffects[e._key];
            var t = e.getPipelineContext();
            t && this._deletePipelineContext(t)
        }
    }
    ,
    i.prototype._deletePipelineContext = function(e) {
        var t = e;
        t && t.program && (t.program.__SPECTOR_rebuildProgram = null,
        this._gl.deleteProgram(t.program))
    }
    ,
    i.prototype._getGlobalDefines = function(e) {
        if (e) {
            this.isNDCHalfZRange ? e.IS_NDC_HALF_ZRANGE = "" : delete e.IS_NDC_HALF_ZRANGE,
            this.useReverseDepthBuffer ? e.USE_REVERSE_DEPTHBUFFER = "" : delete e.USE_REVERSE_DEPTHBUFFER;
            return
        } else {
            var t = "";
            return this.isNDCHalfZRange && (t += "#define IS_NDC_HALF_ZRANGE"),
            this.useReverseDepthBuffer && (t && (t += `
`),
            t += "#define USE_REVERSE_DEPTHBUFFER"),
            t
        }
    }
    ,
    i.prototype.createEffect = function(e, t, r, n, o, a, s, l, u, c) {
        var h;
        c === void 0 && (c = ShaderLanguage.GLSL);
        var f = e.vertexElement || e.vertex || e.vertexToken || e.vertexSource || e
          , d = e.fragmentElement || e.fragment || e.fragmentToken || e.fragmentSource || e
          , _ = this._getGlobalDefines()
          , g = (h = o != null ? o : t.defines) !== null && h !== void 0 ? h : "";
        _ && (g += _);
        var m = f + "+" + d + "@" + g;
        if (this._compiledEffects[m]) {
            var v = this._compiledEffects[m];
            return s && v.isReady() && s(v),
            v
        }
        var y = new Effect(e,t,r,n,this,o,a,s,l,u,m,c);
        return this._compiledEffects[m] = y,
        y
    }
    ,
    i._ConcatenateShader = function(e, t, r) {
        return r === void 0 && (r = ""),
        r + (t ? t + `
` : "") + e
    }
    ,
    i.prototype._compileShader = function(e, t, r, n) {
        return this._compileRawShader(i._ConcatenateShader(e, r, n), t)
    }
    ,
    i.prototype._compileRawShader = function(e, t) {
        for (var r = this._gl; r.getError() != r.NO_ERROR; )
            ;
        var n = r.createShader(t === "vertex" ? r.VERTEX_SHADER : r.FRAGMENT_SHADER);
        if (!n)
            throw new Error("Something went wrong while creating a gl " + t + " shader object. gl error=" + r.getError() + ", gl isContextLost=" + r.isContextLost() + ", _contextWasLost=" + this._contextWasLost);
        return r.shaderSource(n, e),
        r.compileShader(n),
        n
    }
    ,
    i.prototype._getShaderSource = function(e) {
        return this._gl.getShaderSource(e)
    }
    ,
    i.prototype.createRawShaderProgram = function(e, t, r, n, o) {
        o === void 0 && (o = null),
        n = n || this._gl;
        var a = this._compileRawShader(t, "vertex")
          , s = this._compileRawShader(r, "fragment");
        return this._createShaderProgram(e, a, s, n, o)
    }
    ,
    i.prototype.createShaderProgram = function(e, t, r, n, o, a) {
        a === void 0 && (a = null),
        o = o || this._gl;
        var s = this._webGLVersion > 1 ? `#version 300 es
#define WEBGL2 
` : ""
          , l = this._compileShader(t, "vertex", n, s)
          , u = this._compileShader(r, "fragment", n, s);
        return this._createShaderProgram(e, l, u, o, a)
    }
    ,
    i.prototype.inlineShaderCode = function(e) {
        return e
    }
    ,
    i.prototype.createPipelineContext = function(e) {
        var t = new WebGLPipelineContext;
        return t.engine = this,
        this._caps.parallelShaderCompile && (t.isParallelCompiled = !0),
        t
    }
    ,
    i.prototype.createMaterialContext = function() {}
    ,
    i.prototype.createDrawContext = function() {}
    ,
    i.prototype._createShaderProgram = function(e, t, r, n, o) {
        var a = n.createProgram();
        if (e.program = a,
        !a)
            throw new Error("Unable to create program");
        return n.attachShader(a, t),
        n.attachShader(a, r),
        n.linkProgram(a),
        e.context = n,
        e.vertexShader = t,
        e.fragmentShader = r,
        e.isParallelCompiled || this._finalizePipelineContext(e),
        a
    }
    ,
    i.prototype._finalizePipelineContext = function(e) {
        var t = e.context
          , r = e.vertexShader
          , n = e.fragmentShader
          , o = e.program
          , a = t.getProgramParameter(o, t.LINK_STATUS);
        if (!a) {
            if (!this._gl.getShaderParameter(r, this._gl.COMPILE_STATUS)) {
                var s = this._gl.getShaderInfoLog(r);
                if (s)
                    throw e.vertexCompilationError = s,
                    new Error("VERTEX SHADER " + s)
            }
            if (!this._gl.getShaderParameter(n, this._gl.COMPILE_STATUS)) {
                var s = this._gl.getShaderInfoLog(n);
                if (s)
                    throw e.fragmentCompilationError = s,
                    new Error("FRAGMENT SHADER " + s)
            }
            var l = t.getProgramInfoLog(o);
            if (l)
                throw e.programLinkError = l,
                new Error(l)
        }
        if (this.validateShaderPrograms) {
            t.validateProgram(o);
            var u = t.getProgramParameter(o, t.VALIDATE_STATUS);
            if (!u) {
                var l = t.getProgramInfoLog(o);
                if (l)
                    throw e.programValidationError = l,
                    new Error(l)
            }
        }
        t.deleteShader(r),
        t.deleteShader(n),
        e.vertexShader = void 0,
        e.fragmentShader = void 0,
        e.onCompiled && (e.onCompiled(),
        e.onCompiled = void 0)
    }
    ,
    i.prototype._preparePipelineContext = function(e, t, r, n, o, a, s, l, u, c) {
        var h = e;
        n ? h.program = this.createRawShaderProgram(h, t, r, void 0, u) : h.program = this.createShaderProgram(h, t, r, l, void 0, u),
        h.program.__SPECTOR_rebuildProgram = s
    }
    ,
    i.prototype._isRenderingStateCompiled = function(e) {
        var t = e;
        return this._gl.getProgramParameter(t.program, this._caps.parallelShaderCompile.COMPLETION_STATUS_KHR) ? (this._finalizePipelineContext(t),
        !0) : !1
    }
    ,
    i.prototype._executeWhenRenderingStateIsCompiled = function(e, t) {
        var r = e;
        if (!r.isParallelCompiled) {
            t();
            return
        }
        var n = r.onCompiled;
        n ? r.onCompiled = function() {
            n(),
            t()
        }
        : r.onCompiled = t
    }
    ,
    i.prototype.getUniforms = function(e, t) {
        for (var r = new Array, n = e, o = 0; o < t.length; o++)
            r.push(this._gl.getUniformLocation(n.program, t[o]));
        return r
    }
    ,
    i.prototype.getAttributes = function(e, t) {
        for (var r = [], n = e, o = 0; o < t.length; o++)
            try {
                r.push(this._gl.getAttribLocation(n.program, t[o]))
            } catch {
                r.push(-1)
            }
        return r
    }
    ,
    i.prototype.enableEffect = function(e) {
        e = e !== null && DrawWrapper.IsWrapper(e) ? e.effect : e,
        !(!e || e === this._currentEffect) && (this._stencilStateComposer.stencilMaterial = void 0,
        e = e,
        this.bindSamplers(e),
        this._currentEffect = e,
        e.onBind && e.onBind(e),
        e._onBindObservable && e._onBindObservable.notifyObservers(e))
    }
    ,
    i.prototype.setInt = function(e, t) {
        return e ? (this._gl.uniform1i(e, t),
        !0) : !1
    }
    ,
    i.prototype.setInt2 = function(e, t, r) {
        return e ? (this._gl.uniform2i(e, t, r),
        !0) : !1
    }
    ,
    i.prototype.setInt3 = function(e, t, r, n) {
        return e ? (this._gl.uniform3i(e, t, r, n),
        !0) : !1
    }
    ,
    i.prototype.setInt4 = function(e, t, r, n, o) {
        return e ? (this._gl.uniform4i(e, t, r, n, o),
        !0) : !1
    }
    ,
    i.prototype.setIntArray = function(e, t) {
        return e ? (this._gl.uniform1iv(e, t),
        !0) : !1
    }
    ,
    i.prototype.setIntArray2 = function(e, t) {
        return !e || t.length % 2 !== 0 ? !1 : (this._gl.uniform2iv(e, t),
        !0)
    }
    ,
    i.prototype.setIntArray3 = function(e, t) {
        return !e || t.length % 3 !== 0 ? !1 : (this._gl.uniform3iv(e, t),
        !0)
    }
    ,
    i.prototype.setIntArray4 = function(e, t) {
        return !e || t.length % 4 !== 0 ? !1 : (this._gl.uniform4iv(e, t),
        !0)
    }
    ,
    i.prototype.setArray = function(e, t) {
        return !e || t.length < 1 ? !1 : (this._gl.uniform1fv(e, t),
        !0)
    }
    ,
    i.prototype.setArray2 = function(e, t) {
        return !e || t.length % 2 !== 0 ? !1 : (this._gl.uniform2fv(e, t),
        !0)
    }
    ,
    i.prototype.setArray3 = function(e, t) {
        return !e || t.length % 3 !== 0 ? !1 : (this._gl.uniform3fv(e, t),
        !0)
    }
    ,
    i.prototype.setArray4 = function(e, t) {
        return !e || t.length % 4 !== 0 ? !1 : (this._gl.uniform4fv(e, t),
        !0)
    }
    ,
    i.prototype.setMatrices = function(e, t) {
        return e ? (this._gl.uniformMatrix4fv(e, !1, t),
        !0) : !1
    }
    ,
    i.prototype.setMatrix3x3 = function(e, t) {
        return e ? (this._gl.uniformMatrix3fv(e, !1, t),
        !0) : !1
    }
    ,
    i.prototype.setMatrix2x2 = function(e, t) {
        return e ? (this._gl.uniformMatrix2fv(e, !1, t),
        !0) : !1
    }
    ,
    i.prototype.setFloat = function(e, t) {
        return e ? (this._gl.uniform1f(e, t),
        !0) : !1
    }
    ,
    i.prototype.setFloat2 = function(e, t, r) {
        return e ? (this._gl.uniform2f(e, t, r),
        !0) : !1
    }
    ,
    i.prototype.setFloat3 = function(e, t, r, n) {
        return e ? (this._gl.uniform3f(e, t, r, n),
        !0) : !1
    }
    ,
    i.prototype.setFloat4 = function(e, t, r, n, o) {
        return e ? (this._gl.uniform4f(e, t, r, n, o),
        !0) : !1
    }
    ,
    i.prototype.applyStates = function() {
        if (this._depthCullingState.apply(this._gl),
        this._stencilStateComposer.apply(this._gl),
        this._alphaState.apply(this._gl),
        this._colorWriteChanged) {
            this._colorWriteChanged = !1;
            var e = this._colorWrite;
            this._gl.colorMask(e, e, e, e)
        }
    }
    ,
    i.prototype.setColorWrite = function(e) {
        e !== this._colorWrite && (this._colorWriteChanged = !0,
        this._colorWrite = e)
    }
    ,
    i.prototype.getColorWrite = function() {
        return this._colorWrite
    }
    ,
    Object.defineProperty(i.prototype, "depthCullingState", {
        get: function() {
            return this._depthCullingState
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "alphaState", {
        get: function() {
            return this._alphaState
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "stencilState", {
        get: function() {
            return this._stencilState
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "stencilStateComposer", {
        get: function() {
            return this._stencilStateComposer
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.clearInternalTexturesCache = function() {
        this._internalTexturesCache = []
    }
    ,
    i.prototype.wipeCaches = function(e) {
        this.preventCacheWipeBetweenFrames && !e || (this._currentEffect = null,
        this._viewportCached.x = 0,
        this._viewportCached.y = 0,
        this._viewportCached.z = 0,
        this._viewportCached.w = 0,
        this._unbindVertexArrayObject(),
        e && (this._currentProgram = null,
        this.resetTextureCache(),
        this._stencilStateComposer.reset(),
        this._depthCullingState.reset(),
        this._depthCullingState.depthFunc = this._gl.LEQUAL,
        this._alphaState.reset(),
        this._alphaMode = 1,
        this._alphaEquation = 0,
        this._colorWrite = !0,
        this._colorWriteChanged = !0,
        this._unpackFlipYCached = null,
        this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, this._gl.NONE),
        this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0),
        this._mustWipeVertexAttributes = !0,
        this.unbindAllAttributes()),
        this._resetVertexBufferBinding(),
        this._cachedIndexBuffer = null,
        this._cachedEffectForVertexBuffers = null,
        this.bindIndexBuffer(null))
    }
    ,
    i.prototype._getSamplingParameters = function(e, t) {
        var r = this._gl
          , n = r.NEAREST
          , o = r.NEAREST;
        switch (e) {
        case 11:
            n = r.LINEAR,
            t ? o = r.LINEAR_MIPMAP_NEAREST : o = r.LINEAR;
            break;
        case 3:
            n = r.LINEAR,
            t ? o = r.LINEAR_MIPMAP_LINEAR : o = r.LINEAR;
            break;
        case 8:
            n = r.NEAREST,
            t ? o = r.NEAREST_MIPMAP_LINEAR : o = r.NEAREST;
            break;
        case 4:
            n = r.NEAREST,
            t ? o = r.NEAREST_MIPMAP_NEAREST : o = r.NEAREST;
            break;
        case 5:
            n = r.NEAREST,
            t ? o = r.LINEAR_MIPMAP_NEAREST : o = r.LINEAR;
            break;
        case 6:
            n = r.NEAREST,
            t ? o = r.LINEAR_MIPMAP_LINEAR : o = r.LINEAR;
            break;
        case 7:
            n = r.NEAREST,
            o = r.LINEAR;
            break;
        case 1:
            n = r.NEAREST,
            o = r.NEAREST;
            break;
        case 9:
            n = r.LINEAR,
            t ? o = r.NEAREST_MIPMAP_NEAREST : o = r.NEAREST;
            break;
        case 10:
            n = r.LINEAR,
            t ? o = r.NEAREST_MIPMAP_LINEAR : o = r.NEAREST;
            break;
        case 2:
            n = r.LINEAR,
            o = r.LINEAR;
            break;
        case 12:
            n = r.LINEAR,
            o = r.NEAREST;
            break
        }
        return {
            min: o,
            mag: n
        }
    }
    ,
    i.prototype._createTexture = function() {
        var e = this._gl.createTexture();
        if (!e)
            throw new Error("Unable to create texture");
        return e
    }
    ,
    i.prototype._createHardwareTexture = function() {
        return new WebGLHardwareTexture(this._createTexture(),this._gl)
    }
    ,
    i.prototype._createInternalTexture = function(e, t, r, n) {
        n === void 0 && (n = InternalTextureSource.Unknown);
        var o = {};
        t !== void 0 && typeof t == "object" ? (o.generateMipMaps = t.generateMipMaps,
        o.type = t.type === void 0 ? 0 : t.type,
        o.samplingMode = t.samplingMode === void 0 ? 3 : t.samplingMode,
        o.format = t.format === void 0 ? 5 : t.format) : (o.generateMipMaps = t,
        o.type = 0,
        o.samplingMode = 3,
        o.format = 5),
        (o.type === 1 && !this._caps.textureFloatLinearFiltering || o.type === 2 && !this._caps.textureHalfFloatLinearFiltering) && (o.samplingMode = 1),
        o.type === 1 && !this._caps.textureFloat && (o.type = 0,
        Logger$2.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));
        var a = this._gl
          , s = new InternalTexture(this,n)
          , l = e.width || e
          , u = e.height || e
          , c = e.layers || 0
          , h = this._getSamplingParameters(o.samplingMode, !!o.generateMipMaps)
          , f = c !== 0 ? a.TEXTURE_2D_ARRAY : a.TEXTURE_2D
          , d = this._getRGBABufferInternalSizedFormat(o.type, o.format)
          , _ = this._getInternalFormat(o.format)
          , g = this._getWebGLTextureType(o.type);
        return this._bindTextureDirectly(f, s),
        c !== 0 ? (s.is2DArray = !0,
        a.texImage3D(f, 0, d, l, u, c, 0, _, g, null)) : a.texImage2D(f, 0, d, l, u, 0, _, g, null),
        a.texParameteri(f, a.TEXTURE_MAG_FILTER, h.mag),
        a.texParameteri(f, a.TEXTURE_MIN_FILTER, h.min),
        a.texParameteri(f, a.TEXTURE_WRAP_S, a.CLAMP_TO_EDGE),
        a.texParameteri(f, a.TEXTURE_WRAP_T, a.CLAMP_TO_EDGE),
        o.generateMipMaps && this._gl.generateMipmap(f),
        this._bindTextureDirectly(f, null),
        s.baseWidth = l,
        s.baseHeight = u,
        s.width = l,
        s.height = u,
        s.depth = c,
        s.isReady = !0,
        s.samples = 1,
        s.generateMipMaps = !!o.generateMipMaps,
        s.samplingMode = o.samplingMode,
        s.type = o.type,
        s.format = o.format,
        this._internalTexturesCache.push(s),
        s
    }
    ,
    i.prototype._getUseSRGBBuffer = function(e, t) {
        return e && this._caps.supportSRGBBuffers && (this.webGLVersion > 1 || this.isWebGPU || t)
    }
    ,
    i.prototype._createTextureBase = function(e, t, r, n, o, a, s, l, u, c, h, f, d, _, g, m) {
        var v = this;
        o === void 0 && (o = 3),
        a === void 0 && (a = null),
        s === void 0 && (s = null),
        c === void 0 && (c = null),
        h === void 0 && (h = null),
        f === void 0 && (f = null),
        d === void 0 && (d = null),
        e = e || "";
        var y = e.substr(0, 5) === "data:"
          , b = e.substr(0, 5) === "blob:"
          , T = y && e.indexOf(";base64,") !== -1
          , C = h || new InternalTexture(this,InternalTextureSource.Url)
          , A = e;
        this._transformTextureUrl && !T && !h && !c && (e = this._transformTextureUrl(e)),
        A !== e && (C._originalUrl = A);
        var S = e.lastIndexOf(".")
          , P = d || (S > -1 ? e.substring(S).toLowerCase() : "")
          , R = null
          , M = P.indexOf("?");
        M > -1 && (P = P.split("?")[0]);
        for (var x = 0, I = i._TextureLoaders; x < I.length; x++) {
            var w = I[x];
            if (w.canLoad(P, _)) {
                R = w;
                break
            }
        }
        n && n._addPendingData(C),
        C.url = e,
        C.generateMipMaps = !t,
        C.samplingMode = o,
        C.invertY = r,
        C._useSRGBBuffer = this._getUseSRGBBuffer(!!m, t),
        this._doNotHandleContextLost || (C._buffer = c);
        var O = null;
        a && !h && (O = C.onLoadedObservable.add(a)),
        h || this._internalTexturesCache.push(C);
        var D = function(N, L) {
            n && n._removePendingData(C),
            e === A ? (O && C.onLoadedObservable.remove(O),
            EngineStore.UseFallbackTexture && v._createTextureBase(EngineStore.FallbackTexture, t, C.invertY, n, o, null, s, l, u, c, C),
            N = (N || "Unknown error") + (EngineStore.UseFallbackTexture ? " - Fallback texture was used" : ""),
            C.onErrorObservable.notifyObservers({
                message: N,
                exception: L
            }),
            s && s(N, L)) : (Logger$2.Warn("Failed to load " + e + ", falling back to " + A),
            v._createTextureBase(A, t, C.invertY, n, o, a, s, l, u, c, C, f, d, _, g, m))
        };
        if (R) {
            var F = function(N) {
                R.loadData(N, C, function(L, k, U, z, H, G) {
                    G ? D("TextureLoader failed to load data") : l(C, P, n, {
                        width: L,
                        height: k
                    }, C.invertY, !U, z, function() {
                        return H(),
                        !1
                    }, o)
                }, g)
            };
            c ? c instanceof ArrayBuffer ? F(new Uint8Array(c)) : ArrayBuffer.isView(c) ? F(c) : s && s("Unable to load: only ArrayBuffer or ArrayBufferView is supported", null) : this._loadFile(e, function(N) {
                return F(new Uint8Array(N))
            }, void 0, n ? n.offlineProvider : void 0, !0, function(N, L) {
                D("Unable to load " + (N && N.responseURL,
                L))
            })
        } else {
            var V = function(N) {
                b && !v._doNotHandleContextLost && (C._buffer = N),
                l(C, P, n, N, C.invertY, t, !1, u, o)
            };
            !y || T ? c && (typeof c.decoding == "string" || c.close) ? V(c) : i._FileToolsLoadImage(e, V, D, n ? n.offlineProvider : null, _, C.invertY && this._features.needsInvertingBitmap ? {
                imageOrientation: "flipY"
            } : void 0) : typeof c == "string" || c instanceof ArrayBuffer || ArrayBuffer.isView(c) || c instanceof Blob ? i._FileToolsLoadImage(c, V, D, n ? n.offlineProvider : null, _, C.invertY && this._features.needsInvertingBitmap ? {
                imageOrientation: "flipY"
            } : void 0) : c && V(c)
        }
        return C
    }
    ,
    i.prototype.createTexture = function(e, t, r, n, o, a, s, l, u, c, h, f, d, _, g) {
        var m = this;
        return o === void 0 && (o = 3),
        a === void 0 && (a = null),
        s === void 0 && (s = null),
        l === void 0 && (l = null),
        u === void 0 && (u = null),
        c === void 0 && (c = null),
        h === void 0 && (h = null),
        this._createTextureBase(e, t, r, n, o, a, s, this._prepareWebGLTexture.bind(this), function(v, y, b, T, C, A) {
            var S = m._gl
              , P = b.width === v && b.height === y
              , R = c ? m._getInternalFormat(c, C._useSRGBBuffer) : T === ".jpg" && !C._useSRGBBuffer ? S.RGB : C._useSRGBBuffer ? S.SRGB8_ALPHA8 : S.RGBA
              , M = c ? m._getInternalFormat(c) : T === ".jpg" && !C._useSRGBBuffer ? S.RGB : S.RGBA;
            if (C._useSRGBBuffer && m.webGLVersion === 1 && (M = R),
            P)
                return S.texImage2D(S.TEXTURE_2D, 0, R, M, S.UNSIGNED_BYTE, b),
                !1;
            var x = m._caps.maxTextureSize;
            if (b.width > x || b.height > x || !m._supportsHardwareTextureRescaling)
                return m._prepareWorkingCanvas(),
                !m._workingCanvas || !m._workingContext || (m._workingCanvas.width = v,
                m._workingCanvas.height = y,
                m._workingContext.drawImage(b, 0, 0, b.width, b.height, 0, 0, v, y),
                S.texImage2D(S.TEXTURE_2D, 0, R, M, S.UNSIGNED_BYTE, m._workingCanvas),
                C.width = v,
                C.height = y),
                !1;
            var I = new InternalTexture(m,InternalTextureSource.Temp);
            return m._bindTextureDirectly(S.TEXTURE_2D, I, !0),
            S.texImage2D(S.TEXTURE_2D, 0, R, M, S.UNSIGNED_BYTE, b),
            m._rescaleTexture(I, C, n, R, function() {
                m._releaseTexture(I),
                m._bindTextureDirectly(S.TEXTURE_2D, C, !0),
                A()
            }),
            !0
        }, l, u, c, h, f, d, g)
    }
    ,
    i._FileToolsLoadImage = function(e, t, r, n, o, a) {
        throw _WarnImport("FileTools")
    }
    ,
    i.prototype._rescaleTexture = function(e, t, r, n, o) {}
    ,
    i.prototype.createRawTexture = function(e, t, r, n, o, a, s, l, u) {
        throw _WarnImport("Engine.RawTexture")
    }
    ,
    i.prototype.createRawCubeTexture = function(e, t, r, n, o, a, s, l) {
        throw _WarnImport("Engine.RawTexture")
    }
    ,
    i.prototype.createRawTexture3D = function(e, t, r, n, o, a, s, l, u, c) {
        throw _WarnImport("Engine.RawTexture")
    }
    ,
    i.prototype.createRawTexture2DArray = function(e, t, r, n, o, a, s, l, u, c) {
        throw _WarnImport("Engine.RawTexture")
    }
    ,
    i.prototype._unpackFlipY = function(e) {
        this._unpackFlipYCached !== e && (this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, e ? 1 : 0),
        this.enableUnpackFlipYCached && (this._unpackFlipYCached = e))
    }
    ,
    i.prototype._getUnpackAlignement = function() {
        return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT)
    }
    ,
    i.prototype._getTextureTarget = function(e) {
        return e.isCube ? this._gl.TEXTURE_CUBE_MAP : e.is3D ? this._gl.TEXTURE_3D : e.is2DArray || e.isMultiview ? this._gl.TEXTURE_2D_ARRAY : this._gl.TEXTURE_2D
    }
    ,
    i.prototype.updateTextureSamplingMode = function(e, t, r) {
        r === void 0 && (r = !1);
        var n = this._getTextureTarget(t)
          , o = this._getSamplingParameters(e, t.generateMipMaps || r);
        this._setTextureParameterInteger(n, this._gl.TEXTURE_MAG_FILTER, o.mag, t),
        this._setTextureParameterInteger(n, this._gl.TEXTURE_MIN_FILTER, o.min),
        r && (t.generateMipMaps = !0,
        this._gl.generateMipmap(n)),
        this._bindTextureDirectly(n, null),
        t.samplingMode = e
    }
    ,
    i.prototype.updateTextureDimensions = function(e, t, r, n) {}
    ,
    i.prototype.updateTextureWrappingMode = function(e, t, r, n) {
        r === void 0 && (r = null),
        n === void 0 && (n = null);
        var o = this._getTextureTarget(e);
        t !== null && (this._setTextureParameterInteger(o, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(t), e),
        e._cachedWrapU = t),
        r !== null && (this._setTextureParameterInteger(o, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(r), e),
        e._cachedWrapV = r),
        (e.is2DArray || e.is3D) && n !== null && (this._setTextureParameterInteger(o, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(n), e),
        e._cachedWrapR = n),
        this._bindTextureDirectly(o, null)
    }
    ,
    i.prototype._setupDepthStencilTexture = function(e, t, r, n, o, a) {
        a === void 0 && (a = 1);
        var s = t.width || t
          , l = t.height || t
          , u = t.layers || 0;
        e.baseWidth = s,
        e.baseHeight = l,
        e.width = s,
        e.height = l,
        e.is2DArray = u > 0,
        e.depth = u,
        e.isReady = !0,
        e.samples = a,
        e.generateMipMaps = !1,
        e.samplingMode = n ? 2 : 1,
        e.type = 0,
        e._comparisonFunction = o;
        var c = this._gl
          , h = this._getTextureTarget(e)
          , f = this._getSamplingParameters(e.samplingMode, !1);
        c.texParameteri(h, c.TEXTURE_MAG_FILTER, f.mag),
        c.texParameteri(h, c.TEXTURE_MIN_FILTER, f.min),
        c.texParameteri(h, c.TEXTURE_WRAP_S, c.CLAMP_TO_EDGE),
        c.texParameteri(h, c.TEXTURE_WRAP_T, c.CLAMP_TO_EDGE),
        o === 0 ? (c.texParameteri(h, c.TEXTURE_COMPARE_FUNC, 515),
        c.texParameteri(h, c.TEXTURE_COMPARE_MODE, c.NONE)) : (c.texParameteri(h, c.TEXTURE_COMPARE_FUNC, o),
        c.texParameteri(h, c.TEXTURE_COMPARE_MODE, c.COMPARE_REF_TO_TEXTURE))
    }
    ,
    i.prototype._uploadCompressedDataToTextureDirectly = function(e, t, r, n, o, a, s) {
        a === void 0 && (a = 0),
        s === void 0 && (s = 0);
        var l = this._gl
          , u = l.TEXTURE_2D;
        if (e.isCube && (u = l.TEXTURE_CUBE_MAP_POSITIVE_X + a),
        e._useSRGBBuffer)
            switch (t) {
            case 36492:
                t = l.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT;
                break;
            case 37808:
                t = l.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;
                break;
            case 33776:
                this._caps.s3tc_srgb ? t = l.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT : e._useSRGBBuffer = !1;
                break;
            case 33779:
                this._caps.s3tc_srgb ? t = l.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT : e._useSRGBBuffer = !1;
                break;
            default:
                e._useSRGBBuffer = !1;
                break
            }
        this._gl.compressedTexImage2D(u, s, t, r, n, 0, o)
    }
    ,
    i.prototype._uploadDataToTextureDirectly = function(e, t, r, n, o, a) {
        r === void 0 && (r = 0),
        n === void 0 && (n = 0),
        a === void 0 && (a = !1);
        var s = this._gl
          , l = this._getWebGLTextureType(e.type)
          , u = this._getInternalFormat(e.format)
          , c = o === void 0 ? this._getRGBABufferInternalSizedFormat(e.type, e.format, e._useSRGBBuffer) : this._getInternalFormat(o, e._useSRGBBuffer);
        this._unpackFlipY(e.invertY);
        var h = s.TEXTURE_2D;
        e.isCube && (h = s.TEXTURE_CUBE_MAP_POSITIVE_X + r);
        var f = Math.round(Math.log(e.width) * Math.LOG2E)
          , d = Math.round(Math.log(e.height) * Math.LOG2E)
          , _ = a ? e.width : Math.pow(2, Math.max(f - n, 0))
          , g = a ? e.height : Math.pow(2, Math.max(d - n, 0));
        s.texImage2D(h, n, c, _, g, 0, u, l, t)
    }
    ,
    i.prototype.updateTextureData = function(e, t, r, n, o, a, s, l) {
        s === void 0 && (s = 0),
        l === void 0 && (l = 0);
        var u = this._gl
          , c = this._getWebGLTextureType(e.type)
          , h = this._getInternalFormat(e.format);
        this._unpackFlipY(e.invertY);
        var f = u.TEXTURE_2D;
        e.isCube && (f = u.TEXTURE_CUBE_MAP_POSITIVE_X + s),
        u.texSubImage2D(f, l, r, n, o, a, h, c, t)
    }
    ,
    i.prototype._uploadArrayBufferViewToTexture = function(e, t, r, n) {
        r === void 0 && (r = 0),
        n === void 0 && (n = 0);
        var o = this._gl
          , a = e.isCube ? o.TEXTURE_CUBE_MAP : o.TEXTURE_2D;
        this._bindTextureDirectly(a, e, !0),
        this._uploadDataToTextureDirectly(e, t, r, n),
        this._bindTextureDirectly(a, null, !0)
    }
    ,
    i.prototype._prepareWebGLTextureContinuation = function(e, t, r, n, o) {
        var a = this._gl;
        if (!!a) {
            var s = this._getSamplingParameters(o, !r);
            a.texParameteri(a.TEXTURE_2D, a.TEXTURE_MAG_FILTER, s.mag),
            a.texParameteri(a.TEXTURE_2D, a.TEXTURE_MIN_FILTER, s.min),
            !r && !n && a.generateMipmap(a.TEXTURE_2D),
            this._bindTextureDirectly(a.TEXTURE_2D, null),
            t && t._removePendingData(e),
            e.onLoadedObservable.notifyObservers(e),
            e.onLoadedObservable.clear()
        }
    }
    ,
    i.prototype._prepareWebGLTexture = function(e, t, r, n, o, a, s, l, u) {
        var c = this;
        u === void 0 && (u = 3);
        var h = this.getCaps().maxTextureSize
          , f = Math.min(h, this.needPOTTextures ? i.GetExponentOfTwo(n.width, h) : n.width)
          , d = Math.min(h, this.needPOTTextures ? i.GetExponentOfTwo(n.height, h) : n.height)
          , _ = this._gl;
        if (!!_) {
            if (!e._hardwareTexture) {
                r && r._removePendingData(e);
                return
            }
            this._bindTextureDirectly(_.TEXTURE_2D, e, !0),
            this._unpackFlipY(o === void 0 ? !0 : !!o),
            e.baseWidth = n.width,
            e.baseHeight = n.height,
            e.width = f,
            e.height = d,
            e.isReady = !0,
            !l(f, d, n, t, e, function() {
                c._prepareWebGLTextureContinuation(e, r, a, s, u)
            }) && this._prepareWebGLTextureContinuation(e, r, a, s, u)
        }
    }
    ,
    i.prototype._setupFramebufferDepthAttachments = function(e, t, r, n, o) {
        o === void 0 && (o = 1);
        var a = this._gl;
        if (e && t)
            return this._createRenderBuffer(r, n, o, a.DEPTH_STENCIL, a.DEPTH24_STENCIL8, a.DEPTH_STENCIL_ATTACHMENT);
        if (t) {
            var s = a.DEPTH_COMPONENT16;
            return this._webGLVersion > 1 && (s = a.DEPTH_COMPONENT32F),
            this._createRenderBuffer(r, n, o, s, s, a.DEPTH_ATTACHMENT)
        }
        return e ? this._createRenderBuffer(r, n, o, a.STENCIL_INDEX8, a.STENCIL_INDEX8, a.STENCIL_ATTACHMENT) : null
    }
    ,
    i.prototype._createRenderBuffer = function(e, t, r, n, o, a, s) {
        s === void 0 && (s = !0);
        var l = this._gl
          , u = l.createRenderbuffer();
        return l.bindRenderbuffer(l.RENDERBUFFER, u),
        r > 1 && l.renderbufferStorageMultisample ? l.renderbufferStorageMultisample(l.RENDERBUFFER, r, o, e, t) : l.renderbufferStorage(l.RENDERBUFFER, n, e, t),
        l.framebufferRenderbuffer(l.FRAMEBUFFER, a, l.RENDERBUFFER, u),
        s && l.bindRenderbuffer(l.RENDERBUFFER, null),
        u
    }
    ,
    i.prototype._releaseTexture = function(e) {
        var t;
        this._deleteTexture((t = e._hardwareTexture) === null || t === void 0 ? void 0 : t.underlyingResource),
        this.unbindAllTextures();
        var r = this._internalTexturesCache.indexOf(e);
        r !== -1 && this._internalTexturesCache.splice(r, 1),
        e._lodTextureHigh && e._lodTextureHigh.dispose(),
        e._lodTextureMid && e._lodTextureMid.dispose(),
        e._lodTextureLow && e._lodTextureLow.dispose(),
        e._irradianceTexture && e._irradianceTexture.dispose()
    }
    ,
    i.prototype._releaseRenderTargetWrapper = function(e) {
        var t = this._renderTargetWrapperCache.indexOf(e);
        t !== -1 && this._renderTargetWrapperCache.splice(t, 1)
    }
    ,
    i.prototype._deleteTexture = function(e) {
        e && this._gl.deleteTexture(e)
    }
    ,
    i.prototype._setProgram = function(e) {
        this._currentProgram !== e && (this._gl.useProgram(e),
        this._currentProgram = e)
    }
    ,
    i.prototype.bindSamplers = function(e) {
        var t = e.getPipelineContext();
        this._setProgram(t.program);
        for (var r = e.getSamplers(), n = 0; n < r.length; n++) {
            var o = e.getUniform(r[n]);
            o && (this._boundUniforms[n] = o)
        }
        this._currentEffect = null
    }
    ,
    i.prototype._activateCurrentTexture = function() {
        this._currentTextureChannel !== this._activeChannel && (this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel),
        this._currentTextureChannel = this._activeChannel)
    }
    ,
    i.prototype._bindTextureDirectly = function(e, t, r, n) {
        var o, a;
        r === void 0 && (r = !1),
        n === void 0 && (n = !1);
        var s = !1
          , l = t && t._associatedChannel > -1;
        r && l && (this._activeChannel = t._associatedChannel);
        var u = this._boundTexturesCache[this._activeChannel];
        if (u !== t || n) {
            if (this._activateCurrentTexture(),
            t && t.isMultiview)
                throw console.error(e, t),
                "_bindTextureDirectly called with a multiview texture!";
            this._gl.bindTexture(e, (a = (o = t == null ? void 0 : t._hardwareTexture) === null || o === void 0 ? void 0 : o.underlyingResource) !== null && a !== void 0 ? a : null),
            this._boundTexturesCache[this._activeChannel] = t,
            t && (t._associatedChannel = this._activeChannel)
        } else
            r && (s = !0,
            this._activateCurrentTexture());
        return l && !r && this._bindSamplerUniformToChannel(t._associatedChannel, this._activeChannel),
        s
    }
    ,
    i.prototype._bindTexture = function(e, t, r) {
        if (e !== void 0) {
            t && (t._associatedChannel = e),
            this._activeChannel = e;
            var n = t ? this._getTextureTarget(t) : this._gl.TEXTURE_2D;
            this._bindTextureDirectly(n, t)
        }
    }
    ,
    i.prototype.unbindAllTextures = function() {
        for (var e = 0; e < this._maxSimultaneousTextures; e++)
            this._activeChannel = e,
            this._bindTextureDirectly(this._gl.TEXTURE_2D, null),
            this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null),
            this.webGLVersion > 1 && (this._bindTextureDirectly(this._gl.TEXTURE_3D, null),
            this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY, null))
    }
    ,
    i.prototype.setTexture = function(e, t, r, n) {
        e !== void 0 && (t && (this._boundUniforms[e] = t),
        this._setTexture(e, r))
    }
    ,
    i.prototype._bindSamplerUniformToChannel = function(e, t) {
        var r = this._boundUniforms[e];
        !r || r._currentState === t || (this._gl.uniform1i(r, t),
        r._currentState = t)
    }
    ,
    i.prototype._getTextureWrapMode = function(e) {
        switch (e) {
        case 1:
            return this._gl.REPEAT;
        case 0:
            return this._gl.CLAMP_TO_EDGE;
        case 2:
            return this._gl.MIRRORED_REPEAT
        }
        return this._gl.REPEAT
    }
    ,
    i.prototype._setTexture = function(e, t, r, n, o) {
        if (r === void 0 && (r = !1),
        n === void 0 && (n = !1),
        !t)
            return this._boundTexturesCache[e] != null && (this._activeChannel = e,
            this._bindTextureDirectly(this._gl.TEXTURE_2D, null),
            this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null),
            this.webGLVersion > 1 && (this._bindTextureDirectly(this._gl.TEXTURE_3D, null),
            this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY, null))),
            !1;
        if (t.video)
            this._activeChannel = e,
            t.update();
        else if (t.delayLoadState === 4)
            return t.delayLoad(),
            !1;
        var a;
        n ? a = t.depthStencilTexture : t.isReady() ? a = t.getInternalTexture() : t.isCube ? a = this.emptyCubeTexture : t.is3D ? a = this.emptyTexture3D : t.is2DArray ? a = this.emptyTexture2DArray : a = this.emptyTexture,
        !r && a && (a._associatedChannel = e);
        var s = !0;
        this._boundTexturesCache[e] === a && (r || this._bindSamplerUniformToChannel(a._associatedChannel, e),
        s = !1),
        this._activeChannel = e;
        var l = this._getTextureTarget(a);
        if (s && this._bindTextureDirectly(l, a, r),
        a && !a.isMultiview) {
            if (a.isCube && a._cachedCoordinatesMode !== t.coordinatesMode) {
                a._cachedCoordinatesMode = t.coordinatesMode;
                var u = t.coordinatesMode !== 3 && t.coordinatesMode !== 5 ? 1 : 0;
                t.wrapU = u,
                t.wrapV = u
            }
            a._cachedWrapU !== t.wrapU && (a._cachedWrapU = t.wrapU,
            this._setTextureParameterInteger(l, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(t.wrapU), a)),
            a._cachedWrapV !== t.wrapV && (a._cachedWrapV = t.wrapV,
            this._setTextureParameterInteger(l, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(t.wrapV), a)),
            a.is3D && a._cachedWrapR !== t.wrapR && (a._cachedWrapR = t.wrapR,
            this._setTextureParameterInteger(l, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(t.wrapR), a)),
            this._setAnisotropicLevel(l, a, t.anisotropicFilteringLevel)
        }
        return !0
    }
    ,
    i.prototype.setTextureArray = function(e, t, r, n) {
        if (!(e === void 0 || !t)) {
            (!this._textureUnits || this._textureUnits.length !== r.length) && (this._textureUnits = new Int32Array(r.length));
            for (var o = 0; o < r.length; o++) {
                var a = r[o].getInternalTexture();
                a ? (this._textureUnits[o] = e + o,
                a._associatedChannel = e + o) : this._textureUnits[o] = -1
            }
            this._gl.uniform1iv(t, this._textureUnits);
            for (var s = 0; s < r.length; s++)
                this._setTexture(this._textureUnits[s], r[s], !0)
        }
    }
    ,
    i.prototype._setAnisotropicLevel = function(e, t, r) {
        var n = this._caps.textureAnisotropicFilterExtension;
        t.samplingMode !== 11 && t.samplingMode !== 3 && t.samplingMode !== 2 && (r = 1),
        n && t._cachedAnisotropicFilteringLevel !== r && (this._setTextureParameterFloat(e, n.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(r, this._caps.maxAnisotropy), t),
        t._cachedAnisotropicFilteringLevel = r)
    }
    ,
    i.prototype._setTextureParameterFloat = function(e, t, r, n) {
        this._bindTextureDirectly(e, n, !0, !0),
        this._gl.texParameterf(e, t, r)
    }
    ,
    i.prototype._setTextureParameterInteger = function(e, t, r, n) {
        n && this._bindTextureDirectly(e, n, !0, !0),
        this._gl.texParameteri(e, t, r)
    }
    ,
    i.prototype.unbindAllAttributes = function() {
        if (this._mustWipeVertexAttributes) {
            this._mustWipeVertexAttributes = !1;
            for (var e = 0; e < this._caps.maxVertexAttribs; e++)
                this.disableAttributeByIndex(e);
            return
        }
        for (var e = 0, t = this._vertexAttribArraysEnabled.length; e < t; e++)
            e >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[e] || this.disableAttributeByIndex(e)
    }
    ,
    i.prototype.releaseEffects = function() {
        for (var e in this._compiledEffects) {
            var t = this._compiledEffects[e].getPipelineContext();
            this._deletePipelineContext(t)
        }
        this._compiledEffects = {}
    }
    ,
    i.prototype.dispose = function() {
        var e;
        this.stopRenderLoop(),
        this.onBeforeTextureInitObservable && this.onBeforeTextureInitObservable.clear(),
        this._emptyTexture && (this._releaseTexture(this._emptyTexture),
        this._emptyTexture = null),
        this._emptyCubeTexture && (this._releaseTexture(this._emptyCubeTexture),
        this._emptyCubeTexture = null),
        this._dummyFramebuffer && this._gl.deleteFramebuffer(this._dummyFramebuffer),
        this.releaseEffects(),
        (e = this.releaseComputeEffects) === null || e === void 0 || e.call(this),
        this.unbindAllAttributes(),
        this._boundUniforms = [],
        IsWindowObjectExist() && this._renderingCanvas && (this._doNotHandleContextLost || (this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost),
        this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored)),
        window.removeEventListener("resize", this._checkForMobile)),
        this._workingCanvas = null,
        this._workingContext = null,
        this._currentBufferPointers = [],
        this._renderingCanvas = null,
        this._currentProgram = null,
        this._boundRenderFunction = null,
        Effect.ResetCache();
        for (var t = 0, r = this._activeRequests; t < r.length; t++) {
            var n = r[t];
            n.abort()
        }
        this.onDisposeObservable.notifyObservers(this),
        this.onDisposeObservable.clear()
    }
    ,
    i.prototype.attachContextLostEvent = function(e) {
        this._renderingCanvas && this._renderingCanvas.addEventListener("webglcontextlost", e, !1)
    }
    ,
    i.prototype.attachContextRestoredEvent = function(e) {
        this._renderingCanvas && this._renderingCanvas.addEventListener("webglcontextrestored", e, !1)
    }
    ,
    i.prototype.getError = function() {
        return this._gl.getError()
    }
    ,
    i.prototype._canRenderToFloatFramebuffer = function() {
        return this._webGLVersion > 1 ? this._caps.colorBufferFloat : this._canRenderToFramebuffer(1)
    }
    ,
    i.prototype._canRenderToHalfFloatFramebuffer = function() {
        return this._webGLVersion > 1 ? this._caps.colorBufferFloat : this._canRenderToFramebuffer(2)
    }
    ,
    i.prototype._canRenderToFramebuffer = function(e) {
        for (var t = this._gl; t.getError() !== t.NO_ERROR; )
            ;
        var r = !0
          , n = t.createTexture();
        t.bindTexture(t.TEXTURE_2D, n),
        t.texImage2D(t.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(e), 1, 1, 0, t.RGBA, this._getWebGLTextureType(e), null),
        t.texParameteri(t.TEXTURE_2D, t.TEXTURE_MIN_FILTER, t.NEAREST),
        t.texParameteri(t.TEXTURE_2D, t.TEXTURE_MAG_FILTER, t.NEAREST);
        var o = t.createFramebuffer();
        t.bindFramebuffer(t.FRAMEBUFFER, o),
        t.framebufferTexture2D(t.FRAMEBUFFER, t.COLOR_ATTACHMENT0, t.TEXTURE_2D, n, 0);
        var a = t.checkFramebufferStatus(t.FRAMEBUFFER);
        if (r = r && a === t.FRAMEBUFFER_COMPLETE,
        r = r && t.getError() === t.NO_ERROR,
        r && (t.clear(t.COLOR_BUFFER_BIT),
        r = r && t.getError() === t.NO_ERROR),
        r) {
            t.bindFramebuffer(t.FRAMEBUFFER, null);
            var s = t.RGBA
              , l = t.UNSIGNED_BYTE
              , u = new Uint8Array(4);
            t.readPixels(0, 0, 1, 1, s, l, u),
            r = r && t.getError() === t.NO_ERROR
        }
        for (t.deleteTexture(n),
        t.deleteFramebuffer(o),
        t.bindFramebuffer(t.FRAMEBUFFER, null); !r && t.getError() !== t.NO_ERROR; )
            ;
        return r
    }
    ,
    i.prototype._getWebGLTextureType = function(e) {
        if (this._webGLVersion === 1) {
            switch (e) {
            case 1:
                return this._gl.FLOAT;
            case 2:
                return this._gl.HALF_FLOAT_OES;
            case 0:
                return this._gl.UNSIGNED_BYTE;
            case 8:
                return this._gl.UNSIGNED_SHORT_4_4_4_4;
            case 9:
                return this._gl.UNSIGNED_SHORT_5_5_5_1;
            case 10:
                return this._gl.UNSIGNED_SHORT_5_6_5
            }
            return this._gl.UNSIGNED_BYTE
        }
        switch (e) {
        case 3:
            return this._gl.BYTE;
        case 0:
            return this._gl.UNSIGNED_BYTE;
        case 4:
            return this._gl.SHORT;
        case 5:
            return this._gl.UNSIGNED_SHORT;
        case 6:
            return this._gl.INT;
        case 7:
            return this._gl.UNSIGNED_INT;
        case 1:
            return this._gl.FLOAT;
        case 2:
            return this._gl.HALF_FLOAT;
        case 8:
            return this._gl.UNSIGNED_SHORT_4_4_4_4;
        case 9:
            return this._gl.UNSIGNED_SHORT_5_5_5_1;
        case 10:
            return this._gl.UNSIGNED_SHORT_5_6_5;
        case 11:
            return this._gl.UNSIGNED_INT_2_10_10_10_REV;
        case 12:
            return this._gl.UNSIGNED_INT_24_8;
        case 13:
            return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
        case 14:
            return this._gl.UNSIGNED_INT_5_9_9_9_REV;
        case 15:
            return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV
        }
        return this._gl.UNSIGNED_BYTE
    }
    ,
    i.prototype._getInternalFormat = function(e, t) {
        t === void 0 && (t = !1);
        var r = t ? this._gl.SRGB8_ALPHA8 : this._gl.RGBA;
        switch (e) {
        case 0:
            r = this._gl.ALPHA;
            break;
        case 1:
            r = this._gl.LUMINANCE;
            break;
        case 2:
            r = this._gl.LUMINANCE_ALPHA;
            break;
        case 6:
            r = this._gl.RED;
            break;
        case 7:
            r = this._gl.RG;
            break;
        case 4:
            r = t ? this._gl.SRGB : this._gl.RGB;
            break;
        case 5:
            r = t ? this._gl.SRGB8_ALPHA8 : this._gl.RGBA;
            break
        }
        if (this._webGLVersion > 1)
            switch (e) {
            case 8:
                r = this._gl.RED_INTEGER;
                break;
            case 9:
                r = this._gl.RG_INTEGER;
                break;
            case 10:
                r = this._gl.RGB_INTEGER;
                break;
            case 11:
                r = this._gl.RGBA_INTEGER;
                break
            }
        return r
    }
    ,
    i.prototype._getRGBABufferInternalSizedFormat = function(e, t, r) {
        if (r === void 0 && (r = !1),
        this._webGLVersion === 1) {
            if (t !== void 0)
                switch (t) {
                case 0:
                    return this._gl.ALPHA;
                case 1:
                    return this._gl.LUMINANCE;
                case 2:
                    return this._gl.LUMINANCE_ALPHA;
                case 4:
                    return r ? this._gl.SRGB : this._gl.RGB
                }
            return this._gl.RGBA
        }
        switch (e) {
        case 3:
            switch (t) {
            case 6:
                return this._gl.R8_SNORM;
            case 7:
                return this._gl.RG8_SNORM;
            case 4:
                return this._gl.RGB8_SNORM;
            case 8:
                return this._gl.R8I;
            case 9:
                return this._gl.RG8I;
            case 10:
                return this._gl.RGB8I;
            case 11:
                return this._gl.RGBA8I;
            default:
                return this._gl.RGBA8_SNORM
            }
        case 0:
            switch (t) {
            case 6:
                return this._gl.R8;
            case 7:
                return this._gl.RG8;
            case 4:
                return r ? this._gl.SRGB8 : this._gl.RGB8;
            case 5:
                return r ? this._gl.SRGB8_ALPHA8 : this._gl.RGBA8;
            case 8:
                return this._gl.R8UI;
            case 9:
                return this._gl.RG8UI;
            case 10:
                return this._gl.RGB8UI;
            case 11:
                return this._gl.RGBA8UI;
            case 0:
                return this._gl.ALPHA;
            case 1:
                return this._gl.LUMINANCE;
            case 2:
                return this._gl.LUMINANCE_ALPHA;
            default:
                return this._gl.RGBA8
            }
        case 4:
            switch (t) {
            case 8:
                return this._gl.R16I;
            case 9:
                return this._gl.RG16I;
            case 10:
                return this._gl.RGB16I;
            case 11:
                return this._gl.RGBA16I;
            default:
                return this._gl.RGBA16I
            }
        case 5:
            switch (t) {
            case 8:
                return this._gl.R16UI;
            case 9:
                return this._gl.RG16UI;
            case 10:
                return this._gl.RGB16UI;
            case 11:
                return this._gl.RGBA16UI;
            default:
                return this._gl.RGBA16UI
            }
        case 6:
            switch (t) {
            case 8:
                return this._gl.R32I;
            case 9:
                return this._gl.RG32I;
            case 10:
                return this._gl.RGB32I;
            case 11:
                return this._gl.RGBA32I;
            default:
                return this._gl.RGBA32I
            }
        case 7:
            switch (t) {
            case 8:
                return this._gl.R32UI;
            case 9:
                return this._gl.RG32UI;
            case 10:
                return this._gl.RGB32UI;
            case 11:
                return this._gl.RGBA32UI;
            default:
                return this._gl.RGBA32UI
            }
        case 1:
            switch (t) {
            case 6:
                return this._gl.R32F;
            case 7:
                return this._gl.RG32F;
            case 4:
                return this._gl.RGB32F;
            case 5:
                return this._gl.RGBA32F;
            default:
                return this._gl.RGBA32F
            }
        case 2:
            switch (t) {
            case 6:
                return this._gl.R16F;
            case 7:
                return this._gl.RG16F;
            case 4:
                return this._gl.RGB16F;
            case 5:
                return this._gl.RGBA16F;
            default:
                return this._gl.RGBA16F
            }
        case 10:
            return this._gl.RGB565;
        case 13:
            return this._gl.R11F_G11F_B10F;
        case 14:
            return this._gl.RGB9_E5;
        case 8:
            return this._gl.RGBA4;
        case 9:
            return this._gl.RGB5_A1;
        case 11:
            switch (t) {
            case 5:
                return this._gl.RGB10_A2;
            case 11:
                return this._gl.RGB10_A2UI;
            default:
                return this._gl.RGB10_A2
            }
        }
        return r ? this._gl.SRGB8_ALPHA8 : this._gl.RGBA8
    }
    ,
    i.prototype._getRGBAMultiSampleBufferFormat = function(e) {
        return e === 1 ? this._gl.RGBA32F : e === 2 ? this._gl.RGBA16F : this._gl.RGBA8
    }
    ,
    i.prototype._loadFile = function(e, t, r, n, o, a) {
        var s = this
          , l = i._FileToolsLoadFile(e, t, r, n, o, a);
        return this._activeRequests.push(l),
        l.onCompleteObservable.add(function(u) {
            s._activeRequests.splice(s._activeRequests.indexOf(u), 1)
        }),
        l
    }
    ,
    i._FileToolsLoadFile = function(e, t, r, n, o, a) {
        throw _WarnImport("FileTools")
    }
    ,
    i.prototype.readPixels = function(e, t, r, n, o, a) {
        o === void 0 && (o = !0),
        a === void 0 && (a = !0);
        var s = o ? 4 : 3
          , l = o ? this._gl.RGBA : this._gl.RGB
          , u = new Uint8Array(n * r * s);
        return a && this.flushFramebuffer(),
        this._gl.readPixels(e, t, r, n, l, this._gl.UNSIGNED_BYTE, u),
        Promise.resolve(u)
    }
    ,
    Object.defineProperty(i, "IsSupportedAsync", {
        get: function() {
            return Promise.resolve(this.isSupported())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i, "IsSupported", {
        get: function() {
            return this.isSupported()
        },
        enumerable: !1,
        configurable: !0
    }),
    i.isSupported = function() {
        if (this._HasMajorPerformanceCaveat !== null)
            return !this._HasMajorPerformanceCaveat;
        if (this._IsSupported === null)
            try {
                var e = this._createCanvas(1, 1)
                  , t = e.getContext("webgl") || e.getContext("experimental-webgl");
                this._IsSupported = t != null && !!window.WebGLRenderingContext
            } catch {
                this._IsSupported = !1
            }
        return this._IsSupported
    }
    ,
    Object.defineProperty(i, "HasMajorPerformanceCaveat", {
        get: function() {
            if (this._HasMajorPerformanceCaveat === null)
                try {
                    var e = this._createCanvas(1, 1)
                      , t = e.getContext("webgl", {
                        failIfMajorPerformanceCaveat: !0
                    }) || e.getContext("experimental-webgl", {
                        failIfMajorPerformanceCaveat: !0
                    });
                    this._HasMajorPerformanceCaveat = !t
                } catch {
                    this._HasMajorPerformanceCaveat = !1
                }
            return this._HasMajorPerformanceCaveat
        },
        enumerable: !1,
        configurable: !0
    }),
    i.CeilingPOT = function(e) {
        return e--,
        e |= e >> 1,
        e |= e >> 2,
        e |= e >> 4,
        e |= e >> 8,
        e |= e >> 16,
        e++,
        e
    }
    ,
    i.FloorPOT = function(e) {
        return e = e | e >> 1,
        e = e | e >> 2,
        e = e | e >> 4,
        e = e | e >> 8,
        e = e | e >> 16,
        e - (e >> 1)
    }
    ,
    i.NearestPOT = function(e) {
        var t = i.CeilingPOT(e)
          , r = i.FloorPOT(e);
        return t - e > e - r ? r : t
    }
    ,
    i.GetExponentOfTwo = function(e, t, r) {
        r === void 0 && (r = 2);
        var n;
        switch (r) {
        case 1:
            n = i.FloorPOT(e);
            break;
        case 2:
            n = i.NearestPOT(e);
            break;
        case 3:
        default:
            n = i.CeilingPOT(e);
            break
        }
        return Math.min(n, t)
    }
    ,
    i.QueueNewFrame = function(e, t) {
        return IsWindowObjectExist() ? (t || (t = window),
        t.requestPostAnimationFrame ? t.requestPostAnimationFrame(e) : t.requestAnimationFrame ? t.requestAnimationFrame(e) : t.msRequestAnimationFrame ? t.msRequestAnimationFrame(e) : t.webkitRequestAnimationFrame ? t.webkitRequestAnimationFrame(e) : t.mozRequestAnimationFrame ? t.mozRequestAnimationFrame(e) : t.oRequestAnimationFrame ? t.oRequestAnimationFrame(e) : window.setTimeout(e, 16)) : typeof requestAnimationFrame != "undefined" ? requestAnimationFrame(e) : setTimeout(e, 16)
    }
    ,
    i.prototype.getHostDocument = function() {
        return this._renderingCanvas && this._renderingCanvas.ownerDocument ? this._renderingCanvas.ownerDocument : document
    }
    ,
    i.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: "Chrome/72.+?Mobile",
        capture: null,
        captureConstraint: null,
        targets: ["vao"]
    }, {
        key: "Chrome/73.+?Mobile",
        capture: null,
        captureConstraint: null,
        targets: ["vao"]
    }, {
        key: "Chrome/74.+?Mobile",
        capture: null,
        captureConstraint: null,
        targets: ["vao"]
    }, {
        key: "Mac OS.+Chrome/71",
        capture: null,
        captureConstraint: null,
        targets: ["vao"]
    }, {
        key: "Mac OS.+Chrome/72",
        capture: null,
        captureConstraint: null,
        targets: ["vao"]
    }],
    i._TextureLoaders = [],
    i.CollisionsEpsilon = .001,
    i._IsSupported = null,
    i._HasMajorPerformanceCaveat = null,
    i
}(), TimingTools = function() {
    function i() {}
    return i.SetImmediate = function(e) {
        IsWindowObjectExist() && window.setImmediate ? window.setImmediate(e) : setTimeout(e, 1)
    }
    ,
    i
}(), FileTools, _injectLTSFileTools = function(i, e, t, r, n, o, a, s, l, u) {
    FileTools = {
        DecodeBase64UrlToBinary: i,
        DecodeBase64UrlToString: e,
        DefaultRetryStrategy: t.DefaultRetryStrategy,
        BaseUrl: t.BaseUrl,
        CorsBehavior: t.CorsBehavior,
        PreprocessUrl: t.PreprocessUrl,
        IsBase64DataUrl: r,
        IsFileURL: n,
        LoadFile: o,
        LoadImage: a,
        ReadFile: s,
        RequestFile: l,
        SetCorsBehavior: u
    },
    Object.defineProperty(FileTools, "DefaultRetryStrategy", {
        get: function() {
            return t.DefaultRetryStrategy
        },
        set: function(c) {
            t.DefaultRetryStrategy = c
        }
    }),
    Object.defineProperty(FileTools, "BaseUrl", {
        get: function() {
            return t.BaseUrl
        },
        set: function(c) {
            t.BaseUrl = c
        }
    }),
    Object.defineProperty(FileTools, "PreprocessUrl", {
        get: function() {
            return t.PreprocessUrl
        },
        set: function(c) {
            t.PreprocessUrl = c
        }
    }),
    Object.defineProperty(FileTools, "CorsBehavior", {
        get: function() {
            return t.CorsBehavior
        },
        set: function(c) {
            t.CorsBehavior = c
        }
    })
}, base64DataUrlRegEx = new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i), LoadFileError = function(i) {
    __extends(e, i);
    function e(t, r) {
        var n = i.call(this, t) || this;
        return n.name = "LoadFileError",
        BaseError._setPrototypeOf(n, e.prototype),
        r instanceof WebRequest ? n.request = r : n.file = r,
        n
    }
    return e
}(BaseError), RequestFileError = function(i) {
    __extends(e, i);
    function e(t, r) {
        var n = i.call(this, t) || this;
        return n.request = r,
        n.name = "RequestFileError",
        BaseError._setPrototypeOf(n, e.prototype),
        n
    }
    return e
}(BaseError), ReadFileError = function(i) {
    __extends(e, i);
    function e(t, r) {
        var n = i.call(this, t) || this;
        return n.file = r,
        n.name = "ReadFileError",
        BaseError._setPrototypeOf(n, e.prototype),
        n
    }
    return e
}(BaseError), FileToolsOptions = {
    DefaultRetryStrategy: RetryStrategy.ExponentialBackoff(),
    BaseUrl: "",
    CorsBehavior: "anonymous",
    PreprocessUrl: function(i) {
        return i
    }
}, _CleanUrl = function(i) {
    return i = i.replace(/#/mg, "%23"),
    i
}, SetCorsBehavior = function(i, e) {
    if (!(i && i.indexOf("data:") === 0) && FileToolsOptions.CorsBehavior)
        if (typeof FileToolsOptions.CorsBehavior == "string" || FileToolsOptions.CorsBehavior instanceof String)
            e.crossOrigin = FileToolsOptions.CorsBehavior;
        else {
            var t = FileToolsOptions.CorsBehavior(i);
            t && (e.crossOrigin = t)
        }
}, LoadImage = function(i, e, t, r, n, o) {
    var a;
    n === void 0 && (n = "");
    var s, l = !1;
    i instanceof ArrayBuffer || ArrayBuffer.isView(i) ? typeof Blob != "undefined" ? (s = URL.createObjectURL(new Blob([i],{
        type: n
    })),
    l = !0) : s = "data:" + n + ";base64," + EncodeArrayBufferToBase64(i) : i instanceof Blob ? (s = URL.createObjectURL(i),
    l = !0) : (s = _CleanUrl(i),
    s = FileToolsOptions.PreprocessUrl(i));
    var u = EngineStore.LastCreatedEngine
      , c = function(y) {
        if (t) {
            var b = s || i.toString();
            t("Error while trying to load image: " + (b.indexOf("http") === 0 || b.length <= 128 ? b : b.slice(0, 128) + "..."), y)
        }
    };
    if (typeof Image == "undefined" || ((a = u == null ? void 0 : u._features.forceBitmapOverHTMLImageElement) !== null && a !== void 0 ? a : !1))
        return LoadFile(s, function(y) {
            u.createImageBitmap(new Blob([y],{
                type: n
            }), __assign({
                premultiplyAlpha: "none"
            }, o)).then(function(b) {
                e(b),
                l && URL.revokeObjectURL(s)
            }).catch(function(b) {
                t && t("Error while trying to load image: " + i, b)
            })
        }, void 0, r || void 0, !0, function(y, b) {
            c(b)
        }),
        null;
    var h = new Image;
    SetCorsBehavior(s, h);
    var f = function() {
        h.removeEventListener("load", f),
        h.removeEventListener("error", d),
        e(h),
        l && h.src && URL.revokeObjectURL(h.src)
    }
      , d = function(y) {
        h.removeEventListener("load", f),
        h.removeEventListener("error", d),
        c(y),
        l && h.src && URL.revokeObjectURL(h.src)
    };
    h.addEventListener("load", f),
    h.addEventListener("error", d);
    var _ = function() {
        h.src = s
    }
      , g = function() {
        r && r.loadImage(s, h)
    };
    if (s.substr(0, 5) !== "data:" && r && r.enableTexturesOffline)
        r.open(g, _);
    else {
        if (s.indexOf("file:") !== -1) {
            var m = decodeURIComponent(s.substring(5).toLowerCase());
            if (FilesInputStore.FilesToLoad[m]) {
                try {
                    var v;
                    try {
                        v = URL.createObjectURL(FilesInputStore.FilesToLoad[m])
                    } catch {
                        v = URL.createObjectURL(FilesInputStore.FilesToLoad[m])
                    }
                    h.src = v,
                    l = !0
                } catch {
                    h.src = ""
                }
                return h
            }
        }
        _()
    }
    return h
}, ReadFile = function(i, e, t, r, n) {
    var o = new FileReader
      , a = {
        onCompleteObservable: new Observable,
        abort: function() {
            return o.abort()
        }
    };
    return o.onloadend = function(s) {
        return a.onCompleteObservable.notifyObservers(a)
    }
    ,
    n && (o.onerror = function(s) {
        n(new ReadFileError("Unable to read " + i.name,i))
    }
    ),
    o.onload = function(s) {
        e(s.target.result)
    }
    ,
    t && (o.onprogress = t),
    r ? o.readAsArrayBuffer(i) : o.readAsText(i),
    a
}, LoadFile = function(i, e, t, r, n, o, a) {
    if (i.name)
        return ReadFile(i, e, t, n, o ? function(h) {
            o(void 0, h)
        }
        : void 0);
    var s = i;
    if (s.indexOf("file:") !== -1) {
        var l = decodeURIComponent(s.substring(5).toLowerCase());
        l.indexOf("./") === 0 && (l = l.substring(2));
        var u = FilesInputStore.FilesToLoad[l];
        if (u)
            return ReadFile(u, e, t, n, o ? function(h) {
                return o(void 0, new LoadFileError(h.message,h.file))
            }
            : void 0)
    }
    if (IsBase64DataUrl(s)) {
        var c = {
            onCompleteObservable: new Observable,
            abort: function() {
                return function() {}
            }
        };
        try {
            e(n ? DecodeBase64UrlToBinary(s) : DecodeBase64UrlToString(s))
        } catch (h) {
            o ? o(void 0, h) : Logger$2.Error(h.message || "Failed to parse the Data URL")
        }
        return TimingTools.SetImmediate(function() {
            c.onCompleteObservable.notifyObservers(c)
        }),
        c
    }
    return RequestFile(s, function(h, f) {
        e(h, f ? f.responseURL : void 0)
    }, t, r, n, o ? function(h) {
        o(h.request, new LoadFileError(h.message,h.request))
    }
    : void 0, a)
}, RequestFile = function(i, e, t, r, n, o, a) {
    i = _CleanUrl(i),
    i = FileToolsOptions.PreprocessUrl(i);
    var s = FileToolsOptions.BaseUrl + i
      , l = !1
      , u = {
        onCompleteObservable: new Observable,
        abort: function() {
            return l = !0
        }
    }
      , c = function() {
        var d = new WebRequest
          , _ = null;
        u.abort = function() {
            l = !0,
            d.readyState !== (XMLHttpRequest.DONE || 4) && d.abort(),
            _ !== null && (clearTimeout(_),
            _ = null)
        }
        ;
        var g = function(v) {
            var y = v.message || "Unknown error";
            o ? o(new RequestFileError(y,d)) : Logger$2.Error(y)
        }
          , m = function(v) {
            if (d.open("GET", s),
            a)
                try {
                    a(d)
                } catch (T) {
                    g(T);
                    return
                }
            n && (d.responseType = "arraybuffer"),
            t && d.addEventListener("progress", t);
            var y = function() {
                d.removeEventListener("loadend", y),
                u.onCompleteObservable.notifyObservers(u),
                u.onCompleteObservable.clear()
            };
            d.addEventListener("loadend", y);
            var b = function() {
                if (!l && d.readyState === (XMLHttpRequest.DONE || 4)) {
                    if (d.removeEventListener("readystatechange", b),
                    d.status >= 200 && d.status < 300 || d.status === 0 && (!IsWindowObjectExist() || IsFileURL())) {
                        try {
                            e(n ? d.response : d.responseText, d)
                        } catch (S) {
                            g(S)
                        }
                        return
                    }
                    var T = FileToolsOptions.DefaultRetryStrategy;
                    if (T) {
                        var C = T(s, d, v);
                        if (C !== -1) {
                            d.removeEventListener("loadend", y),
                            d = new WebRequest,
                            _ = setTimeout(function() {
                                return m(v + 1)
                            }, C);
                            return
                        }
                    }
                    var A = new RequestFileError("Error status: " + d.status + " " + d.statusText + " - Unable to load " + s,d);
                    o && o(A)
                }
            };
            d.addEventListener("readystatechange", b),
            d.send()
        };
        m(0)
    };
    if (r && r.enableSceneOffline) {
        var h = function(d) {
            d && d.status > 400 ? o && o(d) : c()
        }
          , f = function() {
            r && r.loadFile(FileToolsOptions.BaseUrl + i, function(d) {
                l || e(d),
                u.onCompleteObservable.notifyObservers(u)
            }, t ? function(d) {
                l || t(d)
            }
            : void 0, h, n)
        };
        r.open(f, h)
    } else
        c();
    return u
}, IsFileURL = function() {
    return typeof location != "undefined" && location.protocol === "file:"
}, IsBase64DataUrl = function(i) {
    return base64DataUrlRegEx.test(i)
};
function DecodeBase64UrlToBinary(i) {
    return DecodeBase64ToBinary(i.split(",")[1])
}
var DecodeBase64UrlToString = function(i) {
    return DecodeBase64ToString(i.split(",")[1])
}
  , initSideEffects$1 = function() {
    ThinEngine._FileToolsLoadImage = LoadImage,
    ThinEngine._FileToolsLoadFile = LoadFile,
    ShaderProcessor._FileToolsLoadFile = LoadFile
};
initSideEffects$1();
_injectLTSFileTools(DecodeBase64UrlToBinary, DecodeBase64UrlToString, FileToolsOptions, IsBase64DataUrl, IsFileURL, LoadFile, LoadImage, ReadFile, RequestFile, SetCorsBehavior);
var PromiseStates;
(function(i) {
    i[i.Pending = 0] = "Pending",
    i[i.Fulfilled = 1] = "Fulfilled",
    i[i.Rejected = 2] = "Rejected"
}
)(PromiseStates || (PromiseStates = {}));
var FulFillmentAgregator = function() {
    function i() {
        this.count = 0,
        this.target = 0,
        this.results = []
    }
    return i
}()
  , InternalPromise = function() {
    function i(e) {
        var t = this;
        if (this._state = PromiseStates.Pending,
        this._children = new Array,
        this._rejectWasConsumed = !1,
        !!e)
            try {
                e(function(r) {
                    t._resolve(r)
                }, function(r) {
                    t._reject(r)
                })
            } catch (r) {
                this._reject(r)
            }
    }
    return Object.defineProperty(i.prototype, "_result", {
        get: function() {
            return this._resultValue
        },
        set: function(e) {
            this._resultValue = e,
            this._parent && this._parent._result === void 0 && (this._parent._result = e)
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.catch = function(e) {
        return this.then(void 0, e)
    }
    ,
    i.prototype.then = function(e, t) {
        var r = this
          , n = new i;
        return n._onFulfilled = e,
        n._onRejected = t,
        this._children.push(n),
        n._parent = this,
        this._state !== PromiseStates.Pending && setTimeout(function() {
            r._state === PromiseStates.Fulfilled || r._rejectWasConsumed ? n._resolve(r._result) : n._reject(r._reason)
        }),
        n
    }
    ,
    i.prototype._moveChildren = function(e) {
        var t, r = this;
        if ((t = this._children).push.apply(t, e.splice(0, e.length)),
        this._children.forEach(function(u) {
            u._parent = r
        }),
        this._state === PromiseStates.Fulfilled)
            for (var n = 0, o = this._children; n < o.length; n++) {
                var a = o[n];
                a._resolve(this._result)
            }
        else if (this._state === PromiseStates.Rejected)
            for (var s = 0, l = this._children; s < l.length; s++) {
                var a = l[s];
                a._reject(this._reason)
            }
    }
    ,
    i.prototype._resolve = function(e) {
        try {
            this._state = PromiseStates.Fulfilled;
            var t = null;
            if (this._onFulfilled && (t = this._onFulfilled(e)),
            t != null)
                if (t._state !== void 0) {
                    var r = t;
                    r._parent = this,
                    r._moveChildren(this._children),
                    e = r._result
                } else
                    e = t;
            this._result = e;
            for (var n = 0, o = this._children; n < o.length; n++) {
                var a = o[n];
                a._resolve(e)
            }
            this._children.length = 0,
            delete this._onFulfilled,
            delete this._onRejected
        } catch (s) {
            this._reject(s, !0)
        }
    }
    ,
    i.prototype._reject = function(e, t) {
        if (t === void 0 && (t = !1),
        this._state = PromiseStates.Rejected,
        this._reason = e,
        this._onRejected && !t)
            try {
                this._onRejected(e),
                this._rejectWasConsumed = !0
            } catch (a) {
                e = a
            }
        for (var r = 0, n = this._children; r < n.length; r++) {
            var o = n[r];
            this._rejectWasConsumed ? o._resolve(null) : o._reject(e)
        }
        this._children.length = 0,
        delete this._onFulfilled,
        delete this._onRejected
    }
    ,
    i.resolve = function(e) {
        var t = new i;
        return t._resolve(e),
        t
    }
    ,
    i._RegisterForFulfillment = function(e, t, r) {
        e.then(function(n) {
            return t.results[r] = n,
            t.count++,
            t.count === t.target && t.rootPromise._resolve(t.results),
            null
        }, function(n) {
            t.rootPromise._state !== PromiseStates.Rejected && t.rootPromise._reject(n)
        })
    }
    ,
    i.all = function(e) {
        var t = new i
          , r = new FulFillmentAgregator;
        if (r.target = e.length,
        r.rootPromise = t,
        e.length)
            for (var n = 0; n < e.length; n++)
                i._RegisterForFulfillment(e[n], r, n);
        else
            t._resolve([]);
        return t
    }
    ,
    i.race = function(e) {
        var t = new i;
        if (e.length)
            for (var r = 0, n = e; r < n.length; r++) {
                var o = n[r];
                o.then(function(a) {
                    return t && (t._resolve(a),
                    t = null),
                    null
                }, function(a) {
                    t && (t._reject(a),
                    t = null)
                })
            }
        return t
    }
    ,
    i
}()
  , PromisePolyfill = function() {
    function i() {}
    return i.Apply = function(e) {
        if (e === void 0 && (e = !1),
        e || typeof Promise == "undefined") {
            var t = window;
            t.Promise = InternalPromise
        }
    }
    ,
    i
}()
  , _RegisteredTypes = {};
function RegisterClass(i, e) {
    _RegisteredTypes[i] = e
}
function GetClass(i) {
    return _RegisteredTypes[i]
}
var InstantiationTools = function() {
    function i() {}
    return i.Instantiate = function(e) {
        if (this.RegisteredExternalClasses && this.RegisteredExternalClasses[e])
            return this.RegisteredExternalClasses[e];
        var t = GetClass(e);
        if (t)
            return t;
        Logger$2.Warn(e + " not found, you may have missed an import.");
        for (var r = e.split("."), n = window || this, o = 0, a = r.length; o < a; o++)
            n = n[r[o]];
        return typeof n != "function" ? null : n
    }
    ,
    i.RegisteredExternalClasses = {},
    i
}();
function RandomGUID() {
    return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(i) {
        var e = Math.random() * 16 | 0
          , t = i === "x" ? e : e & 3 | 8;
        return t.toString(16)
    })
}
var SliceTools = function() {
    function i() {}
    return i.Slice = function(e, t, r) {
        return e.slice ? e.slice(t, r) : Array.prototype.slice.call(e, t, r)
    }
    ,
    i.SliceToArray = function(e, t, r) {
        return Array.isArray(e) ? e.slice(t, r) : Array.prototype.slice.call(e, t, r)
    }
    ,
    i
}()
  , Tools = function() {
    function i() {}
    return Object.defineProperty(i, "BaseUrl", {
        get: function() {
            return FileToolsOptions.BaseUrl
        },
        set: function(e) {
            FileToolsOptions.BaseUrl = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i, "DefaultRetryStrategy", {
        get: function() {
            return FileToolsOptions.DefaultRetryStrategy
        },
        set: function(e) {
            FileToolsOptions.DefaultRetryStrategy = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i, "CorsBehavior", {
        get: function() {
            return FileToolsOptions.CorsBehavior
        },
        set: function(e) {
            FileToolsOptions.CorsBehavior = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i, "UseFallbackTexture", {
        get: function() {
            return EngineStore.UseFallbackTexture
        },
        set: function(e) {
            EngineStore.UseFallbackTexture = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i, "RegisteredExternalClasses", {
        get: function() {
            return InstantiationTools.RegisteredExternalClasses
        },
        set: function(e) {
            InstantiationTools.RegisteredExternalClasses = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i, "fallbackTexture", {
        get: function() {
            return EngineStore.FallbackTexture
        },
        set: function(e) {
            EngineStore.FallbackTexture = e
        },
        enumerable: !1,
        configurable: !0
    }),
    i.FetchToRef = function(e, t, r, n, o, a) {
        var s = Math.abs(e) * r % r | 0
          , l = Math.abs(t) * n % n | 0
          , u = (s + l * r) * 4;
        a.r = o[u] / 255,
        a.g = o[u + 1] / 255,
        a.b = o[u + 2] / 255,
        a.a = o[u + 3] / 255
    }
    ,
    i.Mix = function(e, t, r) {
        return e * (1 - r) + t * r
    }
    ,
    i.Instantiate = function(e) {
        return InstantiationTools.Instantiate(e)
    }
    ,
    i.Slice = function(e, t, r) {
        return SliceTools.Slice(e, t, r)
    }
    ,
    i.SliceToArray = function(e, t, r) {
        return SliceTools.SliceToArray(e, t, r)
    }
    ,
    i.SetImmediate = function(e) {
        TimingTools.SetImmediate(e)
    }
    ,
    i.IsExponentOfTwo = function(e) {
        var t = 1;
        do
            t *= 2;
        while (t < e);
        return t === e
    }
    ,
    i.FloatRound = function(e) {
        return Math.fround ? Math.fround(e) : (i._tmpFloatArray[0] = e,
        i._tmpFloatArray[0])
    }
    ,
    i.GetFilename = function(e) {
        var t = e.lastIndexOf("/");
        return t < 0 ? e : e.substring(t + 1)
    }
    ,
    i.GetFolderPath = function(e, t) {
        t === void 0 && (t = !1);
        var r = e.lastIndexOf("/");
        return r < 0 ? t ? e : "" : e.substring(0, r + 1)
    }
    ,
    i.ToDegrees = function(e) {
        return e * 180 / Math.PI
    }
    ,
    i.ToRadians = function(e) {
        return e * Math.PI / 180
    }
    ,
    i.MakeArray = function(e, t) {
        return t !== !0 && (e === void 0 || e == null) ? null : Array.isArray(e) ? e : [e]
    }
    ,
    i.GetPointerPrefix = function(e) {
        var t = "pointer";
        return IsWindowObjectExist() && !window.PointerEvent && IsNavigatorAvailable() && !navigator.pointerEnabled && (t = "mouse"),
        e._badDesktopOS && !e._badOS && !(document && "ontouchend"in document) && (t = "mouse"),
        t
    }
    ,
    i.SetCorsBehavior = function(e, t) {
        SetCorsBehavior(e, t)
    }
    ,
    i.CleanUrl = function(e) {
        return e = e.replace(/#/gm, "%23"),
        e
    }
    ,
    Object.defineProperty(i, "PreprocessUrl", {
        get: function() {
            return FileToolsOptions.PreprocessUrl
        },
        set: function(e) {
            FileToolsOptions.PreprocessUrl = e
        },
        enumerable: !1,
        configurable: !0
    }),
    i.LoadImage = function(e, t, r, n, o, a) {
        return LoadImage(e, t, r, n, o, a)
    }
    ,
    i.LoadFile = function(e, t, r, n, o, a) {
        return LoadFile(e, t, r, n, o, a)
    }
    ,
    i.LoadFileAsync = function(e, t) {
        return t === void 0 && (t = !0),
        new Promise(function(r, n) {
            LoadFile(e, function(o) {
                r(o)
            }, void 0, void 0, t, function(o, a) {
                n(a)
            })
        }
        )
    }
    ,
    i.LoadScript = function(e, t, r, n) {
        if (!!IsWindowObjectExist()) {
            var o = document.getElementsByTagName("head")[0]
              , a = document.createElement("script");
            a.setAttribute("type", "text/javascript"),
            a.setAttribute("src", e),
            n && (a.id = n),
            a.onload = function() {
                t && t()
            }
            ,
            a.onerror = function(s) {
                r && r("Unable to load script '" + e + "'", s)
            }
            ,
            o.appendChild(a)
        }
    }
    ,
    i.LoadScriptAsync = function(e, t) {
        var r = this;
        return new Promise(function(n, o) {
            r.LoadScript(e, function() {
                n()
            }, function(a, s) {
                o(s)
            })
        }
        )
    }
    ,
    i.ReadFileAsDataURL = function(e, t, r) {
        var n = new FileReader
          , o = {
            onCompleteObservable: new Observable,
            abort: function() {
                return n.abort()
            }
        };
        return n.onloadend = function(a) {
            o.onCompleteObservable.notifyObservers(o)
        }
        ,
        n.onload = function(a) {
            t(a.target.result)
        }
        ,
        n.onprogress = r,
        n.readAsDataURL(e),
        o
    }
    ,
    i.ReadFile = function(e, t, r, n, o) {
        return ReadFile(e, t, r, n, o)
    }
    ,
    i.FileAsURL = function(e) {
        var t = new Blob([e])
          , r = window.URL || window.webkitURL
          , n = r.createObjectURL(t);
        return n
    }
    ,
    i.Format = function(e, t) {
        return t === void 0 && (t = 2),
        e.toFixed(t)
    }
    ,
    i.DeepCopy = function(e, t, r, n) {
        DeepCopier.DeepCopy(e, t, r, n)
    }
    ,
    i.IsEmpty = function(e) {
        for (var t in e)
            if (e.hasOwnProperty(t))
                return !1;
        return !0
    }
    ,
    i.RegisterTopRootEvents = function(e, t) {
        for (var r = 0; r < t.length; r++) {
            var n = t[r];
            e.addEventListener(n.name, n.handler, !1);
            try {
                window.parent && window.parent.addEventListener(n.name, n.handler, !1)
            } catch {}
        }
    }
    ,
    i.UnregisterTopRootEvents = function(e, t) {
        for (var r = 0; r < t.length; r++) {
            var n = t[r];
            e.removeEventListener(n.name, n.handler);
            try {
                e.parent && e.parent.removeEventListener(n.name, n.handler)
            } catch {}
        }
    }
    ,
    i.DumpFramebuffer = function(e, t, r, n, o, a) {
        return o === void 0 && (o = "image/png"),
        __awaiter(this, void 0, void 0, function() {
            var s, l;
            return __generator(this, function(u) {
                switch (u.label) {
                case 0:
                    return [4, r.readPixels(0, 0, e, t)];
                case 1:
                    return s = u.sent(),
                    l = new Uint8Array(s.buffer),
                    i.DumpData(e, t, l, n, o, a, !0),
                    [2]
                }
            })
        })
    }
    ,
    i.DumpData = function(e, t, r, n, o, a, s, l, u) {
        o === void 0 && (o = "image/png"),
        s === void 0 && (s = !1),
        l === void 0 && (l = !1),
        i._ScreenshotCanvas || (i._ScreenshotCanvas = document.createElement("canvas")),
        i._ScreenshotCanvas.width = e,
        i._ScreenshotCanvas.height = t;
        var c = i._ScreenshotCanvas.getContext("2d");
        if (c) {
            if (r instanceof Float32Array) {
                for (var h = new Uint8Array(r.length), f = r.length; f--; ) {
                    var d = r[f];
                    h[f] = d < 0 ? 0 : d > 1 ? 1 : Math.round(d * 255)
                }
                r = h
            }
            var _ = c.createImageData(e, t)
              , g = _.data;
            g.set(r),
            c.putImageData(_, 0, 0);
            var m = i._ScreenshotCanvas;
            if (s) {
                var v = document.createElement("canvas");
                v.width = e,
                v.height = t;
                var y = v.getContext("2d");
                if (!y)
                    return;
                y.translate(0, t),
                y.scale(1, -1),
                y.drawImage(i._ScreenshotCanvas, 0, 0),
                m = v
            }
            l ? i.ToBlob(m, function(b) {
                var T = new FileReader;
                T.onload = function(C) {
                    var A = C.target.result;
                    n && n(A)
                }
                ,
                T.readAsArrayBuffer(b)
            }, o, u) : i.EncodeScreenshotCanvasData(n, o, a, m, u)
        }
    }
    ,
    i.DumpDataAsync = function(e, t, r, n, o, a, s, l) {
        return n === void 0 && (n = "image/png"),
        a === void 0 && (a = !1),
        s === void 0 && (s = !1),
        new Promise(function(u) {
            i.DumpData(e, t, r, function(c) {
                return u(c)
            }, n, o, a, s, l)
        }
        )
    }
    ,
    i.ToBlob = function(e, t, r, n) {
        r === void 0 && (r = "image/png"),
        e.toBlob || (e.toBlob = function(o, a, s) {
            var l = this;
            setTimeout(function() {
                for (var u = atob(l.toDataURL(a, s).split(",")[1]), c = u.length, h = new Uint8Array(c), f = 0; f < c; f++)
                    h[f] = u.charCodeAt(f);
                o(new Blob([h]))
            })
        }
        ),
        e.toBlob(function(o) {
            t(o)
        }, r, n)
    }
    ,
    i.EncodeScreenshotCanvasData = function(e, t, r, n, o) {
        if (t === void 0 && (t = "image/png"),
        e) {
            var a = (n != null ? n : i._ScreenshotCanvas).toDataURL(t, o);
            e(a)
        } else
            this.ToBlob(n != null ? n : i._ScreenshotCanvas, function(s) {
                if ("download"in document.createElement("a")) {
                    if (!r) {
                        var l = new Date
                          , u = (l.getFullYear() + "-" + (l.getMonth() + 1)).slice(2) + "-" + l.getDate() + "_" + l.getHours() + "-" + ("0" + l.getMinutes()).slice(-2);
                        r = "screenshot_" + u + ".png"
                    }
                    i.Download(s, r)
                } else {
                    var c = URL.createObjectURL(s)
                      , h = window.open("");
                    if (!h)
                        return;
                    var f = h.document.createElement("img");
                    f.onload = function() {
                        URL.revokeObjectURL(c)
                    }
                    ,
                    f.src = c,
                    h.document.body.appendChild(f)
                }
            }, t, o)
    }
    ,
    i.Download = function(e, t) {
        if (navigator && navigator.msSaveBlob) {
            navigator.msSaveBlob(e, t);
            return
        }
        var r = window.URL.createObjectURL(e)
          , n = document.createElement("a");
        document.body.appendChild(n),
        n.style.display = "none",
        n.href = r,
        n.download = t,
        n.addEventListener("click", function() {
            n.parentElement && n.parentElement.removeChild(n)
        }),
        n.click(),
        window.URL.revokeObjectURL(r)
    }
    ,
    i.BackCompatCameraNoPreventDefault = function(e) {
        return typeof e[0] == "boolean" ? e[0] : typeof e[1] == "boolean" ? e[1] : !1
    }
    ,
    i.CreateScreenshot = function(e, t, r, n, o) {
        throw _WarnImport("ScreenshotTools")
    }
    ,
    i.CreateScreenshotAsync = function(e, t, r, n) {
        throw _WarnImport("ScreenshotTools")
    }
    ,
    i.CreateScreenshotUsingRenderTarget = function(e, t, r, n, o, a, s, l) {
        throw _WarnImport("ScreenshotTools")
    }
    ,
    i.CreateScreenshotUsingRenderTargetAsync = function(e, t, r, n, o, a, s) {
        throw _WarnImport("ScreenshotTools")
    }
    ,
    i.RandomId = function() {
        return RandomGUID()
    }
    ,
    i.IsBase64 = function(e) {
        return IsBase64DataUrl(e)
    }
    ,
    i.DecodeBase64 = function(e) {
        return DecodeBase64UrlToBinary(e)
    }
    ,
    Object.defineProperty(i, "errorsCount", {
        get: function() {
            return Logger$2.errorsCount
        },
        enumerable: !1,
        configurable: !0
    }),
    i.Log = function(e) {
        Logger$2.Log(e)
    }
    ,
    i.Warn = function(e) {
        Logger$2.Warn(e)
    }
    ,
    i.Error = function(e) {
        Logger$2.Error(e)
    }
    ,
    Object.defineProperty(i, "LogCache", {
        get: function() {
            return Logger$2.LogCache
        },
        enumerable: !1,
        configurable: !0
    }),
    i.ClearLogCache = function() {
        Logger$2.ClearLogCache()
    }
    ,
    Object.defineProperty(i, "LogLevels", {
        set: function(e) {
            Logger$2.LogLevels = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i, "PerformanceLogLevel", {
        set: function(e) {
            if ((e & i.PerformanceUserMarkLogLevel) === i.PerformanceUserMarkLogLevel) {
                i.StartPerformanceCounter = i._StartUserMark,
                i.EndPerformanceCounter = i._EndUserMark;
                return
            }
            if ((e & i.PerformanceConsoleLogLevel) === i.PerformanceConsoleLogLevel) {
                i.StartPerformanceCounter = i._StartPerformanceConsole,
                i.EndPerformanceCounter = i._EndPerformanceConsole;
                return
            }
            i.StartPerformanceCounter = i._StartPerformanceCounterDisabled,
            i.EndPerformanceCounter = i._EndPerformanceCounterDisabled
        },
        enumerable: !1,
        configurable: !0
    }),
    i._StartPerformanceCounterDisabled = function(e, t) {}
    ,
    i._EndPerformanceCounterDisabled = function(e, t) {}
    ,
    i._StartUserMark = function(e, t) {
        if (t === void 0 && (t = !0),
        !i._performance) {
            if (!IsWindowObjectExist())
                return;
            i._performance = window.performance
        }
        !t || !i._performance.mark || i._performance.mark(e + "-Begin")
    }
    ,
    i._EndUserMark = function(e, t) {
        t === void 0 && (t = !0),
        !(!t || !i._performance.mark) && (i._performance.mark(e + "-End"),
        i._performance.measure(e, e + "-Begin", e + "-End"))
    }
    ,
    i._StartPerformanceConsole = function(e, t) {
        t === void 0 && (t = !0),
        t && (i._StartUserMark(e, t),
        console.time && console.time(e))
    }
    ,
    i._EndPerformanceConsole = function(e, t) {
        t === void 0 && (t = !0),
        t && (i._EndUserMark(e, t),
        console.timeEnd(e))
    }
    ,
    Object.defineProperty(i, "Now", {
        get: function() {
            return PrecisionDate.Now
        },
        enumerable: !1,
        configurable: !0
    }),
    i.GetClassName = function(e, t) {
        t === void 0 && (t = !1);
        var r = null;
        if (!t && e.getClassName)
            r = e.getClassName();
        else {
            if (e instanceof Object) {
                var n = t ? e : Object.getPrototypeOf(e);
                r = n.constructor.__bjsclassName__
            }
            r || (r = typeof e)
        }
        return r
    }
    ,
    i.First = function(e, t) {
        for (var r = 0, n = e; r < n.length; r++) {
            var o = n[r];
            if (t(o))
                return o
        }
        return null
    }
    ,
    i.getFullClassName = function(e, t) {
        t === void 0 && (t = !1);
        var r = null
          , n = null;
        if (!t && e.getClassName)
            r = e.getClassName();
        else {
            if (e instanceof Object) {
                var o = t ? e : Object.getPrototypeOf(e);
                r = o.constructor.__bjsclassName__,
                n = o.constructor.__bjsmoduleName__
            }
            r || (r = typeof e)
        }
        return r ? (n != null ? n + "." : "") + r : null
    }
    ,
    i.DelayAsync = function(e) {
        return new Promise(function(t) {
            setTimeout(function() {
                t()
            }, e)
        }
        )
    }
    ,
    i.IsSafari = function() {
        return IsNavigatorAvailable() ? /^((?!chrome|android).)*safari/i.test(navigator.userAgent) : !1
    }
    ,
    i.UseCustomRequestHeaders = !1,
    i.CustomRequestHeaders = WebRequest.CustomRequestHeaders,
    i._tmpFloatArray = new Float32Array(1),
    i.GetDOMTextContent = GetDOMTextContent,
    i.GetAbsoluteUrl = typeof document == "object" ? function(e) {
        var t = document.createElement("a");
        return t.href = e,
        t.href
    }
    : typeof URL == "function" && typeof location == "object" ? function(e) {
        return new URL(e,location.origin).href
    }
    : function(e) {
        throw new Error("Unable to get absolute URL. Override BABYLON.Tools.GetAbsoluteUrl to a custom implementation for the current context.")
    }
    ,
    i.NoneLogLevel = Logger$2.NoneLogLevel,
    i.MessageLogLevel = Logger$2.MessageLogLevel,
    i.WarningLogLevel = Logger$2.WarningLogLevel,
    i.ErrorLogLevel = Logger$2.ErrorLogLevel,
    i.AllLogLevel = Logger$2.AllLogLevel,
    i.IsWindowObjectExist = IsWindowObjectExist,
    i.PerformanceNoneLogLevel = 0,
    i.PerformanceUserMarkLogLevel = 1,
    i.PerformanceConsoleLogLevel = 2,
    i.StartPerformanceCounter = i._StartPerformanceCounterDisabled,
    i.EndPerformanceCounter = i._EndPerformanceCounterDisabled,
    i
}()
  , AsyncLoop = function() {
    function i(e, t, r, n) {
        n === void 0 && (n = 0),
        this.iterations = e,
        this.index = n - 1,
        this._done = !1,
        this._fn = t,
        this._successCallback = r
    }
    return i.prototype.executeNext = function() {
        this._done || (this.index + 1 < this.iterations ? (++this.index,
        this._fn(this)) : this.breakLoop())
    }
    ,
    i.prototype.breakLoop = function() {
        this._done = !0,
        this._successCallback()
    }
    ,
    i.Run = function(e, t, r, n) {
        n === void 0 && (n = 0);
        var o = new i(e,t,r,n);
        return o.executeNext(),
        o
    }
    ,
    i.SyncAsyncForLoop = function(e, t, r, n, o, a) {
        return a === void 0 && (a = 0),
        i.Run(Math.ceil(e / t), function(s) {
            o && o() ? s.breakLoop() : setTimeout(function() {
                for (var l = 0; l < t; ++l) {
                    var u = s.index * t + l;
                    if (u >= e)
                        break;
                    if (r(u),
                    o && o()) {
                        s.breakLoop();
                        break
                    }
                }
                s.executeNext()
            }, a)
        }, n)
    }
    ,
    i
}();
EngineStore.FallbackTexture = "data:image/jpg;base64, ";
PromisePolyfill.Apply();
var SmartArray = function() {
    function i(e) {
        this.length = 0,
        this.data = new Array(e),
        this._id = i._GlobalId++
    }
    return i.prototype.push = function(e) {
        this.data[this.length++] = e,
        this.length > this.data.length && (this.data.length *= 2)
    }
    ,
    i.prototype.forEach = function(e) {
        for (var t = 0; t < this.length; t++)
            e(this.data[t])
    }
    ,
    i.prototype.sort = function(e) {
        this.data.sort(e)
    }
    ,
    i.prototype.reset = function() {
        this.length = 0
    }
    ,
    i.prototype.dispose = function() {
        this.reset(),
        this.data && (this.data.length = 0,
        this.data = [])
    }
    ,
    i.prototype.concat = function(e) {
        if (e.length !== 0) {
            this.length + e.length > this.data.length && (this.data.length = (this.length + e.length) * 2);
            for (var t = 0; t < e.length; t++)
                this.data[this.length++] = (e.data || e)[t]
        }
    }
    ,
    i.prototype.indexOf = function(e) {
        var t = this.data.indexOf(e);
        return t >= this.length ? -1 : t
    }
    ,
    i.prototype.contains = function(e) {
        return this.indexOf(e) !== -1
    }
    ,
    i._GlobalId = 0,
    i
}()
  , SmartArrayNoDuplicate = function(i) {
    __extends(e, i);
    function e() {
        var t = i !== null && i.apply(this, arguments) || this;
        return t._duplicateId = 0,
        t
    }
    return e.prototype.push = function(t) {
        i.prototype.push.call(this, t),
        t.__smartArrayFlags || (t.__smartArrayFlags = {}),
        t.__smartArrayFlags[this._id] = this._duplicateId
    }
    ,
    e.prototype.pushNoDuplicate = function(t) {
        return t.__smartArrayFlags && t.__smartArrayFlags[this._id] === this._duplicateId ? !1 : (this.push(t),
        !0)
    }
    ,
    e.prototype.reset = function() {
        i.prototype.reset.call(this),
        this._duplicateId++
    }
    ,
    e.prototype.concatWithNoDuplicate = function(t) {
        if (t.length !== 0) {
            this.length + t.length > this.data.length && (this.data.length = (this.length + t.length) * 2);
            for (var r = 0; r < t.length; r++) {
                var n = (t.data || t)[r];
                this.pushNoDuplicate(n)
            }
        }
    }
    ,
    e
}(SmartArray)
  , StringDictionary = function() {
    function i() {
        this._count = 0,
        this._data = {}
    }
    return i.prototype.copyFrom = function(e) {
        var t = this;
        this.clear(),
        e.forEach(function(r, n) {
            return t.add(r, n)
        })
    }
    ,
    i.prototype.get = function(e) {
        var t = this._data[e];
        if (t !== void 0)
            return t
    }
    ,
    i.prototype.getOrAddWithFactory = function(e, t) {
        var r = this.get(e);
        return r !== void 0 || (r = t(e),
        r && this.add(e, r)),
        r
    }
    ,
    i.prototype.getOrAdd = function(e, t) {
        var r = this.get(e);
        return r !== void 0 ? r : (this.add(e, t),
        t)
    }
    ,
    i.prototype.contains = function(e) {
        return this._data[e] !== void 0
    }
    ,
    i.prototype.add = function(e, t) {
        return this._data[e] !== void 0 ? !1 : (this._data[e] = t,
        ++this._count,
        !0)
    }
    ,
    i.prototype.set = function(e, t) {
        return this._data[e] === void 0 ? !1 : (this._data[e] = t,
        !0)
    }
    ,
    i.prototype.getAndRemove = function(e) {
        var t = this.get(e);
        return t !== void 0 ? (delete this._data[e],
        --this._count,
        t) : null
    }
    ,
    i.prototype.remove = function(e) {
        return this.contains(e) ? (delete this._data[e],
        --this._count,
        !0) : !1
    }
    ,
    i.prototype.clear = function() {
        this._data = {},
        this._count = 0
    }
    ,
    Object.defineProperty(i.prototype, "count", {
        get: function() {
            return this._count
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.forEach = function(e) {
        for (var t in this._data) {
            var r = this._data[t];
            e(t, r)
        }
    }
    ,
    i.prototype.first = function(e) {
        for (var t in this._data) {
            var r = this._data[t]
              , n = e(t, r);
            if (n)
                return n
        }
        return null
    }
    ,
    i
}()
  , AndOrNotEvaluator = function() {
    function i() {}
    return i.Eval = function(e, t) {
        return e.match(/\([^\(\)]*\)/g) ? e = e.replace(/\([^\(\)]*\)/g, function(r) {
            return r = r.slice(1, r.length - 1),
            i._HandleParenthesisContent(r, t)
        }) : e = i._HandleParenthesisContent(e, t),
        e === "true" ? !0 : e === "false" ? !1 : i.Eval(e, t)
    }
    ,
    i._HandleParenthesisContent = function(e, t) {
        t = t || function(c) {
            return c === "true"
        }
        ;
        var r, n = e.split("||");
        for (var o in n)
            if (n.hasOwnProperty(o)) {
                var a = i._SimplifyNegation(n[o].trim())
                  , s = a.split("&&");
                if (s.length > 1)
                    for (var l = 0; l < s.length; ++l) {
                        var u = i._SimplifyNegation(s[l].trim());
                        if (u !== "true" && u !== "false" ? u[0] === "!" ? r = !t(u.substring(1)) : r = t(u) : r = u === "true",
                        !r) {
                            a = "false";
                            break
                        }
                    }
                if (r || a === "true") {
                    r = !0;
                    break
                }
                a !== "true" && a !== "false" ? a[0] === "!" ? r = !t(a.substring(1)) : r = t(a) : r = a === "true"
            }
        return r ? "true" : "false"
    }
    ,
    i._SimplifyNegation = function(e) {
        return e = e.replace(/^[\s!]+/, function(t) {
            return t = t.replace(/[\s]/g, function() {
                return ""
            }),
            t.length % 2 ? "!" : ""
        }),
        e = e.trim(),
        e === "!true" ? e = "false" : e === "!false" && (e = "true"),
        e
    }
    ,
    i
}()
  , Tags = function() {
    function i() {}
    return i.EnableFor = function(e) {
        e._tags = e._tags || {},
        e.hasTags = function() {
            return i.HasTags(e)
        }
        ,
        e.addTags = function(t) {
            return i.AddTagsTo(e, t)
        }
        ,
        e.removeTags = function(t) {
            return i.RemoveTagsFrom(e, t)
        }
        ,
        e.matchesTagsQuery = function(t) {
            return i.MatchesQuery(e, t)
        }
    }
    ,
    i.DisableFor = function(e) {
        delete e._tags,
        delete e.hasTags,
        delete e.addTags,
        delete e.removeTags,
        delete e.matchesTagsQuery
    }
    ,
    i.HasTags = function(e) {
        if (!e._tags)
            return !1;
        var t = e._tags;
        for (var r in t)
            if (t.hasOwnProperty(r))
                return !0;
        return !1
    }
    ,
    i.GetTags = function(e, t) {
        if (t === void 0 && (t = !0),
        !e._tags)
            return null;
        if (t) {
            var r = [];
            for (var n in e._tags)
                e._tags.hasOwnProperty(n) && e._tags[n] === !0 && r.push(n);
            return r.join(" ")
        } else
            return e._tags
    }
    ,
    i.AddTagsTo = function(e, t) {
        if (!!t && typeof t == "string") {
            var r = t.split(" ");
            r.forEach(function(n, o, a) {
                i._AddTagTo(e, n)
            })
        }
    }
    ,
    i._AddTagTo = function(e, t) {
        t = t.trim(),
        !(t === "" || t === "true" || t === "false") && (t.match(/[\s]/) || t.match(/^([!]|([|]|[&]){2})/) || (i.EnableFor(e),
        e._tags[t] = !0))
    }
    ,
    i.RemoveTagsFrom = function(e, t) {
        if (!!i.HasTags(e)) {
            var r = t.split(" ");
            for (var n in r)
                i._RemoveTagFrom(e, r[n])
        }
    }
    ,
    i._RemoveTagFrom = function(e, t) {
        delete e._tags[t]
    }
    ,
    i.MatchesQuery = function(e, t) {
        return t === void 0 ? !0 : t === "" ? i.HasTags(e) : AndOrNotEvaluator.Eval(t, function(r) {
            return i.HasTags(e) && e._tags[r]
        })
    }
    ,
    i
}()
  , Scalar = function() {
    function i() {}
    return i.WithinEpsilon = function(e, t, r) {
        return r === void 0 && (r = 1401298e-51),
        Math.abs(e - t) <= r
    }
    ,
    i.ToHex = function(e) {
        var t = e.toString(16);
        return e <= 15 ? ("0" + t).toUpperCase() : t.toUpperCase()
    }
    ,
    i.Sign = function(e) {
        return e = +e,
        e === 0 || isNaN(e) ? e : e > 0 ? 1 : -1
    }
    ,
    i.Clamp = function(e, t, r) {
        return t === void 0 && (t = 0),
        r === void 0 && (r = 1),
        Math.min(r, Math.max(t, e))
    }
    ,
    i.Log2 = function(e) {
        return Math.log(e) * Math.LOG2E
    }
    ,
    i.ILog2 = function(e) {
        if (Math.log2)
            return Math.floor(Math.log2(e));
        if (e < 0)
            return NaN;
        if (e === 0)
            return -1 / 0;
        var t = 0;
        if (e < 1) {
            for (; e < 1; )
                t++,
                e = e * 2;
            t = -t
        } else if (e > 1)
            for (; e > 1; )
                t++,
                e = Math.floor(e / 2);
        return t
    }
    ,
    i.Repeat = function(e, t) {
        return e - Math.floor(e / t) * t
    }
    ,
    i.Normalize = function(e, t, r) {
        return (e - t) / (r - t)
    }
    ,
    i.Denormalize = function(e, t, r) {
        return e * (r - t) + t
    }
    ,
    i.DeltaAngle = function(e, t) {
        var r = i.Repeat(t - e, 360);
        return r > 180 && (r -= 360),
        r
    }
    ,
    i.PingPong = function(e, t) {
        var r = i.Repeat(e, t * 2);
        return t - Math.abs(r - t)
    }
    ,
    i.SmoothStep = function(e, t, r) {
        var n = i.Clamp(r);
        return n = -2 * n * n * n + 3 * n * n,
        t * n + e * (1 - n)
    }
    ,
    i.MoveTowards = function(e, t, r) {
        var n = 0;
        return Math.abs(t - e) <= r ? n = t : n = e + i.Sign(t - e) * r,
        n
    }
    ,
    i.MoveTowardsAngle = function(e, t, r) {
        var n = i.DeltaAngle(e, t)
          , o = 0;
        return -r < n && n < r ? o = t : (t = e + n,
        o = i.MoveTowards(e, t, r)),
        o
    }
    ,
    i.Lerp = function(e, t, r) {
        return e + (t - e) * r
    }
    ,
    i.LerpAngle = function(e, t, r) {
        var n = i.Repeat(t - e, 360);
        return n > 180 && (n -= 360),
        e + n * i.Clamp(r)
    }
    ,
    i.InverseLerp = function(e, t, r) {
        var n = 0;
        return e != t ? n = i.Clamp((r - e) / (t - e)) : n = 0,
        n
    }
    ,
    i.Hermite = function(e, t, r, n, o) {
        var a = o * o
          , s = o * a
          , l = 2 * s - 3 * a + 1
          , u = -2 * s + 3 * a
          , c = s - 2 * a + o
          , h = s - a;
        return e * l + r * u + t * c + n * h
    }
    ,
    i.Hermite1stDerivative = function(e, t, r, n, o) {
        var a = o * o;
        return (a - o) * 6 * e + (3 * a - 4 * o + 1) * t + (-a + o) * 6 * r + (3 * a - 2 * o) * n
    }
    ,
    i.RandomRange = function(e, t) {
        return e === t ? e : Math.random() * (t - e) + e
    }
    ,
    i.RangeToPercent = function(e, t, r) {
        return (e - t) / (r - t)
    }
    ,
    i.PercentToRange = function(e, t, r) {
        return (r - t) * e + t
    }
    ,
    i.NormalizeRadians = function(e) {
        return e -= i.TwoPi * Math.floor((e + Math.PI) / i.TwoPi),
        e
    }
    ,
    i.HCF = function(e, t) {
        var r = e % t;
        return r === 0 ? t : i.HCF(t, r)
    }
    ,
    i.TwoPi = Math.PI * 2,
    i
}()
  , ToGammaSpace = 1 / 2.2
  , ToLinearSpace = 2.2
  , PHI = (1 + Math.sqrt(5)) / 2
  , Epsilon = .001
  , ArrayTools = function() {
    function i() {}
    return i.BuildArray = function(e, t) {
        for (var r = [], n = 0; n < e; ++n)
            r.push(t());
        return r
    }
    ,
    i.BuildTuple = function(e, t) {
        return i.BuildArray(e, t)
    }
    ,
    i
}()
  , Vector2 = function() {
    function i(e, t) {
        e === void 0 && (e = 0),
        t === void 0 && (t = 0),
        this.x = e,
        this.y = t
    }
    return i.prototype.toString = function() {
        return "{X: " + this.x + " Y: " + this.y + "}"
    }
    ,
    i.prototype.getClassName = function() {
        return "Vector2"
    }
    ,
    i.prototype.getHashCode = function() {
        var e = this.x | 0;
        return e = e * 397 ^ (this.y | 0),
        e
    }
    ,
    i.prototype.toArray = function(e, t) {
        return t === void 0 && (t = 0),
        e[t] = this.x,
        e[t + 1] = this.y,
        this
    }
    ,
    i.prototype.fromArray = function(e, t) {
        return t === void 0 && (t = 0),
        i.FromArrayToRef(e, t, this),
        this
    }
    ,
    i.prototype.asArray = function() {
        var e = new Array;
        return this.toArray(e, 0),
        e
    }
    ,
    i.prototype.copyFrom = function(e) {
        return this.x = e.x,
        this.y = e.y,
        this
    }
    ,
    i.prototype.copyFromFloats = function(e, t) {
        return this.x = e,
        this.y = t,
        this
    }
    ,
    i.prototype.set = function(e, t) {
        return this.copyFromFloats(e, t)
    }
    ,
    i.prototype.add = function(e) {
        return new i(this.x + e.x,this.y + e.y)
    }
    ,
    i.prototype.addToRef = function(e, t) {
        return t.x = this.x + e.x,
        t.y = this.y + e.y,
        this
    }
    ,
    i.prototype.addInPlace = function(e) {
        return this.x += e.x,
        this.y += e.y,
        this
    }
    ,
    i.prototype.addVector3 = function(e) {
        return new i(this.x + e.x,this.y + e.y)
    }
    ,
    i.prototype.subtract = function(e) {
        return new i(this.x - e.x,this.y - e.y)
    }
    ,
    i.prototype.subtractToRef = function(e, t) {
        return t.x = this.x - e.x,
        t.y = this.y - e.y,
        this
    }
    ,
    i.prototype.subtractInPlace = function(e) {
        return this.x -= e.x,
        this.y -= e.y,
        this
    }
    ,
    i.prototype.multiplyInPlace = function(e) {
        return this.x *= e.x,
        this.y *= e.y,
        this
    }
    ,
    i.prototype.multiply = function(e) {
        return new i(this.x * e.x,this.y * e.y)
    }
    ,
    i.prototype.multiplyToRef = function(e, t) {
        return t.x = this.x * e.x,
        t.y = this.y * e.y,
        this
    }
    ,
    i.prototype.multiplyByFloats = function(e, t) {
        return new i(this.x * e,this.y * t)
    }
    ,
    i.prototype.divide = function(e) {
        return new i(this.x / e.x,this.y / e.y)
    }
    ,
    i.prototype.divideToRef = function(e, t) {
        return t.x = this.x / e.x,
        t.y = this.y / e.y,
        this
    }
    ,
    i.prototype.divideInPlace = function(e) {
        return this.divideToRef(e, this)
    }
    ,
    i.prototype.negate = function() {
        return new i(-this.x,-this.y)
    }
    ,
    i.prototype.negateInPlace = function() {
        return this.x *= -1,
        this.y *= -1,
        this
    }
    ,
    i.prototype.negateToRef = function(e) {
        return e.copyFromFloats(this.x * -1, this.y * -1)
    }
    ,
    i.prototype.scaleInPlace = function(e) {
        return this.x *= e,
        this.y *= e,
        this
    }
    ,
    i.prototype.scale = function(e) {
        var t = new i(0,0);
        return this.scaleToRef(e, t),
        t
    }
    ,
    i.prototype.scaleToRef = function(e, t) {
        return t.x = this.x * e,
        t.y = this.y * e,
        this
    }
    ,
    i.prototype.scaleAndAddToRef = function(e, t) {
        return t.x += this.x * e,
        t.y += this.y * e,
        this
    }
    ,
    i.prototype.equals = function(e) {
        return e && this.x === e.x && this.y === e.y
    }
    ,
    i.prototype.equalsWithEpsilon = function(e, t) {
        return t === void 0 && (t = Epsilon),
        e && Scalar.WithinEpsilon(this.x, e.x, t) && Scalar.WithinEpsilon(this.y, e.y, t)
    }
    ,
    i.prototype.floor = function() {
        return new i(Math.floor(this.x),Math.floor(this.y))
    }
    ,
    i.prototype.fract = function() {
        return new i(this.x - Math.floor(this.x),this.y - Math.floor(this.y))
    }
    ,
    i.prototype.rotateToRef = function(e, t) {
        var r = Math.cos(e)
          , n = Math.sin(e);
        return t.x = r * this.x - n * this.y,
        t.y = n * this.x + r * this.y,
        this
    }
    ,
    i.prototype.length = function() {
        return Math.sqrt(this.x * this.x + this.y * this.y)
    }
    ,
    i.prototype.lengthSquared = function() {
        return this.x * this.x + this.y * this.y
    }
    ,
    i.prototype.normalize = function() {
        return i.NormalizeToRef(this, this),
        this
    }
    ,
    i.prototype.clone = function() {
        return new i(this.x,this.y)
    }
    ,
    i.Zero = function() {
        return new i(0,0)
    }
    ,
    i.One = function() {
        return new i(1,1)
    }
    ,
    i.FromArray = function(e, t) {
        return t === void 0 && (t = 0),
        new i(e[t],e[t + 1])
    }
    ,
    i.FromArrayToRef = function(e, t, r) {
        r.x = e[t],
        r.y = e[t + 1]
    }
    ,
    i.CatmullRom = function(e, t, r, n, o) {
        var a = o * o
          , s = o * a
          , l = .5 * (2 * t.x + (-e.x + r.x) * o + (2 * e.x - 5 * t.x + 4 * r.x - n.x) * a + (-e.x + 3 * t.x - 3 * r.x + n.x) * s)
          , u = .5 * (2 * t.y + (-e.y + r.y) * o + (2 * e.y - 5 * t.y + 4 * r.y - n.y) * a + (-e.y + 3 * t.y - 3 * r.y + n.y) * s);
        return new i(l,u)
    }
    ,
    i.Clamp = function(e, t, r) {
        var n = e.x;
        n = n > r.x ? r.x : n,
        n = n < t.x ? t.x : n;
        var o = e.y;
        return o = o > r.y ? r.y : o,
        o = o < t.y ? t.y : o,
        new i(n,o)
    }
    ,
    i.Hermite = function(e, t, r, n, o) {
        var a = o * o
          , s = o * a
          , l = 2 * s - 3 * a + 1
          , u = -2 * s + 3 * a
          , c = s - 2 * a + o
          , h = s - a
          , f = e.x * l + r.x * u + t.x * c + n.x * h
          , d = e.y * l + r.y * u + t.y * c + n.y * h;
        return new i(f,d)
    }
    ,
    i.Hermite1stDerivative = function(e, t, r, n, o) {
        var a = i.Zero();
        return this.Hermite1stDerivativeToRef(e, t, r, n, o, a),
        a
    }
    ,
    i.Hermite1stDerivativeToRef = function(e, t, r, n, o, a) {
        var s = o * o;
        a.x = (s - o) * 6 * e.x + (3 * s - 4 * o + 1) * t.x + (-s + o) * 6 * r.x + (3 * s - 2 * o) * n.x,
        a.y = (s - o) * 6 * e.y + (3 * s - 4 * o + 1) * t.y + (-s + o) * 6 * r.y + (3 * s - 2 * o) * n.y
    }
    ,
    i.Lerp = function(e, t, r) {
        var n = e.x + (t.x - e.x) * r
          , o = e.y + (t.y - e.y) * r;
        return new i(n,o)
    }
    ,
    i.Dot = function(e, t) {
        return e.x * t.x + e.y * t.y
    }
    ,
    i.Normalize = function(e) {
        var t = i.Zero();
        return this.NormalizeToRef(e, t),
        t
    }
    ,
    i.NormalizeToRef = function(e, t) {
        var r = e.length();
        r !== 0 && (t.x = e.x / r,
        t.y = e.y / r)
    }
    ,
    i.Minimize = function(e, t) {
        var r = e.x < t.x ? e.x : t.x
          , n = e.y < t.y ? e.y : t.y;
        return new i(r,n)
    }
    ,
    i.Maximize = function(e, t) {
        var r = e.x > t.x ? e.x : t.x
          , n = e.y > t.y ? e.y : t.y;
        return new i(r,n)
    }
    ,
    i.Transform = function(e, t) {
        var r = i.Zero();
        return i.TransformToRef(e, t, r),
        r
    }
    ,
    i.TransformToRef = function(e, t, r) {
        var n = t.m
          , o = e.x * n[0] + e.y * n[4] + n[12]
          , a = e.x * n[1] + e.y * n[5] + n[13];
        r.x = o,
        r.y = a
    }
    ,
    i.PointInTriangle = function(e, t, r, n) {
        var o = .5 * (-r.y * n.x + t.y * (-r.x + n.x) + t.x * (r.y - n.y) + r.x * n.y)
          , a = o < 0 ? -1 : 1
          , s = (t.y * n.x - t.x * n.y + (n.y - t.y) * e.x + (t.x - n.x) * e.y) * a
          , l = (t.x * r.y - t.y * r.x + (t.y - r.y) * e.x + (r.x - t.x) * e.y) * a;
        return s > 0 && l > 0 && s + l < 2 * o * a
    }
    ,
    i.Distance = function(e, t) {
        return Math.sqrt(i.DistanceSquared(e, t))
    }
    ,
    i.DistanceSquared = function(e, t) {
        var r = e.x - t.x
          , n = e.y - t.y;
        return r * r + n * n
    }
    ,
    i.Center = function(e, t) {
        return i.CenterToRef(e, t, i.Zero())
    }
    ,
    i.CenterToRef = function(e, t, r) {
        return r.copyFromFloats((e.x + t.x) / 2, (e.y + t.y) / 2)
    }
    ,
    i.DistanceOfPointFromSegment = function(e, t, r) {
        var n = i.DistanceSquared(t, r);
        if (n === 0)
            return i.Distance(e, t);
        var o = r.subtract(t)
          , a = Math.max(0, Math.min(1, i.Dot(e.subtract(t), o) / n))
          , s = t.add(o.multiplyByFloats(a, a));
        return i.Distance(e, s)
    }
    ,
    i
}()
  , Vector3 = function() {
    function i(e, t, r) {
        e === void 0 && (e = 0),
        t === void 0 && (t = 0),
        r === void 0 && (r = 0),
        this._isDirty = !0,
        this._x = e,
        this._y = t,
        this._z = r
    }
    return Object.defineProperty(i.prototype, "x", {
        get: function() {
            return this._x
        },
        set: function(e) {
            this._x = e,
            this._isDirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "y", {
        get: function() {
            return this._y
        },
        set: function(e) {
            this._y = e,
            this._isDirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "z", {
        get: function() {
            return this._z
        },
        set: function(e) {
            this._z = e,
            this._isDirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.toString = function() {
        return "{X: " + this._x + " Y: " + this._y + " Z: " + this._z + "}"
    }
    ,
    i.prototype.getClassName = function() {
        return "Vector3"
    }
    ,
    i.prototype.getHashCode = function() {
        var e = this._x | 0;
        return e = e * 397 ^ (this._y | 0),
        e = e * 397 ^ (this._z | 0),
        e
    }
    ,
    i.prototype.asArray = function() {
        var e = [];
        return this.toArray(e, 0),
        e
    }
    ,
    i.prototype.toArray = function(e, t) {
        return t === void 0 && (t = 0),
        e[t] = this._x,
        e[t + 1] = this._y,
        e[t + 2] = this._z,
        this
    }
    ,
    i.prototype.fromArray = function(e, t) {
        return t === void 0 && (t = 0),
        i.FromArrayToRef(e, t, this),
        this
    }
    ,
    i.prototype.toQuaternion = function() {
        return Quaternion.RotationYawPitchRoll(this._y, this._x, this._z)
    }
    ,
    i.prototype.addInPlace = function(e) {
        return this.addInPlaceFromFloats(e._x, e._y, e._z)
    }
    ,
    i.prototype.addInPlaceFromFloats = function(e, t, r) {
        return this.x += e,
        this.y += t,
        this.z += r,
        this
    }
    ,
    i.prototype.add = function(e) {
        return new i(this._x + e._x,this._y + e._y,this._z + e._z)
    }
    ,
    i.prototype.addToRef = function(e, t) {
        return t.copyFromFloats(this._x + e._x, this._y + e._y, this._z + e._z)
    }
    ,
    i.prototype.subtractInPlace = function(e) {
        return this.x -= e._x,
        this.y -= e._y,
        this.z -= e._z,
        this
    }
    ,
    i.prototype.subtract = function(e) {
        return new i(this._x - e._x,this._y - e._y,this._z - e._z)
    }
    ,
    i.prototype.subtractToRef = function(e, t) {
        return this.subtractFromFloatsToRef(e._x, e._y, e._z, t)
    }
    ,
    i.prototype.subtractFromFloats = function(e, t, r) {
        return new i(this._x - e,this._y - t,this._z - r)
    }
    ,
    i.prototype.subtractFromFloatsToRef = function(e, t, r, n) {
        return n.copyFromFloats(this._x - e, this._y - t, this._z - r)
    }
    ,
    i.prototype.negate = function() {
        return new i(-this._x,-this._y,-this._z)
    }
    ,
    i.prototype.negateInPlace = function() {
        return this.x *= -1,
        this.y *= -1,
        this.z *= -1,
        this
    }
    ,
    i.prototype.negateToRef = function(e) {
        return e.copyFromFloats(this._x * -1, this._y * -1, this._z * -1)
    }
    ,
    i.prototype.scaleInPlace = function(e) {
        return this.x *= e,
        this.y *= e,
        this.z *= e,
        this
    }
    ,
    i.prototype.scale = function(e) {
        return new i(this._x * e,this._y * e,this._z * e)
    }
    ,
    i.prototype.scaleToRef = function(e, t) {
        return t.copyFromFloats(this._x * e, this._y * e, this._z * e)
    }
    ,
    i.prototype.scaleAndAddToRef = function(e, t) {
        return t.addInPlaceFromFloats(this._x * e, this._y * e, this._z * e)
    }
    ,
    i.prototype.projectOnPlane = function(e, t) {
        var r = i.Zero();
        return this.projectOnPlaneToRef(e, t, r),
        r
    }
    ,
    i.prototype.projectOnPlaneToRef = function(e, t, r) {
        var n = e.normal
          , o = e.d
          , a = MathTmp.Vector3[0];
        this.subtractToRef(t, a),
        a.normalize();
        var s = i.Dot(a, n)
          , l = -(i.Dot(t, n) + o) / s
          , u = a.scaleInPlace(l);
        t.addToRef(u, r)
    }
    ,
    i.prototype.equals = function(e) {
        return e && this._x === e._x && this._y === e._y && this._z === e._z
    }
    ,
    i.prototype.equalsWithEpsilon = function(e, t) {
        return t === void 0 && (t = Epsilon),
        e && Scalar.WithinEpsilon(this._x, e._x, t) && Scalar.WithinEpsilon(this._y, e._y, t) && Scalar.WithinEpsilon(this._z, e._z, t)
    }
    ,
    i.prototype.equalsToFloats = function(e, t, r) {
        return this._x === e && this._y === t && this._z === r
    }
    ,
    i.prototype.multiplyInPlace = function(e) {
        return this.x *= e._x,
        this.y *= e._y,
        this.z *= e._z,
        this
    }
    ,
    i.prototype.multiply = function(e) {
        return this.multiplyByFloats(e._x, e._y, e._z)
    }
    ,
    i.prototype.multiplyToRef = function(e, t) {
        return t.copyFromFloats(this._x * e._x, this._y * e._y, this._z * e._z)
    }
    ,
    i.prototype.multiplyByFloats = function(e, t, r) {
        return new i(this._x * e,this._y * t,this._z * r)
    }
    ,
    i.prototype.divide = function(e) {
        return new i(this._x / e._x,this._y / e._y,this._z / e._z)
    }
    ,
    i.prototype.divideToRef = function(e, t) {
        return t.copyFromFloats(this._x / e._x, this._y / e._y, this._z / e._z)
    }
    ,
    i.prototype.divideInPlace = function(e) {
        return this.divideToRef(e, this)
    }
    ,
    i.prototype.minimizeInPlace = function(e) {
        return this.minimizeInPlaceFromFloats(e._x, e._y, e._z)
    }
    ,
    i.prototype.maximizeInPlace = function(e) {
        return this.maximizeInPlaceFromFloats(e._x, e._y, e._z)
    }
    ,
    i.prototype.minimizeInPlaceFromFloats = function(e, t, r) {
        return e < this._x && (this.x = e),
        t < this._y && (this.y = t),
        r < this._z && (this.z = r),
        this
    }
    ,
    i.prototype.maximizeInPlaceFromFloats = function(e, t, r) {
        return e > this._x && (this.x = e),
        t > this._y && (this.y = t),
        r > this._z && (this.z = r),
        this
    }
    ,
    i.prototype.isNonUniformWithinEpsilon = function(e) {
        var t = Math.abs(this._x)
          , r = Math.abs(this._y);
        if (!Scalar.WithinEpsilon(t, r, e))
            return !0;
        var n = Math.abs(this._z);
        return !Scalar.WithinEpsilon(t, n, e) || !Scalar.WithinEpsilon(r, n, e)
    }
    ,
    Object.defineProperty(i.prototype, "isNonUniform", {
        get: function() {
            var e = Math.abs(this._x)
              , t = Math.abs(this._y);
            if (e !== t)
                return !0;
            var r = Math.abs(this._z);
            return e !== r
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.floor = function() {
        return new i(Math.floor(this._x),Math.floor(this._y),Math.floor(this._z))
    }
    ,
    i.prototype.fract = function() {
        return new i(this._x - Math.floor(this._x),this._y - Math.floor(this._y),this._z - Math.floor(this._z))
    }
    ,
    i.prototype.length = function() {
        return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z)
    }
    ,
    i.prototype.lengthSquared = function() {
        return this._x * this._x + this._y * this._y + this._z * this._z
    }
    ,
    i.prototype.normalize = function() {
        return this.normalizeFromLength(this.length())
    }
    ,
    i.prototype.reorderInPlace = function(e) {
        var t = this;
        return e = e.toLowerCase(),
        e === "xyz" ? this : (MathTmp.Vector3[0].copyFrom(this),
        ["x", "y", "z"].forEach(function(r, n) {
            t[r] = MathTmp.Vector3[0][e[n]]
        }),
        this)
    }
    ,
    i.prototype.rotateByQuaternionToRef = function(e, t) {
        return e.toRotationMatrix(MathTmp.Matrix[0]),
        i.TransformCoordinatesToRef(this, MathTmp.Matrix[0], t),
        t
    }
    ,
    i.prototype.rotateByQuaternionAroundPointToRef = function(e, t, r) {
        return this.subtractToRef(t, MathTmp.Vector3[0]),
        MathTmp.Vector3[0].rotateByQuaternionToRef(e, MathTmp.Vector3[0]),
        t.addToRef(MathTmp.Vector3[0], r),
        r
    }
    ,
    i.prototype.cross = function(e) {
        return i.Cross(this, e)
    }
    ,
    i.prototype.normalizeFromLength = function(e) {
        return e === 0 || e === 1 ? this : this.scaleInPlace(1 / e)
    }
    ,
    i.prototype.normalizeToNew = function() {
        var e = new i(0,0,0);
        return this.normalizeToRef(e),
        e
    }
    ,
    i.prototype.normalizeToRef = function(e) {
        var t = this.length();
        return t === 0 || t === 1 ? e.copyFromFloats(this._x, this._y, this._z) : this.scaleToRef(1 / t, e)
    }
    ,
    i.prototype.clone = function() {
        return new i(this._x,this._y,this._z)
    }
    ,
    i.prototype.copyFrom = function(e) {
        return this.copyFromFloats(e._x, e._y, e._z)
    }
    ,
    i.prototype.copyFromFloats = function(e, t, r) {
        return this.x = e,
        this.y = t,
        this.z = r,
        this
    }
    ,
    i.prototype.set = function(e, t, r) {
        return this.copyFromFloats(e, t, r)
    }
    ,
    i.prototype.setAll = function(e) {
        return this.x = this.y = this.z = e,
        this
    }
    ,
    i.GetClipFactor = function(e, t, r, n) {
        var o = i.Dot(e, r) - n
          , a = i.Dot(t, r) - n
          , s = o / (o - a);
        return s
    }
    ,
    i.GetAngleBetweenVectors = function(e, t, r) {
        var n = e.normalizeToRef(MathTmp.Vector3[1])
          , o = t.normalizeToRef(MathTmp.Vector3[2])
          , a = i.Dot(n, o)
          , s = Math.acos(a)
          , l = MathTmp.Vector3[3];
        return i.CrossToRef(n, o, l),
        i.Dot(l, r) > 0 ? isNaN(s) ? 0 : s : isNaN(s) ? -Math.PI : -Math.acos(a)
    }
    ,
    i.GetAngleBetweenVectorsOnPlane = function(e, t, r) {
        MathTmp.Vector3[0].copyFrom(e);
        var n = MathTmp.Vector3[0];
        MathTmp.Vector3[1].copyFrom(t);
        var o = MathTmp.Vector3[1];
        MathTmp.Vector3[2].copyFrom(r);
        var a = MathTmp.Vector3[2]
          , s = MathTmp.Vector3[3]
          , l = MathTmp.Vector3[4];
        n.normalize(),
        o.normalize(),
        a.normalize(),
        i.CrossToRef(a, n, s),
        i.CrossToRef(s, a, l);
        var u = Math.atan2(i.Dot(o, s), i.Dot(o, l));
        return Scalar.NormalizeRadians(u)
    }
    ,
    i.SlerpToRef = function(e, t, r, n) {
        r = Scalar.Clamp(r, 0, 1);
        var o = MathTmp.Vector3[0], a = MathTmp.Vector3[1], s, l;
        o.copyFrom(e),
        s = o.length(),
        o.normalizeFromLength(s),
        a.copyFrom(t),
        l = a.length(),
        a.normalizeFromLength(l);
        var u = i.Dot(o, a), c, h;
        if (u < 1 - Epsilon) {
            var f = Math.acos(u)
              , d = 1 / Math.sin(f);
            c = Math.sin((1 - r) * f) * d,
            h = Math.sin(r * f) * d
        } else
            c = 1 - r,
            h = r;
        o.scaleInPlace(c),
        a.scaleInPlace(h),
        n.copyFrom(o).addInPlace(a),
        n.scaleInPlace(Scalar.Lerp(s, l, r))
    }
    ,
    i.SmoothToRef = function(e, t, r, n, o) {
        i.SlerpToRef(e, t, n === 0 ? 1 : r / n, o)
    }
    ,
    i.FromArray = function(e, t) {
        return t === void 0 && (t = 0),
        new i(e[t],e[t + 1],e[t + 2])
    }
    ,
    i.FromFloatArray = function(e, t) {
        return i.FromArray(e, t)
    }
    ,
    i.FromArrayToRef = function(e, t, r) {
        r.x = e[t],
        r.y = e[t + 1],
        r.z = e[t + 2]
    }
    ,
    i.FromFloatArrayToRef = function(e, t, r) {
        return i.FromArrayToRef(e, t, r)
    }
    ,
    i.FromFloatsToRef = function(e, t, r, n) {
        n.copyFromFloats(e, t, r)
    }
    ,
    i.Zero = function() {
        return new i(0,0,0)
    }
    ,
    i.One = function() {
        return new i(1,1,1)
    }
    ,
    i.Up = function() {
        return new i(0,1,0)
    }
    ,
    Object.defineProperty(i, "UpReadOnly", {
        get: function() {
            return i._UpReadOnly
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i, "RightReadOnly", {
        get: function() {
            return i._RightReadOnly
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i, "LeftHandedForwardReadOnly", {
        get: function() {
            return i._LeftHandedForwardReadOnly
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i, "RightHandedForwardReadOnly", {
        get: function() {
            return i._RightHandedForwardReadOnly
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i, "ZeroReadOnly", {
        get: function() {
            return i._ZeroReadOnly
        },
        enumerable: !1,
        configurable: !0
    }),
    i.Down = function() {
        return new i(0,-1,0)
    }
    ,
    i.Forward = function(e) {
        return e === void 0 && (e = !1),
        new i(0,0,e ? -1 : 1)
    }
    ,
    i.Backward = function(e) {
        return e === void 0 && (e = !1),
        new i(0,0,e ? 1 : -1)
    }
    ,
    i.Right = function() {
        return new i(1,0,0)
    }
    ,
    i.Left = function() {
        return new i(-1,0,0)
    }
    ,
    i.TransformCoordinates = function(e, t) {
        var r = i.Zero();
        return i.TransformCoordinatesToRef(e, t, r),
        r
    }
    ,
    i.TransformCoordinatesToRef = function(e, t, r) {
        i.TransformCoordinatesFromFloatsToRef(e._x, e._y, e._z, t, r)
    }
    ,
    i.TransformCoordinatesFromFloatsToRef = function(e, t, r, n, o) {
        var a = n.m
          , s = e * a[0] + t * a[4] + r * a[8] + a[12]
          , l = e * a[1] + t * a[5] + r * a[9] + a[13]
          , u = e * a[2] + t * a[6] + r * a[10] + a[14]
          , c = 1 / (e * a[3] + t * a[7] + r * a[11] + a[15]);
        o.x = s * c,
        o.y = l * c,
        o.z = u * c
    }
    ,
    i.TransformNormal = function(e, t) {
        var r = i.Zero();
        return i.TransformNormalToRef(e, t, r),
        r
    }
    ,
    i.TransformNormalToRef = function(e, t, r) {
        this.TransformNormalFromFloatsToRef(e._x, e._y, e._z, t, r)
    }
    ,
    i.TransformNormalFromFloatsToRef = function(e, t, r, n, o) {
        var a = n.m;
        o.x = e * a[0] + t * a[4] + r * a[8],
        o.y = e * a[1] + t * a[5] + r * a[9],
        o.z = e * a[2] + t * a[6] + r * a[10]
    }
    ,
    i.CatmullRom = function(e, t, r, n, o) {
        var a = o * o
          , s = o * a
          , l = .5 * (2 * t._x + (-e._x + r._x) * o + (2 * e._x - 5 * t._x + 4 * r._x - n._x) * a + (-e._x + 3 * t._x - 3 * r._x + n._x) * s)
          , u = .5 * (2 * t._y + (-e._y + r._y) * o + (2 * e._y - 5 * t._y + 4 * r._y - n._y) * a + (-e._y + 3 * t._y - 3 * r._y + n._y) * s)
          , c = .5 * (2 * t._z + (-e._z + r._z) * o + (2 * e._z - 5 * t._z + 4 * r._z - n._z) * a + (-e._z + 3 * t._z - 3 * r._z + n._z) * s);
        return new i(l,u,c)
    }
    ,
    i.Clamp = function(e, t, r) {
        var n = new i;
        return i.ClampToRef(e, t, r, n),
        n
    }
    ,
    i.ClampToRef = function(e, t, r, n) {
        var o = e._x;
        o = o > r._x ? r._x : o,
        o = o < t._x ? t._x : o;
        var a = e._y;
        a = a > r._y ? r._y : a,
        a = a < t._y ? t._y : a;
        var s = e._z;
        s = s > r._z ? r._z : s,
        s = s < t._z ? t._z : s,
        n.copyFromFloats(o, a, s)
    }
    ,
    i.CheckExtends = function(e, t, r) {
        t.minimizeInPlace(e),
        r.maximizeInPlace(e)
    }
    ,
    i.Hermite = function(e, t, r, n, o) {
        var a = o * o
          , s = o * a
          , l = 2 * s - 3 * a + 1
          , u = -2 * s + 3 * a
          , c = s - 2 * a + o
          , h = s - a
          , f = e._x * l + r._x * u + t._x * c + n._x * h
          , d = e._y * l + r._y * u + t._y * c + n._y * h
          , _ = e._z * l + r._z * u + t._z * c + n._z * h;
        return new i(f,d,_)
    }
    ,
    i.Hermite1stDerivative = function(e, t, r, n, o) {
        var a = i.Zero();
        return this.Hermite1stDerivativeToRef(e, t, r, n, o, a),
        a
    }
    ,
    i.Hermite1stDerivativeToRef = function(e, t, r, n, o, a) {
        var s = o * o;
        a.x = (s - o) * 6 * e.x + (3 * s - 4 * o + 1) * t.x + (-s + o) * 6 * r.x + (3 * s - 2 * o) * n.x,
        a.y = (s - o) * 6 * e.y + (3 * s - 4 * o + 1) * t.y + (-s + o) * 6 * r.y + (3 * s - 2 * o) * n.y,
        a.z = (s - o) * 6 * e.z + (3 * s - 4 * o + 1) * t.z + (-s + o) * 6 * r.z + (3 * s - 2 * o) * n.z
    }
    ,
    i.Lerp = function(e, t, r) {
        var n = new i(0,0,0);
        return i.LerpToRef(e, t, r, n),
        n
    }
    ,
    i.LerpToRef = function(e, t, r, n) {
        n.x = e._x + (t._x - e._x) * r,
        n.y = e._y + (t._y - e._y) * r,
        n.z = e._z + (t._z - e._z) * r
    }
    ,
    i.Dot = function(e, t) {
        return e._x * t._x + e._y * t._y + e._z * t._z
    }
    ,
    i.Cross = function(e, t) {
        var r = i.Zero();
        return i.CrossToRef(e, t, r),
        r
    }
    ,
    i.CrossToRef = function(e, t, r) {
        var n = e._y * t._z - e._z * t._y
          , o = e._z * t._x - e._x * t._z
          , a = e._x * t._y - e._y * t._x;
        r.copyFromFloats(n, o, a)
    }
    ,
    i.Normalize = function(e) {
        var t = i.Zero();
        return i.NormalizeToRef(e, t),
        t
    }
    ,
    i.NormalizeToRef = function(e, t) {
        e.normalizeToRef(t)
    }
    ,
    i.Project = function(e, t, r, n) {
        var o = new i;
        return i.ProjectToRef(e, t, r, n, o),
        o
    }
    ,
    i.ProjectToRef = function(e, t, r, n, o) {
        var a = n.width
          , s = n.height
          , l = n.x
          , u = n.y
          , c = MathTmp.Matrix[1];
        Matrix.FromValuesToRef(a / 2, 0, 0, 0, 0, -s / 2, 0, 0, 0, 0, .5, 0, l + a / 2, s / 2 + u, .5, 1, c);
        var h = MathTmp.Matrix[0];
        return t.multiplyToRef(r, h),
        h.multiplyToRef(c, h),
        i.TransformCoordinatesToRef(e, h, o),
        o
    }
    ,
    i._UnprojectFromInvertedMatrixToRef = function(e, t, r) {
        i.TransformCoordinatesToRef(e, t, r);
        var n = t.m
          , o = e._x * n[3] + e._y * n[7] + e._z * n[11] + n[15];
        Scalar.WithinEpsilon(o, 1) && r.scaleInPlace(1 / o)
    }
    ,
    i.UnprojectFromTransform = function(e, t, r, n, o) {
        var a = MathTmp.Matrix[0];
        n.multiplyToRef(o, a),
        a.invert(),
        e.x = e._x / t * 2 - 1,
        e.y = -(e._y / r * 2 - 1);
        var s = new i;
        return i._UnprojectFromInvertedMatrixToRef(e, a, s),
        s
    }
    ,
    i.Unproject = function(e, t, r, n, o, a) {
        var s = i.Zero();
        return i.UnprojectToRef(e, t, r, n, o, a, s),
        s
    }
    ,
    i.UnprojectToRef = function(e, t, r, n, o, a, s) {
        i.UnprojectFloatsToRef(e._x, e._y, e._z, t, r, n, o, a, s)
    }
    ,
    i.UnprojectFloatsToRef = function(e, t, r, n, o, a, s, l, u) {
        var c = MathTmp.Matrix[0];
        a.multiplyToRef(s, c),
        c.multiplyToRef(l, c),
        c.invert();
        var h = MathTmp.Vector3[0];
        h.x = e / n * 2 - 1,
        h.y = -(t / o * 2 - 1),
        h.z = 2 * r - 1,
        i._UnprojectFromInvertedMatrixToRef(h, c, u)
    }
    ,
    i.Minimize = function(e, t) {
        var r = e.clone();
        return r.minimizeInPlace(t),
        r
    }
    ,
    i.Maximize = function(e, t) {
        var r = e.clone();
        return r.maximizeInPlace(t),
        r
    }
    ,
    i.Distance = function(e, t) {
        return Math.sqrt(i.DistanceSquared(e, t))
    }
    ,
    i.DistanceSquared = function(e, t) {
        var r = e._x - t._x
          , n = e._y - t._y
          , o = e._z - t._z;
        return r * r + n * n + o * o
    }
    ,
    i.ProjectOnTriangleToRef = function(e, t, r, n, o) {
        var a = MathTmp.Vector3[0]
          , s = MathTmp.Vector3[1]
          , l = MathTmp.Vector3[2]
          , u = MathTmp.Vector3[3]
          , c = MathTmp.Vector3[4];
        r.subtractToRef(t, a),
        n.subtractToRef(t, s),
        n.subtractToRef(r, l);
        var h = a.length()
          , f = s.length()
          , d = l.length();
        if (h < Epsilon || f < Epsilon || d < Epsilon)
            return o.copyFrom(t),
            i.Distance(e, t);
        e.subtractToRef(t, c),
        i.CrossToRef(a, s, u);
        var _ = u.length();
        if (_ < Epsilon)
            return o.copyFrom(t),
            i.Distance(e, t);
        u.normalizeFromLength(_);
        var g = c.length();
        if (g < Epsilon)
            return o.copyFrom(t),
            0;
        c.normalizeFromLength(g);
        var m = i.Dot(u, c)
          , v = MathTmp.Vector3[5]
          , y = MathTmp.Vector3[6];
        v.copyFrom(u).scaleInPlace(-g * m),
        y.copyFrom(e).addInPlace(v);
        var b = MathTmp.Vector3[4]
          , T = MathTmp.Vector3[5]
          , C = MathTmp.Vector3[7]
          , A = MathTmp.Vector3[8];
        b.copyFrom(a).scaleInPlace(1 / h),
        A.copyFrom(s).scaleInPlace(1 / f),
        b.addInPlace(A).scaleInPlace(-1),
        T.copyFrom(a).scaleInPlace(-1 / h),
        A.copyFrom(l).scaleInPlace(1 / d),
        T.addInPlace(A).scaleInPlace(-1),
        C.copyFrom(l).scaleInPlace(-1 / d),
        A.copyFrom(s).scaleInPlace(-1 / f),
        C.addInPlace(A).scaleInPlace(-1);
        var S = MathTmp.Vector3[9], P, R, M, x;
        S.copyFrom(y).subtractInPlace(t),
        i.CrossToRef(b, S, A),
        P = i.Dot(A, u),
        R = P,
        S.copyFrom(y).subtractInPlace(r),
        i.CrossToRef(T, S, A),
        P = i.Dot(A, u),
        M = P,
        S.copyFrom(y).subtractInPlace(n),
        i.CrossToRef(C, S, A),
        P = i.Dot(A, u),
        x = P;
        var I = MathTmp.Vector3[10], w, O;
        R > 0 && M < 0 ? (I.copyFrom(a),
        w = t,
        O = r) : M > 0 && x < 0 ? (I.copyFrom(l),
        w = r,
        O = n) : (I.copyFrom(s).scaleInPlace(-1),
        w = n,
        O = t);
        var D = MathTmp.Vector3[9]
          , F = MathTmp.Vector3[4];
        w.subtractToRef(y, A),
        O.subtractToRef(y, D),
        i.CrossToRef(A, D, F);
        var V = i.Dot(F, u) < 0;
        if (!V)
            return o.copyFrom(y),
            Math.abs(g * m);
        var N = MathTmp.Vector3[5];
        i.CrossToRef(I, F, N),
        N.normalize();
        var L = MathTmp.Vector3[9];
        L.copyFrom(w).subtractInPlace(y);
        var k = L.length();
        if (k < Epsilon)
            return o.copyFrom(w),
            i.Distance(e, w);
        L.normalizeFromLength(k);
        var U = i.Dot(N, L)
          , z = MathTmp.Vector3[7];
        z.copyFrom(y).addInPlace(N.scaleInPlace(k * U)),
        A.copyFrom(z).subtractInPlace(w),
        g = I.length(),
        I.normalizeFromLength(g);
        var H = i.Dot(A, I) / Math.max(g, Epsilon);
        return H = Scalar.Clamp(H, 0, 1),
        z.copyFrom(w).addInPlace(I.scaleInPlace(H * g)),
        o.copyFrom(z),
        i.Distance(e, z)
    }
    ,
    i.Center = function(e, t) {
        return i.CenterToRef(e, t, i.Zero())
    }
    ,
    i.CenterToRef = function(e, t, r) {
        return r.copyFromFloats((e._x + t._x) / 2, (e._y + t._y) / 2, (e._z + t._z) / 2)
    }
    ,
    i.RotationFromAxis = function(e, t, r) {
        var n = i.Zero();
        return i.RotationFromAxisToRef(e, t, r, n),
        n
    }
    ,
    i.RotationFromAxisToRef = function(e, t, r, n) {
        var o = MathTmp.Quaternion[0];
        Quaternion.RotationQuaternionFromAxisToRef(e, t, r, o),
        o.toEulerAnglesToRef(n)
    }
    ,
    i._UpReadOnly = i.Up(),
    i._LeftHandedForwardReadOnly = i.Forward(!1),
    i._RightHandedForwardReadOnly = i.Forward(!0),
    i._RightReadOnly = i.Right(),
    i._ZeroReadOnly = i.Zero(),
    i
}()
  , Vector4 = function() {
    function i(e, t, r, n) {
        this.x = e,
        this.y = t,
        this.z = r,
        this.w = n
    }
    return i.prototype.toString = function() {
        return "{X: " + this.x + " Y: " + this.y + " Z: " + this.z + " W: " + this.w + "}"
    }
    ,
    i.prototype.getClassName = function() {
        return "Vector4"
    }
    ,
    i.prototype.getHashCode = function() {
        var e = this.x | 0;
        return e = e * 397 ^ (this.y | 0),
        e = e * 397 ^ (this.z | 0),
        e = e * 397 ^ (this.w | 0),
        e
    }
    ,
    i.prototype.asArray = function() {
        var e = new Array;
        return this.toArray(e, 0),
        e
    }
    ,
    i.prototype.toArray = function(e, t) {
        return t === void 0 && (t = 0),
        e[t] = this.x,
        e[t + 1] = this.y,
        e[t + 2] = this.z,
        e[t + 3] = this.w,
        this
    }
    ,
    i.prototype.fromArray = function(e, t) {
        return t === void 0 && (t = 0),
        i.FromArrayToRef(e, t, this),
        this
    }
    ,
    i.prototype.addInPlace = function(e) {
        return this.x += e.x,
        this.y += e.y,
        this.z += e.z,
        this.w += e.w,
        this
    }
    ,
    i.prototype.add = function(e) {
        return new i(this.x + e.x,this.y + e.y,this.z + e.z,this.w + e.w)
    }
    ,
    i.prototype.addToRef = function(e, t) {
        return t.x = this.x + e.x,
        t.y = this.y + e.y,
        t.z = this.z + e.z,
        t.w = this.w + e.w,
        this
    }
    ,
    i.prototype.subtractInPlace = function(e) {
        return this.x -= e.x,
        this.y -= e.y,
        this.z -= e.z,
        this.w -= e.w,
        this
    }
    ,
    i.prototype.subtract = function(e) {
        return new i(this.x - e.x,this.y - e.y,this.z - e.z,this.w - e.w)
    }
    ,
    i.prototype.subtractToRef = function(e, t) {
        return t.x = this.x - e.x,
        t.y = this.y - e.y,
        t.z = this.z - e.z,
        t.w = this.w - e.w,
        this
    }
    ,
    i.prototype.subtractFromFloats = function(e, t, r, n) {
        return new i(this.x - e,this.y - t,this.z - r,this.w - n)
    }
    ,
    i.prototype.subtractFromFloatsToRef = function(e, t, r, n, o) {
        return o.x = this.x - e,
        o.y = this.y - t,
        o.z = this.z - r,
        o.w = this.w - n,
        this
    }
    ,
    i.prototype.negate = function() {
        return new i(-this.x,-this.y,-this.z,-this.w)
    }
    ,
    i.prototype.negateInPlace = function() {
        return this.x *= -1,
        this.y *= -1,
        this.z *= -1,
        this.w *= -1,
        this
    }
    ,
    i.prototype.negateToRef = function(e) {
        return e.copyFromFloats(this.x * -1, this.y * -1, this.z * -1, this.w * -1)
    }
    ,
    i.prototype.scaleInPlace = function(e) {
        return this.x *= e,
        this.y *= e,
        this.z *= e,
        this.w *= e,
        this
    }
    ,
    i.prototype.scale = function(e) {
        return new i(this.x * e,this.y * e,this.z * e,this.w * e)
    }
    ,
    i.prototype.scaleToRef = function(e, t) {
        return t.x = this.x * e,
        t.y = this.y * e,
        t.z = this.z * e,
        t.w = this.w * e,
        this
    }
    ,
    i.prototype.scaleAndAddToRef = function(e, t) {
        return t.x += this.x * e,
        t.y += this.y * e,
        t.z += this.z * e,
        t.w += this.w * e,
        this
    }
    ,
    i.prototype.equals = function(e) {
        return e && this.x === e.x && this.y === e.y && this.z === e.z && this.w === e.w
    }
    ,
    i.prototype.equalsWithEpsilon = function(e, t) {
        return t === void 0 && (t = Epsilon),
        e && Scalar.WithinEpsilon(this.x, e.x, t) && Scalar.WithinEpsilon(this.y, e.y, t) && Scalar.WithinEpsilon(this.z, e.z, t) && Scalar.WithinEpsilon(this.w, e.w, t)
    }
    ,
    i.prototype.equalsToFloats = function(e, t, r, n) {
        return this.x === e && this.y === t && this.z === r && this.w === n
    }
    ,
    i.prototype.multiplyInPlace = function(e) {
        return this.x *= e.x,
        this.y *= e.y,
        this.z *= e.z,
        this.w *= e.w,
        this
    }
    ,
    i.prototype.multiply = function(e) {
        return new i(this.x * e.x,this.y * e.y,this.z * e.z,this.w * e.w)
    }
    ,
    i.prototype.multiplyToRef = function(e, t) {
        return t.x = this.x * e.x,
        t.y = this.y * e.y,
        t.z = this.z * e.z,
        t.w = this.w * e.w,
        this
    }
    ,
    i.prototype.multiplyByFloats = function(e, t, r, n) {
        return new i(this.x * e,this.y * t,this.z * r,this.w * n)
    }
    ,
    i.prototype.divide = function(e) {
        return new i(this.x / e.x,this.y / e.y,this.z / e.z,this.w / e.w)
    }
    ,
    i.prototype.divideToRef = function(e, t) {
        return t.x = this.x / e.x,
        t.y = this.y / e.y,
        t.z = this.z / e.z,
        t.w = this.w / e.w,
        this
    }
    ,
    i.prototype.divideInPlace = function(e) {
        return this.divideToRef(e, this)
    }
    ,
    i.prototype.minimizeInPlace = function(e) {
        return e.x < this.x && (this.x = e.x),
        e.y < this.y && (this.y = e.y),
        e.z < this.z && (this.z = e.z),
        e.w < this.w && (this.w = e.w),
        this
    }
    ,
    i.prototype.maximizeInPlace = function(e) {
        return e.x > this.x && (this.x = e.x),
        e.y > this.y && (this.y = e.y),
        e.z > this.z && (this.z = e.z),
        e.w > this.w && (this.w = e.w),
        this
    }
    ,
    i.prototype.floor = function() {
        return new i(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z),Math.floor(this.w))
    }
    ,
    i.prototype.fract = function() {
        return new i(this.x - Math.floor(this.x),this.y - Math.floor(this.y),this.z - Math.floor(this.z),this.w - Math.floor(this.w))
    }
    ,
    i.prototype.length = function() {
        return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w)
    }
    ,
    i.prototype.lengthSquared = function() {
        return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w
    }
    ,
    i.prototype.normalize = function() {
        var e = this.length();
        return e === 0 ? this : this.scaleInPlace(1 / e)
    }
    ,
    i.prototype.toVector3 = function() {
        return new Vector3(this.x,this.y,this.z)
    }
    ,
    i.prototype.clone = function() {
        return new i(this.x,this.y,this.z,this.w)
    }
    ,
    i.prototype.copyFrom = function(e) {
        return this.x = e.x,
        this.y = e.y,
        this.z = e.z,
        this.w = e.w,
        this
    }
    ,
    i.prototype.copyFromFloats = function(e, t, r, n) {
        return this.x = e,
        this.y = t,
        this.z = r,
        this.w = n,
        this
    }
    ,
    i.prototype.set = function(e, t, r, n) {
        return this.copyFromFloats(e, t, r, n)
    }
    ,
    i.prototype.setAll = function(e) {
        return this.x = this.y = this.z = this.w = e,
        this
    }
    ,
    i.FromArray = function(e, t) {
        return t || (t = 0),
        new i(e[t],e[t + 1],e[t + 2],e[t + 3])
    }
    ,
    i.FromArrayToRef = function(e, t, r) {
        r.x = e[t],
        r.y = e[t + 1],
        r.z = e[t + 2],
        r.w = e[t + 3]
    }
    ,
    i.FromFloatArrayToRef = function(e, t, r) {
        i.FromArrayToRef(e, t, r)
    }
    ,
    i.FromFloatsToRef = function(e, t, r, n, o) {
        o.x = e,
        o.y = t,
        o.z = r,
        o.w = n
    }
    ,
    i.Zero = function() {
        return new i(0,0,0,0)
    }
    ,
    i.One = function() {
        return new i(1,1,1,1)
    }
    ,
    i.Normalize = function(e) {
        var t = i.Zero();
        return i.NormalizeToRef(e, t),
        t
    }
    ,
    i.NormalizeToRef = function(e, t) {
        t.copyFrom(e),
        t.normalize()
    }
    ,
    i.Minimize = function(e, t) {
        var r = e.clone();
        return r.minimizeInPlace(t),
        r
    }
    ,
    i.Maximize = function(e, t) {
        var r = e.clone();
        return r.maximizeInPlace(t),
        r
    }
    ,
    i.Distance = function(e, t) {
        return Math.sqrt(i.DistanceSquared(e, t))
    }
    ,
    i.DistanceSquared = function(e, t) {
        var r = e.x - t.x
          , n = e.y - t.y
          , o = e.z - t.z
          , a = e.w - t.w;
        return r * r + n * n + o * o + a * a
    }
    ,
    i.Center = function(e, t) {
        return i.CenterToRef(e, t, i.Zero())
    }
    ,
    i.CenterToRef = function(e, t, r) {
        return r.copyFromFloats((e.x + t.x) / 2, (e.y + t.y) / 2, (e.z + t.z) / 2, (e.w + t.w) / 2)
    }
    ,
    i.TransformCoordinates = function(e, t) {
        var r = i.Zero();
        return i.TransformCoordinatesToRef(e, t, r),
        r
    }
    ,
    i.TransformCoordinatesToRef = function(e, t, r) {
        i.TransformCoordinatesFromFloatsToRef(e._x, e._y, e._z, t, r)
    }
    ,
    i.TransformCoordinatesFromFloatsToRef = function(e, t, r, n, o) {
        var a = n.m
          , s = e * a[0] + t * a[4] + r * a[8] + a[12]
          , l = e * a[1] + t * a[5] + r * a[9] + a[13]
          , u = e * a[2] + t * a[6] + r * a[10] + a[14]
          , c = e * a[3] + t * a[7] + r * a[11] + a[15];
        o.x = s,
        o.y = l,
        o.z = u,
        o.w = c
    }
    ,
    i.TransformNormal = function(e, t) {
        var r = i.Zero();
        return i.TransformNormalToRef(e, t, r),
        r
    }
    ,
    i.TransformNormalToRef = function(e, t, r) {
        var n = t.m
          , o = e.x * n[0] + e.y * n[4] + e.z * n[8]
          , a = e.x * n[1] + e.y * n[5] + e.z * n[9]
          , s = e.x * n[2] + e.y * n[6] + e.z * n[10];
        r.x = o,
        r.y = a,
        r.z = s,
        r.w = e.w
    }
    ,
    i.TransformNormalFromFloatsToRef = function(e, t, r, n, o, a) {
        var s = o.m;
        a.x = e * s[0] + t * s[4] + r * s[8],
        a.y = e * s[1] + t * s[5] + r * s[9],
        a.z = e * s[2] + t * s[6] + r * s[10],
        a.w = n
    }
    ,
    i.FromVector3 = function(e, t) {
        return t === void 0 && (t = 0),
        new i(e._x,e._y,e._z,t)
    }
    ,
    i
}()
  , Quaternion = function() {
    function i(e, t, r, n) {
        e === void 0 && (e = 0),
        t === void 0 && (t = 0),
        r === void 0 && (r = 0),
        n === void 0 && (n = 1),
        this._isDirty = !0,
        this._x = e,
        this._y = t,
        this._z = r,
        this._w = n
    }
    return Object.defineProperty(i.prototype, "x", {
        get: function() {
            return this._x
        },
        set: function(e) {
            this._x = e,
            this._isDirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "y", {
        get: function() {
            return this._y
        },
        set: function(e) {
            this._y = e,
            this._isDirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "z", {
        get: function() {
            return this._z
        },
        set: function(e) {
            this._z = e,
            this._isDirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "w", {
        get: function() {
            return this._w
        },
        set: function(e) {
            this._w = e,
            this._isDirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.toString = function() {
        return "{X: " + this._x + " Y: " + this._y + " Z: " + this._z + " W: " + this._w + "}"
    }
    ,
    i.prototype.getClassName = function() {
        return "Quaternion"
    }
    ,
    i.prototype.getHashCode = function() {
        var e = this._x | 0;
        return e = e * 397 ^ (this._y | 0),
        e = e * 397 ^ (this._z | 0),
        e = e * 397 ^ (this._w | 0),
        e
    }
    ,
    i.prototype.asArray = function() {
        return [this._x, this._y, this._z, this._w]
    }
    ,
    i.prototype.equals = function(e) {
        return e && this._x === e._x && this._y === e._y && this._z === e._z && this._w === e._w
    }
    ,
    i.prototype.equalsWithEpsilon = function(e, t) {
        return t === void 0 && (t = Epsilon),
        e && Scalar.WithinEpsilon(this._x, e._x, t) && Scalar.WithinEpsilon(this._y, e._y, t) && Scalar.WithinEpsilon(this._z, e._z, t) && Scalar.WithinEpsilon(this._w, e._w, t)
    }
    ,
    i.prototype.clone = function() {
        return new i(this._x,this._y,this._z,this._w)
    }
    ,
    i.prototype.copyFrom = function(e) {
        return this.x = e._x,
        this.y = e._y,
        this.z = e._z,
        this.w = e._w,
        this
    }
    ,
    i.prototype.copyFromFloats = function(e, t, r, n) {
        return this.x = e,
        this.y = t,
        this.z = r,
        this.w = n,
        this
    }
    ,
    i.prototype.set = function(e, t, r, n) {
        return this.copyFromFloats(e, t, r, n)
    }
    ,
    i.prototype.add = function(e) {
        return new i(this._x + e._x,this._y + e._y,this._z + e._z,this._w + e._w)
    }
    ,
    i.prototype.addInPlace = function(e) {
        return this._x += e._x,
        this._y += e._y,
        this._z += e._z,
        this._w += e._w,
        this
    }
    ,
    i.prototype.subtract = function(e) {
        return new i(this._x - e._x,this._y - e._y,this._z - e._z,this._w - e._w)
    }
    ,
    i.prototype.scale = function(e) {
        return new i(this._x * e,this._y * e,this._z * e,this._w * e)
    }
    ,
    i.prototype.scaleToRef = function(e, t) {
        return t.x = this._x * e,
        t.y = this._y * e,
        t.z = this._z * e,
        t.w = this._w * e,
        this
    }
    ,
    i.prototype.scaleInPlace = function(e) {
        return this.x *= e,
        this.y *= e,
        this.z *= e,
        this.w *= e,
        this
    }
    ,
    i.prototype.scaleAndAddToRef = function(e, t) {
        return t.x += this._x * e,
        t.y += this._y * e,
        t.z += this._z * e,
        t.w += this._w * e,
        this
    }
    ,
    i.prototype.multiply = function(e) {
        var t = new i(0,0,0,1);
        return this.multiplyToRef(e, t),
        t
    }
    ,
    i.prototype.multiplyToRef = function(e, t) {
        var r = this._x * e._w + this._y * e._z - this._z * e._y + this._w * e._x
          , n = -this._x * e._z + this._y * e._w + this._z * e._x + this._w * e._y
          , o = this._x * e._y - this._y * e._x + this._z * e._w + this._w * e._z
          , a = -this._x * e._x - this._y * e._y - this._z * e._z + this._w * e._w;
        return t.copyFromFloats(r, n, o, a),
        this
    }
    ,
    i.prototype.multiplyInPlace = function(e) {
        return this.multiplyToRef(e, this),
        this
    }
    ,
    i.prototype.conjugateToRef = function(e) {
        return e.copyFromFloats(-this._x, -this._y, -this._z, this._w),
        this
    }
    ,
    i.prototype.conjugateInPlace = function() {
        return this.x *= -1,
        this.y *= -1,
        this.z *= -1,
        this
    }
    ,
    i.prototype.conjugate = function() {
        var e = new i(-this._x,-this._y,-this._z,this._w);
        return e
    }
    ,
    i.prototype.length = function() {
        return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w)
    }
    ,
    i.prototype.normalize = function() {
        var e = this.length();
        if (e === 0)
            return this;
        var t = 1 / e;
        return this.x *= t,
        this.y *= t,
        this.z *= t,
        this.w *= t,
        this
    }
    ,
    i.prototype.toEulerAngles = function() {
        var e = Vector3.Zero();
        return this.toEulerAnglesToRef(e),
        e
    }
    ,
    i.prototype.toEulerAnglesToRef = function(e) {
        var t = this._z
          , r = this._x
          , n = this._y
          , o = this._w
          , a = o * o
          , s = t * t
          , l = r * r
          , u = n * n
          , c = n * t - r * o
          , h = .4999999;
        return c < -h ? (e.y = 2 * Math.atan2(n, o),
        e.x = Math.PI / 2,
        e.z = 0) : c > h ? (e.y = 2 * Math.atan2(n, o),
        e.x = -Math.PI / 2,
        e.z = 0) : (e.z = Math.atan2(2 * (r * n + t * o), -s - l + u + a),
        e.x = Math.asin(-2 * (t * n - r * o)),
        e.y = Math.atan2(2 * (t * r + n * o), s - l - u + a)),
        this
    }
    ,
    i.prototype.toRotationMatrix = function(e) {
        return Matrix.FromQuaternionToRef(this, e),
        this
    }
    ,
    i.prototype.fromRotationMatrix = function(e) {
        return i.FromRotationMatrixToRef(e, this),
        this
    }
    ,
    i.FromRotationMatrix = function(e) {
        var t = new i;
        return i.FromRotationMatrixToRef(e, t),
        t
    }
    ,
    i.FromRotationMatrixToRef = function(e, t) {
        var r = e.m, n = r[0], o = r[4], a = r[8], s = r[1], l = r[5], u = r[9], c = r[2], h = r[6], f = r[10], d = n + l + f, _;
        d > 0 ? (_ = .5 / Math.sqrt(d + 1),
        t.w = .25 / _,
        t.x = (h - u) * _,
        t.y = (a - c) * _,
        t.z = (s - o) * _) : n > l && n > f ? (_ = 2 * Math.sqrt(1 + n - l - f),
        t.w = (h - u) / _,
        t.x = .25 * _,
        t.y = (o + s) / _,
        t.z = (a + c) / _) : l > f ? (_ = 2 * Math.sqrt(1 + l - n - f),
        t.w = (a - c) / _,
        t.x = (o + s) / _,
        t.y = .25 * _,
        t.z = (u + h) / _) : (_ = 2 * Math.sqrt(1 + f - n - l),
        t.w = (s - o) / _,
        t.x = (a + c) / _,
        t.y = (u + h) / _,
        t.z = .25 * _)
    }
    ,
    i.Dot = function(e, t) {
        return e._x * t._x + e._y * t._y + e._z * t._z + e._w * t._w
    }
    ,
    i.AreClose = function(e, t) {
        var r = i.Dot(e, t);
        return r >= 0
    }
    ,
    i.SmoothToRef = function(e, t, r, n, o) {
        var a = n === 0 ? 1 : r / n;
        a = Scalar.Clamp(a, 0, 1),
        i.SlerpToRef(e, t, a, o)
    }
    ,
    i.Zero = function() {
        return new i(0,0,0,0)
    }
    ,
    i.Inverse = function(e) {
        return new i(-e._x,-e._y,-e._z,e._w)
    }
    ,
    i.InverseToRef = function(e, t) {
        return t.set(-e._x, -e._y, -e._z, e._w),
        t
    }
    ,
    i.Identity = function() {
        return new i(0,0,0,1)
    }
    ,
    i.IsIdentity = function(e) {
        return e && e._x === 0 && e._y === 0 && e._z === 0 && e._w === 1
    }
    ,
    i.RotationAxis = function(e, t) {
        return i.RotationAxisToRef(e, t, new i)
    }
    ,
    i.RotationAxisToRef = function(e, t, r) {
        var n = Math.sin(t / 2);
        return e.normalize(),
        r.w = Math.cos(t / 2),
        r.x = e._x * n,
        r.y = e._y * n,
        r.z = e._z * n,
        r
    }
    ,
    i.FromArray = function(e, t) {
        return t || (t = 0),
        new i(e[t],e[t + 1],e[t + 2],e[t + 3])
    }
    ,
    i.FromArrayToRef = function(e, t, r) {
        r.x = e[t],
        r.y = e[t + 1],
        r.z = e[t + 2],
        r.w = e[t + 3]
    }
    ,
    i.FromEulerAngles = function(e, t, r) {
        var n = new i;
        return i.RotationYawPitchRollToRef(t, e, r, n),
        n
    }
    ,
    i.FromEulerAnglesToRef = function(e, t, r, n) {
        return i.RotationYawPitchRollToRef(t, e, r, n),
        n
    }
    ,
    i.FromEulerVector = function(e) {
        var t = new i;
        return i.RotationYawPitchRollToRef(e._y, e._x, e._z, t),
        t
    }
    ,
    i.FromEulerVectorToRef = function(e, t) {
        return i.RotationYawPitchRollToRef(e._y, e._x, e._z, t),
        t
    }
    ,
    i.FromUnitVectorsToRef = function(e, t, r) {
        var n = Vector3.Dot(e, t) + 1;
        return n < Epsilon ? Math.abs(e.x) > Math.abs(e.z) ? r.set(-e.y, e.x, 0, 0) : r.set(0, -e.z, e.y, 0) : (Vector3.CrossToRef(e, t, TmpVectors.Vector3[0]),
        r.set(TmpVectors.Vector3[0].x, TmpVectors.Vector3[0].y, TmpVectors.Vector3[0].z, n)),
        r.normalize()
    }
    ,
    i.RotationYawPitchRoll = function(e, t, r) {
        var n = new i;
        return i.RotationYawPitchRollToRef(e, t, r, n),
        n
    }
    ,
    i.RotationYawPitchRollToRef = function(e, t, r, n) {
        var o = r * .5
          , a = t * .5
          , s = e * .5
          , l = Math.sin(o)
          , u = Math.cos(o)
          , c = Math.sin(a)
          , h = Math.cos(a)
          , f = Math.sin(s)
          , d = Math.cos(s);
        n.x = d * c * u + f * h * l,
        n.y = f * h * u - d * c * l,
        n.z = d * h * l - f * c * u,
        n.w = d * h * u + f * c * l
    }
    ,
    i.RotationAlphaBetaGamma = function(e, t, r) {
        var n = new i;
        return i.RotationAlphaBetaGammaToRef(e, t, r, n),
        n
    }
    ,
    i.RotationAlphaBetaGammaToRef = function(e, t, r, n) {
        var o = (r + e) * .5
          , a = (r - e) * .5
          , s = t * .5;
        n.x = Math.cos(a) * Math.sin(s),
        n.y = Math.sin(a) * Math.sin(s),
        n.z = Math.sin(o) * Math.cos(s),
        n.w = Math.cos(o) * Math.cos(s)
    }
    ,
    i.RotationQuaternionFromAxis = function(e, t, r) {
        var n = new i(0,0,0,0);
        return i.RotationQuaternionFromAxisToRef(e, t, r, n),
        n
    }
    ,
    i.RotationQuaternionFromAxisToRef = function(e, t, r, n) {
        var o = MathTmp.Matrix[0];
        Matrix.FromXYZAxesToRef(e.normalize(), t.normalize(), r.normalize(), o),
        i.FromRotationMatrixToRef(o, n)
    }
    ,
    i.FromLookDirectionLH = function(e, t) {
        var r = new i;
        return i.FromLookDirectionLHToRef(e, t, r),
        r
    }
    ,
    i.FromLookDirectionLHToRef = function(e, t, r) {
        var n = MathTmp.Matrix[0];
        Matrix.LookDirectionLHToRef(e, t, n),
        i.FromRotationMatrixToRef(n, r)
    }
    ,
    i.FromLookDirectionRH = function(e, t) {
        var r = new i;
        return i.FromLookDirectionRHToRef(e, t, r),
        r
    }
    ,
    i.FromLookDirectionRHToRef = function(e, t, r) {
        var n = MathTmp.Matrix[0];
        return Matrix.LookDirectionRHToRef(e, t, n),
        i.FromRotationMatrixToRef(n, r)
    }
    ,
    i.Slerp = function(e, t, r) {
        var n = i.Identity();
        return i.SlerpToRef(e, t, r, n),
        n
    }
    ,
    i.SlerpToRef = function(e, t, r, n) {
        var o, a, s = e._x * t._x + e._y * t._y + e._z * t._z + e._w * t._w, l = !1;
        if (s < 0 && (l = !0,
        s = -s),
        s > .999999)
            a = 1 - r,
            o = l ? -r : r;
        else {
            var u = Math.acos(s)
              , c = 1 / Math.sin(u);
            a = Math.sin((1 - r) * u) * c,
            o = l ? -Math.sin(r * u) * c : Math.sin(r * u) * c
        }
        n.x = a * e._x + o * t._x,
        n.y = a * e._y + o * t._y,
        n.z = a * e._z + o * t._z,
        n.w = a * e._w + o * t._w
    }
    ,
    i.Hermite = function(e, t, r, n, o) {
        var a = o * o
          , s = o * a
          , l = 2 * s - 3 * a + 1
          , u = -2 * s + 3 * a
          , c = s - 2 * a + o
          , h = s - a
          , f = e._x * l + r._x * u + t._x * c + n._x * h
          , d = e._y * l + r._y * u + t._y * c + n._y * h
          , _ = e._z * l + r._z * u + t._z * c + n._z * h
          , g = e._w * l + r._w * u + t._w * c + n._w * h;
        return new i(f,d,_,g)
    }
    ,
    i.Hermite1stDerivative = function(e, t, r, n, o) {
        var a = i.Zero();
        return this.Hermite1stDerivativeToRef(e, t, r, n, o, a),
        a
    }
    ,
    i.Hermite1stDerivativeToRef = function(e, t, r, n, o, a) {
        var s = o * o;
        a.x = (s - o) * 6 * e.x + (3 * s - 4 * o + 1) * t.x + (-s + o) * 6 * r.x + (3 * s - 2 * o) * n.x,
        a.y = (s - o) * 6 * e.y + (3 * s - 4 * o + 1) * t.y + (-s + o) * 6 * r.y + (3 * s - 2 * o) * n.y,
        a.z = (s - o) * 6 * e.z + (3 * s - 4 * o + 1) * t.z + (-s + o) * 6 * r.z + (3 * s - 2 * o) * n.z,
        a.w = (s - o) * 6 * e.w + (3 * s - 4 * o + 1) * t.w + (-s + o) * 6 * r.w + (3 * s - 2 * o) * n.w
    }
    ,
    i
}()
  , Matrix = function() {
    function i() {
        this._isIdentity = !1,
        this._isIdentityDirty = !0,
        this._isIdentity3x2 = !0,
        this._isIdentity3x2Dirty = !0,
        this.updateFlag = -1,
        PerformanceConfigurator.MatrixTrackPrecisionChange && PerformanceConfigurator.MatrixTrackedMatrices.push(this),
        this._m = new PerformanceConfigurator.MatrixCurrentType(16),
        this._markAsUpdated()
    }
    return Object.defineProperty(i, "Use64Bits", {
        get: function() {
            return PerformanceConfigurator.MatrixUse64Bits
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "m", {
        get: function() {
            return this._m
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype._markAsUpdated = function() {
        this.updateFlag = i._updateFlagSeed++,
        this._isIdentity = !1,
        this._isIdentity3x2 = !1,
        this._isIdentityDirty = !0,
        this._isIdentity3x2Dirty = !0
    }
    ,
    i.prototype._updateIdentityStatus = function(e, t, r, n) {
        t === void 0 && (t = !1),
        r === void 0 && (r = !1),
        n === void 0 && (n = !0),
        this._isIdentity = e,
        this._isIdentity3x2 = e || r,
        this._isIdentityDirty = this._isIdentity ? !1 : t,
        this._isIdentity3x2Dirty = this._isIdentity3x2 ? !1 : n
    }
    ,
    i.prototype.isIdentity = function() {
        if (this._isIdentityDirty) {
            this._isIdentityDirty = !1;
            var e = this._m;
            this._isIdentity = e[0] === 1 && e[1] === 0 && e[2] === 0 && e[3] === 0 && e[4] === 0 && e[5] === 1 && e[6] === 0 && e[7] === 0 && e[8] === 0 && e[9] === 0 && e[10] === 1 && e[11] === 0 && e[12] === 0 && e[13] === 0 && e[14] === 0 && e[15] === 1
        }
        return this._isIdentity
    }
    ,
    i.prototype.isIdentityAs3x2 = function() {
        return this._isIdentity3x2Dirty && (this._isIdentity3x2Dirty = !1,
        this._m[0] !== 1 || this._m[5] !== 1 || this._m[15] !== 1 ? this._isIdentity3x2 = !1 : this._m[1] !== 0 || this._m[2] !== 0 || this._m[3] !== 0 || this._m[4] !== 0 || this._m[6] !== 0 || this._m[7] !== 0 || this._m[8] !== 0 || this._m[9] !== 0 || this._m[10] !== 0 || this._m[11] !== 0 || this._m[12] !== 0 || this._m[13] !== 0 || this._m[14] !== 0 ? this._isIdentity3x2 = !1 : this._isIdentity3x2 = !0),
        this._isIdentity3x2
    }
    ,
    i.prototype.determinant = function() {
        if (this._isIdentity === !0)
            return 1;
        var e = this._m
          , t = e[0]
          , r = e[1]
          , n = e[2]
          , o = e[3]
          , a = e[4]
          , s = e[5]
          , l = e[6]
          , u = e[7]
          , c = e[8]
          , h = e[9]
          , f = e[10]
          , d = e[11]
          , _ = e[12]
          , g = e[13]
          , m = e[14]
          , v = e[15]
          , y = f * v - m * d
          , b = h * v - g * d
          , T = h * m - g * f
          , C = c * v - _ * d
          , A = c * m - f * _
          , S = c * g - _ * h
          , P = +(s * y - l * b + u * T)
          , R = -(a * y - l * C + u * A)
          , M = +(a * b - s * C + u * S)
          , x = -(a * T - s * A + l * S);
        return t * P + r * R + n * M + o * x
    }
    ,
    i.prototype.toArray = function() {
        return this._m
    }
    ,
    i.prototype.asArray = function() {
        return this._m
    }
    ,
    i.prototype.invert = function() {
        return this.invertToRef(this),
        this
    }
    ,
    i.prototype.reset = function() {
        return i.FromValuesToRef(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, this),
        this._updateIdentityStatus(!1),
        this
    }
    ,
    i.prototype.add = function(e) {
        var t = new i;
        return this.addToRef(e, t),
        t
    }
    ,
    i.prototype.addToRef = function(e, t) {
        for (var r = this._m, n = t._m, o = e.m, a = 0; a < 16; a++)
            n[a] = r[a] + o[a];
        return t._markAsUpdated(),
        this
    }
    ,
    i.prototype.addToSelf = function(e) {
        for (var t = this._m, r = e.m, n = 0; n < 16; n++)
            t[n] += r[n];
        return this._markAsUpdated(),
        this
    }
    ,
    i.prototype.invertToRef = function(e) {
        if (this._isIdentity === !0)
            return i.IdentityToRef(e),
            this;
        var t = this._m
          , r = t[0]
          , n = t[1]
          , o = t[2]
          , a = t[3]
          , s = t[4]
          , l = t[5]
          , u = t[6]
          , c = t[7]
          , h = t[8]
          , f = t[9]
          , d = t[10]
          , _ = t[11]
          , g = t[12]
          , m = t[13]
          , v = t[14]
          , y = t[15]
          , b = d * y - v * _
          , T = f * y - m * _
          , C = f * v - m * d
          , A = h * y - g * _
          , S = h * v - d * g
          , P = h * m - g * f
          , R = +(l * b - u * T + c * C)
          , M = -(s * b - u * A + c * S)
          , x = +(s * T - l * A + c * P)
          , I = -(s * C - l * S + u * P)
          , w = r * R + n * M + o * x + a * I;
        if (w === 0)
            return e.copyFrom(this),
            this;
        var O = 1 / w
          , D = u * y - v * c
          , F = l * y - m * c
          , V = l * v - m * u
          , N = s * y - g * c
          , L = s * v - g * u
          , k = s * m - g * l
          , U = u * _ - d * c
          , z = l * _ - f * c
          , H = l * d - f * u
          , G = s * _ - h * c
          , W = s * d - h * u
          , j = s * f - h * l
          , B = -(n * b - o * T + a * C)
          , X = +(r * b - o * A + a * S)
          , $ = -(r * T - n * A + a * P)
          , Y = +(r * C - n * S + o * P)
          , K = +(n * D - o * F + a * V)
          , Z = -(r * D - o * N + a * L)
          , q = +(r * F - n * N + a * k)
          , J = -(r * V - n * L + o * k)
          , Q = -(n * U - o * z + a * H)
          , te = +(r * U - o * G + a * W)
          , re = -(r * z - n * G + a * j)
          , ie = +(r * H - n * W + o * j);
        return i.FromValuesToRef(R * O, B * O, K * O, Q * O, M * O, X * O, Z * O, te * O, x * O, $ * O, q * O, re * O, I * O, Y * O, J * O, ie * O, e),
        this
    }
    ,
    i.prototype.addAtIndex = function(e, t) {
        return this._m[e] += t,
        this._markAsUpdated(),
        this
    }
    ,
    i.prototype.multiplyAtIndex = function(e, t) {
        return this._m[e] *= t,
        this._markAsUpdated(),
        this
    }
    ,
    i.prototype.setTranslationFromFloats = function(e, t, r) {
        return this._m[12] = e,
        this._m[13] = t,
        this._m[14] = r,
        this._markAsUpdated(),
        this
    }
    ,
    i.prototype.addTranslationFromFloats = function(e, t, r) {
        return this._m[12] += e,
        this._m[13] += t,
        this._m[14] += r,
        this._markAsUpdated(),
        this
    }
    ,
    i.prototype.setTranslation = function(e) {
        return this.setTranslationFromFloats(e._x, e._y, e._z)
    }
    ,
    i.prototype.getTranslation = function() {
        return new Vector3(this._m[12],this._m[13],this._m[14])
    }
    ,
    i.prototype.getTranslationToRef = function(e) {
        return e.x = this._m[12],
        e.y = this._m[13],
        e.z = this._m[14],
        this
    }
    ,
    i.prototype.removeRotationAndScaling = function() {
        var e = this.m;
        return i.FromValuesToRef(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, e[12], e[13], e[14], e[15], this),
        this._updateIdentityStatus(e[12] === 0 && e[13] === 0 && e[14] === 0 && e[15] === 1),
        this
    }
    ,
    i.prototype.multiply = function(e) {
        var t = new i;
        return this.multiplyToRef(e, t),
        t
    }
    ,
    i.prototype.copyFrom = function(e) {
        e.copyToArray(this._m);
        var t = e;
        return this.updateFlag = t.updateFlag,
        this._updateIdentityStatus(t._isIdentity, t._isIdentityDirty, t._isIdentity3x2, t._isIdentity3x2Dirty),
        this
    }
    ,
    i.prototype.copyToArray = function(e, t) {
        t === void 0 && (t = 0);
        var r = this._m;
        return e[t] = r[0],
        e[t + 1] = r[1],
        e[t + 2] = r[2],
        e[t + 3] = r[3],
        e[t + 4] = r[4],
        e[t + 5] = r[5],
        e[t + 6] = r[6],
        e[t + 7] = r[7],
        e[t + 8] = r[8],
        e[t + 9] = r[9],
        e[t + 10] = r[10],
        e[t + 11] = r[11],
        e[t + 12] = r[12],
        e[t + 13] = r[13],
        e[t + 14] = r[14],
        e[t + 15] = r[15],
        this
    }
    ,
    i.prototype.multiplyToRef = function(e, t) {
        return this._isIdentity ? (t.copyFrom(e),
        this) : e._isIdentity ? (t.copyFrom(this),
        this) : (this.multiplyToArray(e, t._m, 0),
        t._markAsUpdated(),
        this)
    }
    ,
    i.prototype.multiplyToArray = function(e, t, r) {
        var n = this._m
          , o = e.m
          , a = n[0]
          , s = n[1]
          , l = n[2]
          , u = n[3]
          , c = n[4]
          , h = n[5]
          , f = n[6]
          , d = n[7]
          , _ = n[8]
          , g = n[9]
          , m = n[10]
          , v = n[11]
          , y = n[12]
          , b = n[13]
          , T = n[14]
          , C = n[15]
          , A = o[0]
          , S = o[1]
          , P = o[2]
          , R = o[3]
          , M = o[4]
          , x = o[5]
          , I = o[6]
          , w = o[7]
          , O = o[8]
          , D = o[9]
          , F = o[10]
          , V = o[11]
          , N = o[12]
          , L = o[13]
          , k = o[14]
          , U = o[15];
        return t[r] = a * A + s * M + l * O + u * N,
        t[r + 1] = a * S + s * x + l * D + u * L,
        t[r + 2] = a * P + s * I + l * F + u * k,
        t[r + 3] = a * R + s * w + l * V + u * U,
        t[r + 4] = c * A + h * M + f * O + d * N,
        t[r + 5] = c * S + h * x + f * D + d * L,
        t[r + 6] = c * P + h * I + f * F + d * k,
        t[r + 7] = c * R + h * w + f * V + d * U,
        t[r + 8] = _ * A + g * M + m * O + v * N,
        t[r + 9] = _ * S + g * x + m * D + v * L,
        t[r + 10] = _ * P + g * I + m * F + v * k,
        t[r + 11] = _ * R + g * w + m * V + v * U,
        t[r + 12] = y * A + b * M + T * O + C * N,
        t[r + 13] = y * S + b * x + T * D + C * L,
        t[r + 14] = y * P + b * I + T * F + C * k,
        t[r + 15] = y * R + b * w + T * V + C * U,
        this
    }
    ,
    i.prototype.equals = function(e) {
        var t = e;
        if (!t)
            return !1;
        if ((this._isIdentity || t._isIdentity) && !this._isIdentityDirty && !t._isIdentityDirty)
            return this._isIdentity && t._isIdentity;
        var r = this.m
          , n = t.m;
        return r[0] === n[0] && r[1] === n[1] && r[2] === n[2] && r[3] === n[3] && r[4] === n[4] && r[5] === n[5] && r[6] === n[6] && r[7] === n[7] && r[8] === n[8] && r[9] === n[9] && r[10] === n[10] && r[11] === n[11] && r[12] === n[12] && r[13] === n[13] && r[14] === n[14] && r[15] === n[15]
    }
    ,
    i.prototype.clone = function() {
        var e = new i;
        return e.copyFrom(this),
        e
    }
    ,
    i.prototype.getClassName = function() {
        return "Matrix"
    }
    ,
    i.prototype.getHashCode = function() {
        for (var e = this._m[0] | 0, t = 1; t < 16; t++)
            e = e * 397 ^ (this._m[t] | 0);
        return e
    }
    ,
    i.prototype.decomposeToTransformNode = function(e) {
        return e.rotationQuaternion = e.rotationQuaternion || new Quaternion,
        this.decompose(e.scaling, e.rotationQuaternion, e.position)
    }
    ,
    i.prototype.decompose = function(e, t, r, n) {
        if (this._isIdentity)
            return r && r.setAll(0),
            e && e.setAll(1),
            t && t.copyFromFloats(0, 0, 0, 1),
            !0;
        var o = this._m;
        if (r && r.copyFromFloats(o[12], o[13], o[14]),
        e = e || MathTmp.Vector3[0],
        e.x = Math.sqrt(o[0] * o[0] + o[1] * o[1] + o[2] * o[2]),
        e.y = Math.sqrt(o[4] * o[4] + o[5] * o[5] + o[6] * o[6]),
        e.z = Math.sqrt(o[8] * o[8] + o[9] * o[9] + o[10] * o[10]),
        n) {
            var a = n.scaling.x < 0 ? -1 : 1
              , s = n.scaling.y < 0 ? -1 : 1
              , l = n.scaling.z < 0 ? -1 : 1;
            e.x *= a,
            e.y *= s,
            e.z *= l
        } else
            this.determinant() <= 0 && (e.y *= -1);
        if (e._x === 0 || e._y === 0 || e._z === 0)
            return t && t.copyFromFloats(0, 0, 0, 1),
            !1;
        if (t) {
            var u = 1 / e._x
              , c = 1 / e._y
              , h = 1 / e._z;
            i.FromValuesToRef(o[0] * u, o[1] * u, o[2] * u, 0, o[4] * c, o[5] * c, o[6] * c, 0, o[8] * h, o[9] * h, o[10] * h, 0, 0, 0, 0, 1, MathTmp.Matrix[0]),
            Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], t)
        }
        return !0
    }
    ,
    i.prototype.getRow = function(e) {
        if (e < 0 || e > 3)
            return null;
        var t = e * 4;
        return new Vector4(this._m[t + 0],this._m[t + 1],this._m[t + 2],this._m[t + 3])
    }
    ,
    i.prototype.setRow = function(e, t) {
        return this.setRowFromFloats(e, t.x, t.y, t.z, t.w)
    }
    ,
    i.prototype.transpose = function() {
        return i.Transpose(this)
    }
    ,
    i.prototype.transposeToRef = function(e) {
        return i.TransposeToRef(this, e),
        this
    }
    ,
    i.prototype.setRowFromFloats = function(e, t, r, n, o) {
        if (e < 0 || e > 3)
            return this;
        var a = e * 4;
        return this._m[a + 0] = t,
        this._m[a + 1] = r,
        this._m[a + 2] = n,
        this._m[a + 3] = o,
        this._markAsUpdated(),
        this
    }
    ,
    i.prototype.scale = function(e) {
        var t = new i;
        return this.scaleToRef(e, t),
        t
    }
    ,
    i.prototype.scaleToRef = function(e, t) {
        for (var r = 0; r < 16; r++)
            t._m[r] = this._m[r] * e;
        return t._markAsUpdated(),
        this
    }
    ,
    i.prototype.scaleAndAddToRef = function(e, t) {
        for (var r = 0; r < 16; r++)
            t._m[r] += this._m[r] * e;
        return t._markAsUpdated(),
        this
    }
    ,
    i.prototype.toNormalMatrix = function(e) {
        var t = MathTmp.Matrix[0];
        this.invertToRef(t),
        t.transposeToRef(e);
        var r = e._m;
        i.FromValuesToRef(r[0], r[1], r[2], 0, r[4], r[5], r[6], 0, r[8], r[9], r[10], 0, 0, 0, 0, 1, e)
    }
    ,
    i.prototype.getRotationMatrix = function() {
        var e = new i;
        return this.getRotationMatrixToRef(e),
        e
    }
    ,
    i.prototype.getRotationMatrixToRef = function(e) {
        var t = MathTmp.Vector3[0];
        if (!this.decompose(t))
            return i.IdentityToRef(e),
            this;
        var r = this._m
          , n = 1 / t._x
          , o = 1 / t._y
          , a = 1 / t._z;
        return i.FromValuesToRef(r[0] * n, r[1] * n, r[2] * n, 0, r[4] * o, r[5] * o, r[6] * o, 0, r[8] * a, r[9] * a, r[10] * a, 0, 0, 0, 0, 1, e),
        this
    }
    ,
    i.prototype.toggleModelMatrixHandInPlace = function() {
        var e = this._m;
        e[2] *= -1,
        e[6] *= -1,
        e[8] *= -1,
        e[9] *= -1,
        e[14] *= -1,
        this._markAsUpdated()
    }
    ,
    i.prototype.toggleProjectionMatrixHandInPlace = function() {
        var e = this._m;
        e[8] *= -1,
        e[9] *= -1,
        e[10] *= -1,
        e[11] *= -1,
        this._markAsUpdated()
    }
    ,
    i.FromArray = function(e, t) {
        t === void 0 && (t = 0);
        var r = new i;
        return i.FromArrayToRef(e, t, r),
        r
    }
    ,
    i.FromArrayToRef = function(e, t, r) {
        for (var n = 0; n < 16; n++)
            r._m[n] = e[n + t];
        r._markAsUpdated()
    }
    ,
    i.FromFloat32ArrayToRefScaled = function(e, t, r, n) {
        for (var o = 0; o < 16; o++)
            n._m[o] = e[o + t] * r;
        n._markAsUpdated()
    }
    ,
    Object.defineProperty(i, "IdentityReadOnly", {
        get: function() {
            return i._identityReadOnly
        },
        enumerable: !1,
        configurable: !0
    }),
    i.FromValuesToRef = function(e, t, r, n, o, a, s, l, u, c, h, f, d, _, g, m, v) {
        var y = v._m;
        y[0] = e,
        y[1] = t,
        y[2] = r,
        y[3] = n,
        y[4] = o,
        y[5] = a,
        y[6] = s,
        y[7] = l,
        y[8] = u,
        y[9] = c,
        y[10] = h,
        y[11] = f,
        y[12] = d,
        y[13] = _,
        y[14] = g,
        y[15] = m,
        v._markAsUpdated()
    }
    ,
    i.FromValues = function(e, t, r, n, o, a, s, l, u, c, h, f, d, _, g, m) {
        var v = new i
          , y = v._m;
        return y[0] = e,
        y[1] = t,
        y[2] = r,
        y[3] = n,
        y[4] = o,
        y[5] = a,
        y[6] = s,
        y[7] = l,
        y[8] = u,
        y[9] = c,
        y[10] = h,
        y[11] = f,
        y[12] = d,
        y[13] = _,
        y[14] = g,
        y[15] = m,
        v._markAsUpdated(),
        v
    }
    ,
    i.Compose = function(e, t, r) {
        var n = new i;
        return i.ComposeToRef(e, t, r, n),
        n
    }
    ,
    i.ComposeToRef = function(e, t, r, n) {
        var o = n._m
          , a = t._x
          , s = t._y
          , l = t._z
          , u = t._w
          , c = a + a
          , h = s + s
          , f = l + l
          , d = a * c
          , _ = a * h
          , g = a * f
          , m = s * h
          , v = s * f
          , y = l * f
          , b = u * c
          , T = u * h
          , C = u * f
          , A = e._x
          , S = e._y
          , P = e._z;
        o[0] = (1 - (m + y)) * A,
        o[1] = (_ + C) * A,
        o[2] = (g - T) * A,
        o[3] = 0,
        o[4] = (_ - C) * S,
        o[5] = (1 - (d + y)) * S,
        o[6] = (v + b) * S,
        o[7] = 0,
        o[8] = (g + T) * P,
        o[9] = (v - b) * P,
        o[10] = (1 - (d + m)) * P,
        o[11] = 0,
        o[12] = r._x,
        o[13] = r._y,
        o[14] = r._z,
        o[15] = 1,
        n._markAsUpdated()
    }
    ,
    i.Identity = function() {
        var e = i.FromValues(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
        return e._updateIdentityStatus(!0),
        e
    }
    ,
    i.IdentityToRef = function(e) {
        i.FromValuesToRef(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, e),
        e._updateIdentityStatus(!0)
    }
    ,
    i.Zero = function() {
        var e = i.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
        return e._updateIdentityStatus(!1),
        e
    }
    ,
    i.RotationX = function(e) {
        var t = new i;
        return i.RotationXToRef(e, t),
        t
    }
    ,
    i.Invert = function(e) {
        var t = new i;
        return e.invertToRef(t),
        t
    }
    ,
    i.RotationXToRef = function(e, t) {
        var r = Math.sin(e)
          , n = Math.cos(e);
        i.FromValuesToRef(1, 0, 0, 0, 0, n, r, 0, 0, -r, n, 0, 0, 0, 0, 1, t),
        t._updateIdentityStatus(n === 1 && r === 0)
    }
    ,
    i.RotationY = function(e) {
        var t = new i;
        return i.RotationYToRef(e, t),
        t
    }
    ,
    i.RotationYToRef = function(e, t) {
        var r = Math.sin(e)
          , n = Math.cos(e);
        i.FromValuesToRef(n, 0, -r, 0, 0, 1, 0, 0, r, 0, n, 0, 0, 0, 0, 1, t),
        t._updateIdentityStatus(n === 1 && r === 0)
    }
    ,
    i.RotationZ = function(e) {
        var t = new i;
        return i.RotationZToRef(e, t),
        t
    }
    ,
    i.RotationZToRef = function(e, t) {
        var r = Math.sin(e)
          , n = Math.cos(e);
        i.FromValuesToRef(n, r, 0, 0, -r, n, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, t),
        t._updateIdentityStatus(n === 1 && r === 0)
    }
    ,
    i.RotationAxis = function(e, t) {
        var r = new i;
        return i.RotationAxisToRef(e, t, r),
        r
    }
    ,
    i.RotationAxisToRef = function(e, t, r) {
        var n = Math.sin(-t)
          , o = Math.cos(-t)
          , a = 1 - o;
        e.normalize();
        var s = r._m;
        s[0] = e._x * e._x * a + o,
        s[1] = e._x * e._y * a - e._z * n,
        s[2] = e._x * e._z * a + e._y * n,
        s[3] = 0,
        s[4] = e._y * e._x * a + e._z * n,
        s[5] = e._y * e._y * a + o,
        s[6] = e._y * e._z * a - e._x * n,
        s[7] = 0,
        s[8] = e._z * e._x * a - e._y * n,
        s[9] = e._z * e._y * a + e._x * n,
        s[10] = e._z * e._z * a + o,
        s[11] = 0,
        s[12] = 0,
        s[13] = 0,
        s[14] = 0,
        s[15] = 1,
        r._markAsUpdated()
    }
    ,
    i.RotationAlignToRef = function(e, t, r) {
        var n = Vector3.Dot(t, e)
          , o = r._m;
        if (n < -1 + Epsilon)
            o[0] = -1,
            o[1] = 0,
            o[2] = 0,
            o[3] = 0,
            o[4] = 0,
            o[5] = -1,
            o[6] = 0,
            o[7] = 0,
            o[8] = 0,
            o[9] = 0,
            o[10] = 1,
            o[11] = 0;
        else {
            var a = Vector3.Cross(t, e)
              , s = 1 / (1 + n);
            o[0] = a._x * a._x * s + n,
            o[1] = a._y * a._x * s - a._z,
            o[2] = a._z * a._x * s + a._y,
            o[3] = 0,
            o[4] = a._x * a._y * s + a._z,
            o[5] = a._y * a._y * s + n,
            o[6] = a._z * a._y * s - a._x,
            o[7] = 0,
            o[8] = a._x * a._z * s - a._y,
            o[9] = a._y * a._z * s + a._x,
            o[10] = a._z * a._z * s + n,
            o[11] = 0
        }
        o[12] = 0,
        o[13] = 0,
        o[14] = 0,
        o[15] = 1,
        r._markAsUpdated()
    }
    ,
    i.RotationYawPitchRoll = function(e, t, r) {
        var n = new i;
        return i.RotationYawPitchRollToRef(e, t, r, n),
        n
    }
    ,
    i.RotationYawPitchRollToRef = function(e, t, r, n) {
        Quaternion.RotationYawPitchRollToRef(e, t, r, MathTmp.Quaternion[0]),
        MathTmp.Quaternion[0].toRotationMatrix(n)
    }
    ,
    i.Scaling = function(e, t, r) {
        var n = new i;
        return i.ScalingToRef(e, t, r, n),
        n
    }
    ,
    i.ScalingToRef = function(e, t, r, n) {
        i.FromValuesToRef(e, 0, 0, 0, 0, t, 0, 0, 0, 0, r, 0, 0, 0, 0, 1, n),
        n._updateIdentityStatus(e === 1 && t === 1 && r === 1)
    }
    ,
    i.Translation = function(e, t, r) {
        var n = new i;
        return i.TranslationToRef(e, t, r, n),
        n
    }
    ,
    i.TranslationToRef = function(e, t, r, n) {
        i.FromValuesToRef(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, e, t, r, 1, n),
        n._updateIdentityStatus(e === 0 && t === 0 && r === 0)
    }
    ,
    i.Lerp = function(e, t, r) {
        var n = new i;
        return i.LerpToRef(e, t, r, n),
        n
    }
    ,
    i.LerpToRef = function(e, t, r, n) {
        for (var o = n._m, a = e.m, s = t.m, l = 0; l < 16; l++)
            o[l] = a[l] * (1 - r) + s[l] * r;
        n._markAsUpdated()
    }
    ,
    i.DecomposeLerp = function(e, t, r) {
        var n = new i;
        return i.DecomposeLerpToRef(e, t, r, n),
        n
    }
    ,
    i.DecomposeLerpToRef = function(e, t, r, n) {
        var o = MathTmp.Vector3[0]
          , a = MathTmp.Quaternion[0]
          , s = MathTmp.Vector3[1];
        e.decompose(o, a, s);
        var l = MathTmp.Vector3[2]
          , u = MathTmp.Quaternion[1]
          , c = MathTmp.Vector3[3];
        t.decompose(l, u, c);
        var h = MathTmp.Vector3[4];
        Vector3.LerpToRef(o, l, r, h);
        var f = MathTmp.Quaternion[2];
        Quaternion.SlerpToRef(a, u, r, f);
        var d = MathTmp.Vector3[5];
        Vector3.LerpToRef(s, c, r, d),
        i.ComposeToRef(h, f, d, n)
    }
    ,
    i.LookAtLH = function(e, t, r) {
        var n = new i;
        return i.LookAtLHToRef(e, t, r, n),
        n
    }
    ,
    i.LookAtLHToRef = function(e, t, r, n) {
        var o = MathTmp.Vector3[0]
          , a = MathTmp.Vector3[1]
          , s = MathTmp.Vector3[2];
        t.subtractToRef(e, s),
        s.normalize(),
        Vector3.CrossToRef(r, s, o);
        var l = o.lengthSquared();
        l === 0 ? o.x = 1 : o.normalizeFromLength(Math.sqrt(l)),
        Vector3.CrossToRef(s, o, a),
        a.normalize();
        var u = -Vector3.Dot(o, e)
          , c = -Vector3.Dot(a, e)
          , h = -Vector3.Dot(s, e);
        i.FromValuesToRef(o._x, a._x, s._x, 0, o._y, a._y, s._y, 0, o._z, a._z, s._z, 0, u, c, h, 1, n)
    }
    ,
    i.LookAtRH = function(e, t, r) {
        var n = new i;
        return i.LookAtRHToRef(e, t, r, n),
        n
    }
    ,
    i.LookAtRHToRef = function(e, t, r, n) {
        var o = MathTmp.Vector3[0]
          , a = MathTmp.Vector3[1]
          , s = MathTmp.Vector3[2];
        e.subtractToRef(t, s),
        s.normalize(),
        Vector3.CrossToRef(r, s, o);
        var l = o.lengthSquared();
        l === 0 ? o.x = 1 : o.normalizeFromLength(Math.sqrt(l)),
        Vector3.CrossToRef(s, o, a),
        a.normalize();
        var u = -Vector3.Dot(o, e)
          , c = -Vector3.Dot(a, e)
          , h = -Vector3.Dot(s, e);
        i.FromValuesToRef(o._x, a._x, s._x, 0, o._y, a._y, s._y, 0, o._z, a._z, s._z, 0, u, c, h, 1, n)
    }
    ,
    i.LookDirectionLH = function(e, t) {
        var r = new i;
        return i.LookDirectionLHToRef(e, t, r),
        r
    }
    ,
    i.LookDirectionLHToRef = function(e, t, r) {
        var n = MathTmp.Vector3[0];
        n.copyFrom(e),
        n.scaleInPlace(-1);
        var o = MathTmp.Vector3[1];
        Vector3.CrossToRef(t, n, o),
        i.FromValuesToRef(o._x, o._y, o._z, 0, t._x, t._y, t._z, 0, n._x, n._y, n._z, 0, 0, 0, 0, 1, r)
    }
    ,
    i.LookDirectionRH = function(e, t) {
        var r = new i;
        return i.LookDirectionRHToRef(e, t, r),
        r
    }
    ,
    i.LookDirectionRHToRef = function(e, t, r) {
        var n = MathTmp.Vector3[2];
        Vector3.CrossToRef(t, e, n),
        i.FromValuesToRef(n._x, n._y, n._z, 0, t._x, t._y, t._z, 0, e._x, e._y, e._z, 0, 0, 0, 0, 1, r)
    }
    ,
    i.OrthoLH = function(e, t, r, n, o) {
        var a = new i;
        return i.OrthoLHToRef(e, t, r, n, a, o),
        a
    }
    ,
    i.OrthoLHToRef = function(e, t, r, n, o, a) {
        var s = r
          , l = n
          , u = 2 / e
          , c = 2 / t
          , h = 2 / (l - s)
          , f = -(l + s) / (l - s);
        i.FromValuesToRef(u, 0, 0, 0, 0, c, 0, 0, 0, 0, h, 0, 0, 0, f, 1, o),
        a && o.multiplyToRef(mtxConvertNDCToHalfZRange, o),
        o._updateIdentityStatus(u === 1 && c === 1 && h === 1 && f === 0)
    }
    ,
    i.OrthoOffCenterLH = function(e, t, r, n, o, a, s) {
        var l = new i;
        return i.OrthoOffCenterLHToRef(e, t, r, n, o, a, l, s),
        l
    }
    ,
    i.OrthoOffCenterLHToRef = function(e, t, r, n, o, a, s, l) {
        var u = o
          , c = a
          , h = 2 / (t - e)
          , f = 2 / (n - r)
          , d = 2 / (c - u)
          , _ = -(c + u) / (c - u)
          , g = (e + t) / (e - t)
          , m = (n + r) / (r - n);
        i.FromValuesToRef(h, 0, 0, 0, 0, f, 0, 0, 0, 0, d, 0, g, m, _, 1, s),
        l && s.multiplyToRef(mtxConvertNDCToHalfZRange, s),
        s._markAsUpdated()
    }
    ,
    i.OrthoOffCenterRH = function(e, t, r, n, o, a, s) {
        var l = new i;
        return i.OrthoOffCenterRHToRef(e, t, r, n, o, a, l, s),
        l
    }
    ,
    i.OrthoOffCenterRHToRef = function(e, t, r, n, o, a, s, l) {
        i.OrthoOffCenterLHToRef(e, t, r, n, o, a, s, l),
        s._m[10] *= -1
    }
    ,
    i.PerspectiveLH = function(e, t, r, n, o, a) {
        a === void 0 && (a = 0);
        var s = new i
          , l = r
          , u = n
          , c = 2 * l / e
          , h = 2 * l / t
          , f = (u + l) / (u - l)
          , d = -2 * u * l / (u - l)
          , _ = Math.tan(a);
        return i.FromValuesToRef(c, 0, 0, 0, 0, h, 0, _, 0, 0, f, 1, 0, 0, d, 0, s),
        o && s.multiplyToRef(mtxConvertNDCToHalfZRange, s),
        s._updateIdentityStatus(!1),
        s
    }
    ,
    i.PerspectiveFovLH = function(e, t, r, n, o, a, s) {
        a === void 0 && (a = 0),
        s === void 0 && (s = !1);
        var l = new i;
        return i.PerspectiveFovLHToRef(e, t, r, n, l, !0, o, a, s),
        l
    }
    ,
    i.PerspectiveFovLHToRef = function(e, t, r, n, o, a, s, l, u) {
        a === void 0 && (a = !0),
        l === void 0 && (l = 0),
        u === void 0 && (u = !1);
        var c = r
          , h = n
          , f = 1 / Math.tan(e * .5)
          , d = a ? f / t : f
          , _ = a ? f : f * t
          , g = u && c === 0 ? -1 : h !== 0 ? (h + c) / (h - c) : 1
          , m = u && c === 0 ? 2 * h : h !== 0 ? -2 * h * c / (h - c) : -2 * c
          , v = Math.tan(l);
        i.FromValuesToRef(d, 0, 0, 0, 0, _, 0, v, 0, 0, g, 1, 0, 0, m, 0, o),
        s && o.multiplyToRef(mtxConvertNDCToHalfZRange, o),
        o._updateIdentityStatus(!1)
    }
    ,
    i.PerspectiveFovReverseLHToRef = function(e, t, r, n, o, a, s, l) {
        a === void 0 && (a = !0),
        l === void 0 && (l = 0);
        var u = 1 / Math.tan(e * .5)
          , c = a ? u / t : u
          , h = a ? u : u * t
          , f = Math.tan(l);
        i.FromValuesToRef(c, 0, 0, 0, 0, h, 0, f, 0, 0, -r, 1, 0, 0, 1, 0, o),
        s && o.multiplyToRef(mtxConvertNDCToHalfZRange, o),
        o._updateIdentityStatus(!1)
    }
    ,
    i.PerspectiveFovRH = function(e, t, r, n, o, a, s) {
        a === void 0 && (a = 0),
        s === void 0 && (s = !1);
        var l = new i;
        return i.PerspectiveFovRHToRef(e, t, r, n, l, !0, o, a, s),
        l
    }
    ,
    i.PerspectiveFovRHToRef = function(e, t, r, n, o, a, s, l, u) {
        a === void 0 && (a = !0),
        l === void 0 && (l = 0),
        u === void 0 && (u = !1);
        var c = r
          , h = n
          , f = 1 / Math.tan(e * .5)
          , d = a ? f / t : f
          , _ = a ? f : f * t
          , g = u && c === 0 ? 1 : h !== 0 ? -(h + c) / (h - c) : -1
          , m = u && c === 0 ? 2 * h : h !== 0 ? -2 * h * c / (h - c) : -2 * c
          , v = Math.tan(l);
        i.FromValuesToRef(d, 0, 0, 0, 0, _, 0, v, 0, 0, g, -1, 0, 0, m, 0, o),
        s && o.multiplyToRef(mtxConvertNDCToHalfZRange, o),
        o._updateIdentityStatus(!1)
    }
    ,
    i.PerspectiveFovReverseRHToRef = function(e, t, r, n, o, a, s, l) {
        a === void 0 && (a = !0),
        l === void 0 && (l = 0);
        var u = 1 / Math.tan(e * .5)
          , c = a ? u / t : u
          , h = a ? u : u * t
          , f = Math.tan(l);
        i.FromValuesToRef(c, 0, 0, 0, 0, h, 0, f, 0, 0, -r, -1, 0, 0, -1, 0, o),
        s && o.multiplyToRef(mtxConvertNDCToHalfZRange, o),
        o._updateIdentityStatus(!1)
    }
    ,
    i.PerspectiveFovWebVRToRef = function(e, t, r, n, o, a, s) {
        o === void 0 && (o = !1),
        s === void 0 && (s = 0);
        var l = o ? -1 : 1
          , u = Math.tan(e.upDegrees * Math.PI / 180)
          , c = Math.tan(e.downDegrees * Math.PI / 180)
          , h = Math.tan(e.leftDegrees * Math.PI / 180)
          , f = Math.tan(e.rightDegrees * Math.PI / 180)
          , d = 2 / (h + f)
          , _ = 2 / (u + c)
          , g = Math.tan(s)
          , m = n._m;
        m[0] = d,
        m[1] = m[2] = m[3] = m[4] = 0,
        m[5] = _,
        m[6] = 0,
        m[7] = g,
        m[8] = (h - f) * d * .5,
        m[9] = -((u - c) * _ * .5),
        m[10] = -r / (t - r),
        m[11] = 1 * l,
        m[12] = m[13] = m[15] = 0,
        m[14] = -(2 * r * t) / (r - t),
        a && n.multiplyToRef(mtxConvertNDCToHalfZRange, n),
        n._markAsUpdated()
    }
    ,
    i.GetFinalMatrix = function(e, t, r, n, o, a) {
        var s = e.width
          , l = e.height
          , u = e.x
          , c = e.y
          , h = i.FromValues(s / 2, 0, 0, 0, 0, -l / 2, 0, 0, 0, 0, a - o, 0, u + s / 2, l / 2 + c, o, 1)
          , f = MathTmp.Matrix[0];
        return t.multiplyToRef(r, f),
        f.multiplyToRef(n, f),
        f.multiply(h)
    }
    ,
    i.GetAsMatrix2x2 = function(e) {
        var t = e.m
          , r = [t[0], t[1], t[4], t[5]];
        return PerformanceConfigurator.MatrixUse64Bits ? r : new Float32Array(r)
    }
    ,
    i.GetAsMatrix3x3 = function(e) {
        var t = e.m
          , r = [t[0], t[1], t[2], t[4], t[5], t[6], t[8], t[9], t[10]];
        return PerformanceConfigurator.MatrixUse64Bits ? r : new Float32Array(r)
    }
    ,
    i.Transpose = function(e) {
        var t = new i;
        return i.TransposeToRef(e, t),
        t
    }
    ,
    i.TransposeToRef = function(e, t) {
        var r = t._m
          , n = e.m;
        r[0] = n[0],
        r[1] = n[4],
        r[2] = n[8],
        r[3] = n[12],
        r[4] = n[1],
        r[5] = n[5],
        r[6] = n[9],
        r[7] = n[13],
        r[8] = n[2],
        r[9] = n[6],
        r[10] = n[10],
        r[11] = n[14],
        r[12] = n[3],
        r[13] = n[7],
        r[14] = n[11],
        r[15] = n[15],
        t._markAsUpdated(),
        t._updateIdentityStatus(e._isIdentity, e._isIdentityDirty)
    }
    ,
    i.Reflection = function(e) {
        var t = new i;
        return i.ReflectionToRef(e, t),
        t
    }
    ,
    i.ReflectionToRef = function(e, t) {
        e.normalize();
        var r = e.normal.x
          , n = e.normal.y
          , o = e.normal.z
          , a = -2 * r
          , s = -2 * n
          , l = -2 * o;
        i.FromValuesToRef(a * r + 1, s * r, l * r, 0, a * n, s * n + 1, l * n, 0, a * o, s * o, l * o + 1, 0, a * e.d, s * e.d, l * e.d, 1, t)
    }
    ,
    i.FromXYZAxesToRef = function(e, t, r, n) {
        i.FromValuesToRef(e._x, e._y, e._z, 0, t._x, t._y, t._z, 0, r._x, r._y, r._z, 0, 0, 0, 0, 1, n)
    }
    ,
    i.FromQuaternionToRef = function(e, t) {
        var r = e._x * e._x
          , n = e._y * e._y
          , o = e._z * e._z
          , a = e._x * e._y
          , s = e._z * e._w
          , l = e._z * e._x
          , u = e._y * e._w
          , c = e._y * e._z
          , h = e._x * e._w;
        t._m[0] = 1 - 2 * (n + o),
        t._m[1] = 2 * (a + s),
        t._m[2] = 2 * (l - u),
        t._m[3] = 0,
        t._m[4] = 2 * (a - s),
        t._m[5] = 1 - 2 * (o + r),
        t._m[6] = 2 * (c + h),
        t._m[7] = 0,
        t._m[8] = 2 * (l + u),
        t._m[9] = 2 * (c - h),
        t._m[10] = 1 - 2 * (n + r),
        t._m[11] = 0,
        t._m[12] = 0,
        t._m[13] = 0,
        t._m[14] = 0,
        t._m[15] = 1,
        t._markAsUpdated()
    }
    ,
    i._updateFlagSeed = 0,
    i._identityReadOnly = i.Identity(),
    i
}()
  , MathTmp = function() {
    function i() {}
    return i.Vector3 = ArrayTools.BuildTuple(11, Vector3.Zero),
    i.Matrix = ArrayTools.BuildTuple(2, Matrix.Identity),
    i.Quaternion = ArrayTools.BuildTuple(3, Quaternion.Zero),
    i
}()
  , TmpVectors = function() {
    function i() {}
    return i.Vector2 = ArrayTools.BuildTuple(3, Vector2.Zero),
    i.Vector3 = ArrayTools.BuildTuple(13, Vector3.Zero),
    i.Vector4 = ArrayTools.BuildTuple(3, Vector4.Zero),
    i.Quaternion = ArrayTools.BuildTuple(2, Quaternion.Zero),
    i.Matrix = ArrayTools.BuildTuple(8, Matrix.Identity),
    i
}();
RegisterClass("BABYLON.Vector2", Vector2);
RegisterClass("BABYLON.Vector3", Vector3);
RegisterClass("BABYLON.Vector4", Vector4);
RegisterClass("BABYLON.Matrix", Matrix);
var mtxConvertNDCToHalfZRange = Matrix.FromValues(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, .5, 0, 0, 0, .5, 1)
  , AbstractScene = function() {
    function i() {
        this.rootNodes = new Array,
        this.cameras = new Array,
        this.lights = new Array,
        this.meshes = new Array,
        this.skeletons = new Array,
        this.particleSystems = new Array,
        this.animations = [],
        this.animationGroups = new Array,
        this.multiMaterials = new Array,
        this.materials = new Array,
        this.morphTargetManagers = new Array,
        this.geometries = new Array,
        this.transformNodes = new Array,
        this.actionManagers = new Array,
        this.textures = new Array,
        this._environmentTexture = null,
        this.postProcesses = new Array
    }
    return i.AddParser = function(e, t) {
        this._BabylonFileParsers[e] = t
    }
    ,
    i.GetParser = function(e) {
        return this._BabylonFileParsers[e] ? this._BabylonFileParsers[e] : null
    }
    ,
    i.AddIndividualParser = function(e, t) {
        this._IndividualBabylonFileParsers[e] = t
    }
    ,
    i.GetIndividualParser = function(e) {
        return this._IndividualBabylonFileParsers[e] ? this._IndividualBabylonFileParsers[e] : null
    }
    ,
    i.Parse = function(e, t, r, n) {
        for (var o in this._BabylonFileParsers)
            this._BabylonFileParsers.hasOwnProperty(o) && this._BabylonFileParsers[o](e, t, r, n)
    }
    ,
    Object.defineProperty(i.prototype, "environmentTexture", {
        get: function() {
            return this._environmentTexture
        },
        set: function(e) {
            this._environmentTexture = e
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.getNodes = function() {
        var e = new Array;
        return e = e.concat(this.meshes),
        e = e.concat(this.lights),
        e = e.concat(this.cameras),
        e = e.concat(this.transformNodes),
        this.skeletons.forEach(function(t) {
            return e = e.concat(t.bones)
        }),
        e
    }
    ,
    i._BabylonFileParsers = {},
    i._IndividualBabylonFileParsers = {},
    i
}()
  , Color3 = function() {
    function i(e, t, r) {
        e === void 0 && (e = 0),
        t === void 0 && (t = 0),
        r === void 0 && (r = 0),
        this.r = e,
        this.g = t,
        this.b = r
    }
    return i.prototype.toString = function() {
        return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}"
    }
    ,
    i.prototype.getClassName = function() {
        return "Color3"
    }
    ,
    i.prototype.getHashCode = function() {
        var e = this.r * 255 | 0;
        return e = e * 397 ^ (this.g * 255 | 0),
        e = e * 397 ^ (this.b * 255 | 0),
        e
    }
    ,
    i.prototype.toArray = function(e, t) {
        return t === void 0 && (t = 0),
        e[t] = this.r,
        e[t + 1] = this.g,
        e[t + 2] = this.b,
        this
    }
    ,
    i.prototype.fromArray = function(e, t) {
        return t === void 0 && (t = 0),
        i.FromArrayToRef(e, t, this),
        this
    }
    ,
    i.prototype.toColor4 = function(e) {
        return e === void 0 && (e = 1),
        new Color4(this.r,this.g,this.b,e)
    }
    ,
    i.prototype.asArray = function() {
        var e = new Array;
        return this.toArray(e, 0),
        e
    }
    ,
    i.prototype.toLuminance = function() {
        return this.r * .3 + this.g * .59 + this.b * .11
    }
    ,
    i.prototype.multiply = function(e) {
        return new i(this.r * e.r,this.g * e.g,this.b * e.b)
    }
    ,
    i.prototype.multiplyToRef = function(e, t) {
        return t.r = this.r * e.r,
        t.g = this.g * e.g,
        t.b = this.b * e.b,
        this
    }
    ,
    i.prototype.equals = function(e) {
        return e && this.r === e.r && this.g === e.g && this.b === e.b
    }
    ,
    i.prototype.equalsFloats = function(e, t, r) {
        return this.r === e && this.g === t && this.b === r
    }
    ,
    i.prototype.scale = function(e) {
        return new i(this.r * e,this.g * e,this.b * e)
    }
    ,
    i.prototype.scaleToRef = function(e, t) {
        return t.r = this.r * e,
        t.g = this.g * e,
        t.b = this.b * e,
        this
    }
    ,
    i.prototype.scaleAndAddToRef = function(e, t) {
        return t.r += this.r * e,
        t.g += this.g * e,
        t.b += this.b * e,
        this
    }
    ,
    i.prototype.clampToRef = function(e, t, r) {
        return e === void 0 && (e = 0),
        t === void 0 && (t = 1),
        r.r = Scalar.Clamp(this.r, e, t),
        r.g = Scalar.Clamp(this.g, e, t),
        r.b = Scalar.Clamp(this.b, e, t),
        this
    }
    ,
    i.prototype.add = function(e) {
        return new i(this.r + e.r,this.g + e.g,this.b + e.b)
    }
    ,
    i.prototype.addToRef = function(e, t) {
        return t.r = this.r + e.r,
        t.g = this.g + e.g,
        t.b = this.b + e.b,
        this
    }
    ,
    i.prototype.subtract = function(e) {
        return new i(this.r - e.r,this.g - e.g,this.b - e.b)
    }
    ,
    i.prototype.subtractToRef = function(e, t) {
        return t.r = this.r - e.r,
        t.g = this.g - e.g,
        t.b = this.b - e.b,
        this
    }
    ,
    i.prototype.clone = function() {
        return new i(this.r,this.g,this.b)
    }
    ,
    i.prototype.copyFrom = function(e) {
        return this.r = e.r,
        this.g = e.g,
        this.b = e.b,
        this
    }
    ,
    i.prototype.copyFromFloats = function(e, t, r) {
        return this.r = e,
        this.g = t,
        this.b = r,
        this
    }
    ,
    i.prototype.set = function(e, t, r) {
        return this.copyFromFloats(e, t, r)
    }
    ,
    i.prototype.toHexString = function() {
        var e = Math.round(this.r * 255)
          , t = Math.round(this.g * 255)
          , r = Math.round(this.b * 255);
        return "#" + Scalar.ToHex(e) + Scalar.ToHex(t) + Scalar.ToHex(r)
    }
    ,
    i.prototype.toLinearSpace = function() {
        var e = new i;
        return this.toLinearSpaceToRef(e),
        e
    }
    ,
    i.prototype.toHSV = function() {
        var e = new i;
        return this.toHSVToRef(e),
        e
    }
    ,
    i.prototype.toHSVToRef = function(e) {
        var t = this.r
          , r = this.g
          , n = this.b
          , o = Math.max(t, r, n)
          , a = Math.min(t, r, n)
          , s = 0
          , l = 0
          , u = o
          , c = o - a;
        o !== 0 && (l = c / o),
        o != a && (o == t ? (s = (r - n) / c,
        r < n && (s += 6)) : o == r ? s = (n - t) / c + 2 : o == n && (s = (t - r) / c + 4),
        s *= 60),
        e.r = s,
        e.g = l,
        e.b = u
    }
    ,
    i.prototype.toLinearSpaceToRef = function(e) {
        return e.r = Math.pow(this.r, ToLinearSpace),
        e.g = Math.pow(this.g, ToLinearSpace),
        e.b = Math.pow(this.b, ToLinearSpace),
        this
    }
    ,
    i.prototype.toGammaSpace = function() {
        var e = new i;
        return this.toGammaSpaceToRef(e),
        e
    }
    ,
    i.prototype.toGammaSpaceToRef = function(e) {
        return e.r = Math.pow(this.r, ToGammaSpace),
        e.g = Math.pow(this.g, ToGammaSpace),
        e.b = Math.pow(this.b, ToGammaSpace),
        this
    }
    ,
    i.HSVtoRGBToRef = function(e, t, r, n) {
        var o = r * t
          , a = e / 60
          , s = o * (1 - Math.abs(a % 2 - 1))
          , l = 0
          , u = 0
          , c = 0;
        a >= 0 && a <= 1 ? (l = o,
        u = s) : a >= 1 && a <= 2 ? (l = s,
        u = o) : a >= 2 && a <= 3 ? (u = o,
        c = s) : a >= 3 && a <= 4 ? (u = s,
        c = o) : a >= 4 && a <= 5 ? (l = s,
        c = o) : a >= 5 && a <= 6 && (l = o,
        c = s);
        var h = r - o;
        n.set(l + h, u + h, c + h)
    }
    ,
    i.FromHexString = function(e) {
        if (e.substring(0, 1) !== "#" || e.length !== 7)
            return new i(0,0,0);
        var t = parseInt(e.substring(1, 3), 16)
          , r = parseInt(e.substring(3, 5), 16)
          , n = parseInt(e.substring(5, 7), 16);
        return i.FromInts(t, r, n)
    }
    ,
    i.FromArray = function(e, t) {
        return t === void 0 && (t = 0),
        new i(e[t],e[t + 1],e[t + 2])
    }
    ,
    i.FromArrayToRef = function(e, t, r) {
        t === void 0 && (t = 0),
        r.r = e[t],
        r.g = e[t + 1],
        r.b = e[t + 2]
    }
    ,
    i.FromInts = function(e, t, r) {
        return new i(e / 255,t / 255,r / 255)
    }
    ,
    i.Lerp = function(e, t, r) {
        var n = new i(0,0,0);
        return i.LerpToRef(e, t, r, n),
        n
    }
    ,
    i.LerpToRef = function(e, t, r, n) {
        n.r = e.r + (t.r - e.r) * r,
        n.g = e.g + (t.g - e.g) * r,
        n.b = e.b + (t.b - e.b) * r
    }
    ,
    i.Hermite = function(e, t, r, n, o) {
        var a = o * o
          , s = o * a
          , l = 2 * s - 3 * a + 1
          , u = -2 * s + 3 * a
          , c = s - 2 * a + o
          , h = s - a
          , f = e.r * l + r.r * u + t.r * c + n.r * h
          , d = e.g * l + r.g * u + t.g * c + n.g * h
          , _ = e.b * l + r.b * u + t.b * c + n.b * h;
        return new i(f,d,_)
    }
    ,
    i.Hermite1stDerivative = function(e, t, r, n, o) {
        var a = i.Black();
        return this.Hermite1stDerivativeToRef(e, t, r, n, o, a),
        a
    }
    ,
    i.Hermite1stDerivativeToRef = function(e, t, r, n, o, a) {
        var s = o * o;
        a.r = (s - o) * 6 * e.r + (3 * s - 4 * o + 1) * t.r + (-s + o) * 6 * r.r + (3 * s - 2 * o) * n.r,
        a.g = (s - o) * 6 * e.g + (3 * s - 4 * o + 1) * t.g + (-s + o) * 6 * r.g + (3 * s - 2 * o) * n.g,
        a.b = (s - o) * 6 * e.b + (3 * s - 4 * o + 1) * t.b + (-s + o) * 6 * r.b + (3 * s - 2 * o) * n.b
    }
    ,
    i.Red = function() {
        return new i(1,0,0)
    }
    ,
    i.Green = function() {
        return new i(0,1,0)
    }
    ,
    i.Blue = function() {
        return new i(0,0,1)
    }
    ,
    i.Black = function() {
        return new i(0,0,0)
    }
    ,
    Object.defineProperty(i, "BlackReadOnly", {
        get: function() {
            return i._BlackReadOnly
        },
        enumerable: !1,
        configurable: !0
    }),
    i.White = function() {
        return new i(1,1,1)
    }
    ,
    i.Purple = function() {
        return new i(.5,0,.5)
    }
    ,
    i.Magenta = function() {
        return new i(1,0,1)
    }
    ,
    i.Yellow = function() {
        return new i(1,1,0)
    }
    ,
    i.Gray = function() {
        return new i(.5,.5,.5)
    }
    ,
    i.Teal = function() {
        return new i(0,1,1)
    }
    ,
    i.Random = function() {
        return new i(Math.random(),Math.random(),Math.random())
    }
    ,
    i._BlackReadOnly = i.Black(),
    i
}()
  , Color4 = function() {
    function i(e, t, r, n) {
        e === void 0 && (e = 0),
        t === void 0 && (t = 0),
        r === void 0 && (r = 0),
        n === void 0 && (n = 1),
        this.r = e,
        this.g = t,
        this.b = r,
        this.a = n
    }
    return i.prototype.addInPlace = function(e) {
        return this.r += e.r,
        this.g += e.g,
        this.b += e.b,
        this.a += e.a,
        this
    }
    ,
    i.prototype.asArray = function() {
        var e = new Array;
        return this.toArray(e, 0),
        e
    }
    ,
    i.prototype.toArray = function(e, t) {
        return t === void 0 && (t = 0),
        e[t] = this.r,
        e[t + 1] = this.g,
        e[t + 2] = this.b,
        e[t + 3] = this.a,
        this
    }
    ,
    i.prototype.fromArray = function(e, t) {
        return t === void 0 && (t = 0),
        i.FromArrayToRef(e, t, this),
        this
    }
    ,
    i.prototype.equals = function(e) {
        return e && this.r === e.r && this.g === e.g && this.b === e.b && this.a === e.a
    }
    ,
    i.prototype.add = function(e) {
        return new i(this.r + e.r,this.g + e.g,this.b + e.b,this.a + e.a)
    }
    ,
    i.prototype.subtract = function(e) {
        return new i(this.r - e.r,this.g - e.g,this.b - e.b,this.a - e.a)
    }
    ,
    i.prototype.subtractToRef = function(e, t) {
        return t.r = this.r - e.r,
        t.g = this.g - e.g,
        t.b = this.b - e.b,
        t.a = this.a - e.a,
        this
    }
    ,
    i.prototype.scale = function(e) {
        return new i(this.r * e,this.g * e,this.b * e,this.a * e)
    }
    ,
    i.prototype.scaleToRef = function(e, t) {
        return t.r = this.r * e,
        t.g = this.g * e,
        t.b = this.b * e,
        t.a = this.a * e,
        this
    }
    ,
    i.prototype.scaleAndAddToRef = function(e, t) {
        return t.r += this.r * e,
        t.g += this.g * e,
        t.b += this.b * e,
        t.a += this.a * e,
        this
    }
    ,
    i.prototype.clampToRef = function(e, t, r) {
        return e === void 0 && (e = 0),
        t === void 0 && (t = 1),
        r.r = Scalar.Clamp(this.r, e, t),
        r.g = Scalar.Clamp(this.g, e, t),
        r.b = Scalar.Clamp(this.b, e, t),
        r.a = Scalar.Clamp(this.a, e, t),
        this
    }
    ,
    i.prototype.multiply = function(e) {
        return new i(this.r * e.r,this.g * e.g,this.b * e.b,this.a * e.a)
    }
    ,
    i.prototype.multiplyToRef = function(e, t) {
        return t.r = this.r * e.r,
        t.g = this.g * e.g,
        t.b = this.b * e.b,
        t.a = this.a * e.a,
        t
    }
    ,
    i.prototype.toString = function() {
        return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}"
    }
    ,
    i.prototype.getClassName = function() {
        return "Color4"
    }
    ,
    i.prototype.getHashCode = function() {
        var e = this.r * 255 | 0;
        return e = e * 397 ^ (this.g * 255 | 0),
        e = e * 397 ^ (this.b * 255 | 0),
        e = e * 397 ^ (this.a * 255 | 0),
        e
    }
    ,
    i.prototype.clone = function() {
        return new i(this.r,this.g,this.b,this.a)
    }
    ,
    i.prototype.copyFrom = function(e) {
        return this.r = e.r,
        this.g = e.g,
        this.b = e.b,
        this.a = e.a,
        this
    }
    ,
    i.prototype.copyFromFloats = function(e, t, r, n) {
        return this.r = e,
        this.g = t,
        this.b = r,
        this.a = n,
        this
    }
    ,
    i.prototype.set = function(e, t, r, n) {
        return this.copyFromFloats(e, t, r, n)
    }
    ,
    i.prototype.toHexString = function(e) {
        e === void 0 && (e = !1);
        var t = Math.round(this.r * 255)
          , r = Math.round(this.g * 255)
          , n = Math.round(this.b * 255);
        if (e)
            return "#" + Scalar.ToHex(t) + Scalar.ToHex(r) + Scalar.ToHex(n);
        var o = Math.round(this.a * 255);
        return "#" + Scalar.ToHex(t) + Scalar.ToHex(r) + Scalar.ToHex(n) + Scalar.ToHex(o)
    }
    ,
    i.prototype.toLinearSpace = function() {
        var e = new i;
        return this.toLinearSpaceToRef(e),
        e
    }
    ,
    i.prototype.toLinearSpaceToRef = function(e) {
        return e.r = Math.pow(this.r, ToLinearSpace),
        e.g = Math.pow(this.g, ToLinearSpace),
        e.b = Math.pow(this.b, ToLinearSpace),
        e.a = this.a,
        this
    }
    ,
    i.prototype.toGammaSpace = function() {
        var e = new i;
        return this.toGammaSpaceToRef(e),
        e
    }
    ,
    i.prototype.toGammaSpaceToRef = function(e) {
        return e.r = Math.pow(this.r, ToGammaSpace),
        e.g = Math.pow(this.g, ToGammaSpace),
        e.b = Math.pow(this.b, ToGammaSpace),
        e.a = this.a,
        this
    }
    ,
    i.FromHexString = function(e) {
        if (e.substring(0, 1) !== "#" || e.length !== 9 && e.length !== 7)
            return new i(0,0,0,0);
        var t = parseInt(e.substring(1, 3), 16)
          , r = parseInt(e.substring(3, 5), 16)
          , n = parseInt(e.substring(5, 7), 16)
          , o = e.length === 9 ? parseInt(e.substring(7, 9), 16) : 255;
        return i.FromInts(t, r, n, o)
    }
    ,
    i.Lerp = function(e, t, r) {
        var n = new i(0,0,0,0);
        return i.LerpToRef(e, t, r, n),
        n
    }
    ,
    i.LerpToRef = function(e, t, r, n) {
        n.r = e.r + (t.r - e.r) * r,
        n.g = e.g + (t.g - e.g) * r,
        n.b = e.b + (t.b - e.b) * r,
        n.a = e.a + (t.a - e.a) * r
    }
    ,
    i.Hermite = function(e, t, r, n, o) {
        var a = o * o
          , s = o * a
          , l = 2 * s - 3 * a + 1
          , u = -2 * s + 3 * a
          , c = s - 2 * a + o
          , h = s - a
          , f = e.r * l + r.r * u + t.r * c + n.r * h
          , d = e.g * l + r.g * u + t.g * c + n.g * h
          , _ = e.b * l + r.b * u + t.b * c + n.b * h
          , g = e.a * l + r.a * u + t.a * c + n.a * h;
        return new i(f,d,_,g)
    }
    ,
    i.Hermite1stDerivative = function(e, t, r, n, o) {
        var a = new i;
        return this.Hermite1stDerivativeToRef(e, t, r, n, o, a),
        a
    }
    ,
    i.Hermite1stDerivativeToRef = function(e, t, r, n, o, a) {
        var s = o * o;
        a.r = (s - o) * 6 * e.r + (3 * s - 4 * o + 1) * t.r + (-s + o) * 6 * r.r + (3 * s - 2 * o) * n.r,
        a.g = (s - o) * 6 * e.g + (3 * s - 4 * o + 1) * t.g + (-s + o) * 6 * r.g + (3 * s - 2 * o) * n.g,
        a.b = (s - o) * 6 * e.b + (3 * s - 4 * o + 1) * t.b + (-s + o) * 6 * r.b + (3 * s - 2 * o) * n.b,
        a.a = (s - o) * 6 * e.a + (3 * s - 4 * o + 1) * t.a + (-s + o) * 6 * r.a + (3 * s - 2 * o) * n.a
    }
    ,
    i.FromColor3 = function(e, t) {
        return t === void 0 && (t = 1),
        new i(e.r,e.g,e.b,t)
    }
    ,
    i.FromArray = function(e, t) {
        return t === void 0 && (t = 0),
        new i(e[t],e[t + 1],e[t + 2],e[t + 3])
    }
    ,
    i.FromArrayToRef = function(e, t, r) {
        t === void 0 && (t = 0),
        r.r = e[t],
        r.g = e[t + 1],
        r.b = e[t + 2],
        r.a = e[t + 3]
    }
    ,
    i.FromInts = function(e, t, r, n) {
        return new i(e / 255,t / 255,r / 255,n / 255)
    }
    ,
    i.CheckColors4 = function(e, t) {
        if (e.length === t * 3) {
            for (var r = [], n = 0; n < e.length; n += 3) {
                var o = n / 3 * 4;
                r[o] = e[n],
                r[o + 1] = e[n + 1],
                r[o + 2] = e[n + 2],
                r[o + 3] = 1
            }
            return r
        }
        return e
    }
    ,
    i
}()
  , TmpColors = function() {
    function i() {}
    return i.Color3 = ArrayTools.BuildArray(3, Color3.Black),
    i.Color4 = ArrayTools.BuildArray(3, function() {
        return new Color4(0,0,0,0)
    }),
    i
}();
RegisterClass("BABYLON.Color3", Color3);
RegisterClass("BABYLON.Color4", Color4);
var __decoratorInitialStore = {}
  , __mergedStore = {}
  , _copySource = function(i, e, t) {
    var r = i();
    Tags && Tags.AddTagsTo(r, e.tags);
    var n = getMergedStore(r);
    for (var o in n) {
        var a = n[o]
          , s = e[o]
          , l = a.type;
        if (s != null && (o !== "uniqueId" || SerializationHelper.AllowLoadingUniqueId))
            switch (l) {
            case 0:
            case 6:
            case 11:
                r[o] = s;
                break;
            case 1:
                r[o] = t || s.isRenderTarget ? s : s.clone();
                break;
            case 2:
            case 3:
            case 4:
            case 5:
            case 7:
            case 10:
            case 12:
                r[o] = t ? s : s.clone();
                break
            }
    }
    return r
};
function getDirectStore(i) {
    var e = i.getClassName();
    return __decoratorInitialStore[e] || (__decoratorInitialStore[e] = {}),
    __decoratorInitialStore[e]
}
function getMergedStore(i) {
    var e = i.getClassName();
    if (__mergedStore[e])
        return __mergedStore[e];
    __mergedStore[e] = {};
    for (var t = __mergedStore[e], r = i, n = e; n; ) {
        var o = __decoratorInitialStore[n];
        for (var a in o)
            t[a] = o[a];
        var s = void 0
          , l = !1;
        do {
            if (s = Object.getPrototypeOf(r),
            !s.getClassName) {
                l = !0;
                break
            }
            if (s.getClassName() !== n)
                break;
            r = s
        } while (s);
        if (l)
            break;
        n = s.getClassName(),
        r = s
    }
    return t
}
function generateSerializableMember(i, e) {
    return function(t, r) {
        var n = getDirectStore(t);
        n[r] || (n[r] = {
            type: i,
            sourceName: e
        })
    }
}
function generateExpandMember(i, e) {
    return e === void 0 && (e = null),
    function(t, r) {
        var n = e || "_" + r;
        Object.defineProperty(t, r, {
            get: function() {
                return this[n]
            },
            set: function(o) {
                this[n] !== o && (this[n] = o,
                t[i].apply(this))
            },
            enumerable: !0,
            configurable: !0
        })
    }
}
function expandToProperty(i, e) {
    return e === void 0 && (e = null),
    generateExpandMember(i, e)
}
function serialize(i) {
    return generateSerializableMember(0, i)
}
function serializeAsTexture(i) {
    return generateSerializableMember(1, i)
}
function serializeAsColor3(i) {
    return generateSerializableMember(2, i)
}
function serializeAsFresnelParameters(i) {
    return generateSerializableMember(3, i)
}
function serializeAsVector2(i) {
    return generateSerializableMember(4, i)
}
function serializeAsVector3(i) {
    return generateSerializableMember(5, i)
}
function serializeAsMeshReference(i) {
    return generateSerializableMember(6, i)
}
function serializeAsColorCurves(i) {
    return generateSerializableMember(7, i)
}
function serializeAsColor4(i) {
    return generateSerializableMember(8, i)
}
function serializeAsImageProcessingConfiguration(i) {
    return generateSerializableMember(9, i)
}
function serializeAsQuaternion(i) {
    return generateSerializableMember(10, i)
}
function serializeAsMatrix(i) {
    return generateSerializableMember(12, i)
}
function serializeAsCameraReference(i) {
    return generateSerializableMember(11, i)
}
var SerializationHelper = function() {
    function i() {}
    return i.AppendSerializedAnimations = function(e, t) {
        if (e.animations) {
            t.animations = [];
            for (var r = 0; r < e.animations.length; r++) {
                var n = e.animations[r];
                t.animations.push(n.serialize())
            }
        }
    }
    ,
    i.Serialize = function(e, t) {
        t || (t = {}),
        Tags && (t.tags = Tags.GetTags(e));
        var r = getMergedStore(e);
        for (var n in r) {
            var o = r[n]
              , a = o.sourceName || n
              , s = o.type
              , l = e[n];
            if (l != null && (n !== "uniqueId" || i.AllowLoadingUniqueId))
                switch (s) {
                case 0:
                    t[a] = l;
                    break;
                case 1:
                    t[a] = l.serialize();
                    break;
                case 2:
                    t[a] = l.asArray();
                    break;
                case 3:
                    t[a] = l.serialize();
                    break;
                case 4:
                    t[a] = l.asArray();
                    break;
                case 5:
                    t[a] = l.asArray();
                    break;
                case 6:
                    t[a] = l.id;
                    break;
                case 7:
                    t[a] = l.serialize();
                    break;
                case 8:
                    t[a] = l.asArray();
                    break;
                case 9:
                    t[a] = l.serialize();
                    break;
                case 10:
                    t[a] = l.asArray();
                    break;
                case 11:
                    t[a] = l.id;
                    break;
                case 12:
                    t[a] = l.asArray();
                    break
                }
        }
        return t
    }
    ,
    i.Parse = function(e, t, r, n) {
        n === void 0 && (n = null);
        var o = e();
        n || (n = ""),
        Tags && Tags.AddTagsTo(o, t.tags);
        var a = getMergedStore(o);
        for (var s in a) {
            var l = a[s]
              , u = t[l.sourceName || s]
              , c = l.type;
            if (u != null && (s !== "uniqueId" || i.AllowLoadingUniqueId)) {
                var h = o;
                switch (c) {
                case 0:
                    h[s] = u;
                    break;
                case 1:
                    r && (h[s] = i._TextureParser(u, r, n));
                    break;
                case 2:
                    h[s] = Color3.FromArray(u);
                    break;
                case 3:
                    h[s] = i._FresnelParametersParser(u);
                    break;
                case 4:
                    h[s] = Vector2.FromArray(u);
                    break;
                case 5:
                    h[s] = Vector3.FromArray(u);
                    break;
                case 6:
                    r && (h[s] = r.getLastMeshById(u));
                    break;
                case 7:
                    h[s] = i._ColorCurvesParser(u);
                    break;
                case 8:
                    h[s] = Color4.FromArray(u);
                    break;
                case 9:
                    h[s] = i._ImageProcessingConfigurationParser(u);
                    break;
                case 10:
                    h[s] = Quaternion.FromArray(u);
                    break;
                case 11:
                    r && (h[s] = r.getCameraById(u));
                case 12:
                    h[s] = Matrix.FromArray(u);
                    break
                }
            }
        }
        return o
    }
    ,
    i.Clone = function(e, t) {
        return _copySource(e, t, !1)
    }
    ,
    i.Instanciate = function(e, t) {
        return _copySource(e, t, !0)
    }
    ,
    i.AllowLoadingUniqueId = !1,
    i._ImageProcessingConfigurationParser = function(e) {
        throw _WarnImport("ImageProcessingConfiguration")
    }
    ,
    i._FresnelParametersParser = function(e) {
        throw _WarnImport("FresnelParameters")
    }
    ,
    i._ColorCurvesParser = function(e) {
        throw _WarnImport("ColorCurves")
    }
    ,
    i._TextureParser = function(e, t, r) {
        throw _WarnImport("Texture")
    }
    ,
    i
}();
function nativeOverride(i, e, t, r) {
    var n = t.value;
    t.value = function() {
        for (var o = [], a = 0; a < arguments.length; a++)
            o[a] = arguments[a];
        var s = n;
        if (typeof _native != "undefined" && _native[e]) {
            var l = _native[e];
            r ? s = function() {
                for (var u = [], c = 0; c < arguments.length; c++)
                    u[c] = arguments[c];
                return r.apply(void 0, u) ? l.apply(void 0, u) : n.apply(void 0, u)
            }
            : s = l
        }
        return i[e] = s,
        s.apply(void 0, o)
    }
}
nativeOverride.filter = function(i) {
    return function(e, t, r) {
        return nativeOverride(e, t, r, i)
    }
}
;
var MaterialDefines = function() {
    function i() {
        this._isDirty = !0,
        this._areLightsDirty = !0,
        this._areLightsDisposed = !1,
        this._areAttributesDirty = !0,
        this._areTexturesDirty = !0,
        this._areFresnelDirty = !0,
        this._areMiscDirty = !0,
        this._arePrePassDirty = !0,
        this._areImageProcessingDirty = !0,
        this._normals = !1,
        this._uvs = !1,
        this._needNormals = !1,
        this._needUVs = !1
    }
    return Object.defineProperty(i.prototype, "isDirty", {
        get: function() {
            return this._isDirty
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.markAsProcessed = function() {
        this._isDirty = !1,
        this._areAttributesDirty = !1,
        this._areTexturesDirty = !1,
        this._areFresnelDirty = !1,
        this._areLightsDirty = !1,
        this._areLightsDisposed = !1,
        this._areMiscDirty = !1,
        this._arePrePassDirty = !1,
        this._areImageProcessingDirty = !1
    }
    ,
    i.prototype.markAsUnprocessed = function() {
        this._isDirty = !0
    }
    ,
    i.prototype.markAllAsDirty = function() {
        this._areTexturesDirty = !0,
        this._areAttributesDirty = !0,
        this._areLightsDirty = !0,
        this._areFresnelDirty = !0,
        this._areMiscDirty = !0,
        this._areImageProcessingDirty = !0,
        this._isDirty = !0
    }
    ,
    i.prototype.markAsImageProcessingDirty = function() {
        this._areImageProcessingDirty = !0,
        this._isDirty = !0
    }
    ,
    i.prototype.markAsLightDirty = function(e) {
        e === void 0 && (e = !1),
        this._areLightsDirty = !0,
        this._areLightsDisposed = this._areLightsDisposed || e,
        this._isDirty = !0
    }
    ,
    i.prototype.markAsAttributesDirty = function() {
        this._areAttributesDirty = !0,
        this._isDirty = !0
    }
    ,
    i.prototype.markAsTexturesDirty = function() {
        this._areTexturesDirty = !0,
        this._isDirty = !0
    }
    ,
    i.prototype.markAsFresnelDirty = function() {
        this._areFresnelDirty = !0,
        this._isDirty = !0
    }
    ,
    i.prototype.markAsMiscDirty = function() {
        this._areMiscDirty = !0,
        this._isDirty = !0
    }
    ,
    i.prototype.markAsPrePassDirty = function() {
        this._arePrePassDirty = !0,
        this._isDirty = !0
    }
    ,
    i.prototype.rebuild = function() {
        this._keys = [];
        for (var e = 0, t = Object.keys(this); e < t.length; e++) {
            var r = t[e];
            r[0] !== "_" && this._keys.push(r)
        }
    }
    ,
    i.prototype.isEqual = function(e) {
        if (this._keys.length !== e._keys.length)
            return !1;
        for (var t = 0; t < this._keys.length; t++) {
            var r = this._keys[t];
            if (this[r] !== e[r])
                return !1
        }
        return !0
    }
    ,
    i.prototype.cloneTo = function(e) {
        this._keys.length !== e._keys.length && (e._keys = this._keys.slice(0));
        for (var t = 0; t < this._keys.length; t++) {
            var r = this._keys[t];
            e[r] = this[r]
        }
    }
    ,
    i.prototype.reset = function() {
        for (var e = 0; e < this._keys.length; e++) {
            var t = this._keys[e]
              , r = typeof this[t];
            switch (r) {
            case "number":
                this[t] = 0;
                break;
            case "string":
                this[t] = "";
                break;
            default:
                this[t] = !1;
                break
            }
        }
    }
    ,
    i.prototype.toString = function() {
        for (var e = "", t = 0; t < this._keys.length; t++) {
            var r = this._keys[t]
              , n = this[r]
              , o = typeof n;
            switch (o) {
            case "number":
            case "string":
                e += "#define " + r + " " + n + `
`;
                break;
            default:
                n && (e += "#define " + r + `
`);
                break
            }
        }
        return e
    }
    ,
    i
}()
  , ColorCurves = function() {
    function i() {
        this._dirty = !0,
        this._tempColor = new Color4(0,0,0,0),
        this._globalCurve = new Color4(0,0,0,0),
        this._highlightsCurve = new Color4(0,0,0,0),
        this._midtonesCurve = new Color4(0,0,0,0),
        this._shadowsCurve = new Color4(0,0,0,0),
        this._positiveCurve = new Color4(0,0,0,0),
        this._negativeCurve = new 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
    }
    return Object.defineProperty(i.prototype, "globalHue", {
        get: function() {
            return this._globalHue
        },
        set: function(e) {
            this._globalHue = e,
            this._dirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "globalDensity", {
        get: function() {
            return this._globalDensity
        },
        set: function(e) {
            this._globalDensity = e,
            this._dirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "globalSaturation", {
        get: function() {
            return this._globalSaturation
        },
        set: function(e) {
            this._globalSaturation = e,
            this._dirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "globalExposure", {
        get: function() {
            return this._globalExposure
        },
        set: function(e) {
            this._globalExposure = e,
            this._dirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "highlightsHue", {
        get: function() {
            return this._highlightsHue
        },
        set: function(e) {
            this._highlightsHue = e,
            this._dirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "highlightsDensity", {
        get: function() {
            return this._highlightsDensity
        },
        set: function(e) {
            this._highlightsDensity = e,
            this._dirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "highlightsSaturation", {
        get: function() {
            return this._highlightsSaturation
        },
        set: function(e) {
            this._highlightsSaturation = e,
            this._dirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "highlightsExposure", {
        get: function() {
            return this._highlightsExposure
        },
        set: function(e) {
            this._highlightsExposure = e,
            this._dirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "midtonesHue", {
        get: function() {
            return this._midtonesHue
        },
        set: function(e) {
            this._midtonesHue = e,
            this._dirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "midtonesDensity", {
        get: function() {
            return this._midtonesDensity
        },
        set: function(e) {
            this._midtonesDensity = e,
            this._dirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "midtonesSaturation", {
        get: function() {
            return this._midtonesSaturation
        },
        set: function(e) {
            this._midtonesSaturation = e,
            this._dirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "midtonesExposure", {
        get: function() {
            return this._midtonesExposure
        },
        set: function(e) {
            this._midtonesExposure = e,
            this._dirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "shadowsHue", {
        get: function() {
            return this._shadowsHue
        },
        set: function(e) {
            this._shadowsHue = e,
            this._dirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "shadowsDensity", {
        get: function() {
            return this._shadowsDensity
        },
        set: function(e) {
            this._shadowsDensity = e,
            this._dirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "shadowsSaturation", {
        get: function() {
            return this._shadowsSaturation
        },
        set: function(e) {
            this._shadowsSaturation = e,
            this._dirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "shadowsExposure", {
        get: function() {
            return this._shadowsExposure
        },
        set: function(e) {
            this._shadowsExposure = e,
            this._dirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.getClassName = function() {
        return "ColorCurves"
    }
    ,
    i.Bind = function(e, t, r, n, o) {
        r === void 0 && (r = "vCameraColorCurvePositive"),
        n === void 0 && (n = "vCameraColorCurveNeutral"),
        o === void 0 && (o = "vCameraColorCurveNegative"),
        e._dirty && (e._dirty = !1,
        e.getColorGradingDataToRef(e._globalHue, e._globalDensity, e._globalSaturation, e._globalExposure, e._globalCurve),
        e.getColorGradingDataToRef(e._highlightsHue, e._highlightsDensity, e._highlightsSaturation, e._highlightsExposure, e._tempColor),
        e._tempColor.multiplyToRef(e._globalCurve, e._highlightsCurve),
        e.getColorGradingDataToRef(e._midtonesHue, e._midtonesDensity, e._midtonesSaturation, e._midtonesExposure, e._tempColor),
        e._tempColor.multiplyToRef(e._globalCurve, e._midtonesCurve),
        e.getColorGradingDataToRef(e._shadowsHue, e._shadowsDensity, e._shadowsSaturation, e._shadowsExposure, e._tempColor),
        e._tempColor.multiplyToRef(e._globalCurve, e._shadowsCurve),
        e._highlightsCurve.subtractToRef(e._midtonesCurve, e._positiveCurve),
        e._midtonesCurve.subtractToRef(e._shadowsCurve, e._negativeCurve)),
        t && (t.setFloat4(r, e._positiveCurve.r, e._positiveCurve.g, e._positiveCurve.b, e._positiveCurve.a),
        t.setFloat4(n, e._midtonesCurve.r, e._midtonesCurve.g, e._midtonesCurve.b, e._midtonesCurve.a),
        t.setFloat4(o, e._negativeCurve.r, e._negativeCurve.g, e._negativeCurve.b, e._negativeCurve.a))
    }
    ,
    i.PrepareUniforms = function(e) {
        e.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative")
    }
    ,
    i.prototype.getColorGradingDataToRef = function(e, t, r, n, o) {
        e != null && (e = i.clamp(e, 0, 360),
        t = i.clamp(t, -100, 100),
        r = i.clamp(r, -100, 100),
        n = i.clamp(n, -100, 100),
        t = i.applyColorGradingSliderNonlinear(t),
        t *= .5,
        n = i.applyColorGradingSliderNonlinear(n),
        t < 0 && (t *= -1,
        e = (e + 180) % 360),
        i.fromHSBToRef(e, t, 50 + .25 * n, o),
        o.scaleToRef(2, o),
        o.a = 1 + .01 * r)
    }
    ,
    i.applyColorGradingSliderNonlinear = function(e) {
        e /= 100;
        var t = Math.abs(e);
        return t = Math.pow(t, 2),
        e < 0 && (t *= -1),
        t *= 100,
        t
    }
    ,
    i.fromHSBToRef = function(e, t, r, n) {
        var o = i.clamp(e, 0, 360)
          , a = i.clamp(t / 100, 0, 1)
          , s = i.clamp(r / 100, 0, 1);
        if (a === 0)
            n.r = s,
            n.g = s,
            n.b = s;
        else {
            o /= 60;
            var l = Math.floor(o)
              , u = o - l
              , c = s * (1 - a)
              , h = s * (1 - a * u)
              , f = s * (1 - a * (1 - u));
            switch (l) {
            case 0:
                n.r = s,
                n.g = f,
                n.b = c;
                break;
            case 1:
                n.r = h,
                n.g = s,
                n.b = c;
                break;
            case 2:
                n.r = c,
                n.g = s,
                n.b = f;
                break;
            case 3:
                n.r = c,
                n.g = h,
                n.b = s;
                break;
            case 4:
                n.r = f,
                n.g = c,
                n.b = s;
                break;
            default:
                n.r = s,
                n.g = c,
                n.b = h;
                break
            }
        }
        n.a = 1
    }
    ,
    i.clamp = function(e, t, r) {
        return Math.min(Math.max(e, t), r)
    }
    ,
    i.prototype.clone = function() {
        return SerializationHelper.Clone(function() {
            return new i
        }, this)
    }
    ,
    i.prototype.serialize = function() {
        return SerializationHelper.Serialize(this)
    }
    ,
    i.Parse = function(e) {
        return SerializationHelper.Parse(function() {
            return new i
        }, e, null, null)
    }
    ,
    __decorate([serialize()], i.prototype, "_globalHue", void 0),
    __decorate([serialize()], i.prototype, "_globalDensity", void 0),
    __decorate([serialize()], i.prototype, "_globalSaturation", void 0),
    __decorate([serialize()], i.prototype, "_globalExposure", void 0),
    __decorate([serialize()], i.prototype, "_highlightsHue", void 0),
    __decorate([serialize()], i.prototype, "_highlightsDensity", void 0),
    __decorate([serialize()], i.prototype, "_highlightsSaturation", void 0),
    __decorate([serialize()], i.prototype, "_highlightsExposure", void 0),
    __decorate([serialize()], i.prototype, "_midtonesHue", void 0),
    __decorate([serialize()], i.prototype, "_midtonesDensity", void 0),
    __decorate([serialize()], i.prototype, "_midtonesSaturation", void 0),
    __decorate([serialize()], i.prototype, "_midtonesExposure", void 0),
    i
}();
SerializationHelper._ColorCurvesParser = ColorCurves.Parse;
var ImageProcessingConfigurationDefines = function(i) {
    __extends(e, i);
    function e() {
        var t = i.call(this) || this;
        return t.IMAGEPROCESSING = !1,
        t.VIGNETTE = !1,
        t.VIGNETTEBLENDMODEMULTIPLY = !1,
        t.VIGNETTEBLENDMODEOPAQUE = !1,
        t.TONEMAPPING = !1,
        t.TONEMAPPING_ACES = !1,
        t.CONTRAST = !1,
        t.COLORCURVES = !1,
        t.COLORGRADING = !1,
        t.COLORGRADING3D = !1,
        t.SAMPLER3DGREENDEPTH = !1,
        t.SAMPLER3DBGRMAP = !1,
        t.IMAGEPROCESSINGPOSTPROCESS = !1,
        t.EXPOSURE = !1,
        t.SKIPFINALCOLORCLAMP = !1,
        t.rebuild(),
        t
    }
    return e
}(MaterialDefines)
  , ImageProcessingConfiguration = function() {
    function i() {
        this.colorCurves = new ColorCurves,
        this._colorCurvesEnabled = !1,
        this._colorGradingEnabled = !1,
        this._colorGradingWithGreenDepth = !0,
        this._colorGradingBGR = !0,
        this._exposure = 1,
        this._toneMappingEnabled = !1,
        this._toneMappingType = i.TONEMAPPING_STANDARD,
        this._contrast = 1,
        this.vignetteStretch = 0,
        this.vignetteCentreX = 0,
        this.vignetteCentreY = 0,
        this.vignetteWeight = 1.5,
        this.vignetteColor = new Color4(0,0,0,0),
        this.vignetteCameraFov = .5,
        this._vignetteBlendMode = i.VIGNETTEMODE_MULTIPLY,
        this._vignetteEnabled = !1,
        this._skipFinalColorClamp = !1,
        this._applyByPostProcess = !1,
        this._isEnabled = !0,
        this.onUpdateParameters = new Observable
    }
    return Object.defineProperty(i.prototype, "colorCurvesEnabled", {
        get: function() {
            return this._colorCurvesEnabled
        },
        set: function(e) {
            this._colorCurvesEnabled !== e && (this._colorCurvesEnabled = e,
            this._updateParameters())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "colorGradingTexture", {
        get: function() {
            return this._colorGradingTexture
        },
        set: function(e) {
            this._colorGradingTexture !== e && (this._colorGradingTexture = e,
            this._updateParameters())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "colorGradingEnabled", {
        get: function() {
            return this._colorGradingEnabled
        },
        set: function(e) {
            this._colorGradingEnabled !== e && (this._colorGradingEnabled = e,
            this._updateParameters())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "colorGradingWithGreenDepth", {
        get: function() {
            return this._colorGradingWithGreenDepth
        },
        set: function(e) {
            this._colorGradingWithGreenDepth !== e && (this._colorGradingWithGreenDepth = e,
            this._updateParameters())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "colorGradingBGR", {
        get: function() {
            return this._colorGradingBGR
        },
        set: function(e) {
            this._colorGradingBGR !== e && (this._colorGradingBGR = e,
            this._updateParameters())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "exposure", {
        get: function() {
            return this._exposure
        },
        set: function(e) {
            this._exposure !== e && (this._exposure = e,
            this._updateParameters())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "toneMappingEnabled", {
        get: function() {
            return this._toneMappingEnabled
        },
        set: function(e) {
            this._toneMappingEnabled !== e && (this._toneMappingEnabled = e,
            this._updateParameters())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "toneMappingType", {
        get: function() {
            return this._toneMappingType
        },
        set: function(e) {
            this._toneMappingType !== e && (this._toneMappingType = e,
            this._updateParameters())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "contrast", {
        get: function() {
            return this._contrast
        },
        set: function(e) {
            this._contrast !== e && (this._contrast = e,
            this._updateParameters())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "vignetteBlendMode", {
        get: function() {
            return this._vignetteBlendMode
        },
        set: function(e) {
            this._vignetteBlendMode !== e && (this._vignetteBlendMode = e,
            this._updateParameters())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "vignetteEnabled", {
        get: function() {
            return this._vignetteEnabled
        },
        set: function(e) {
            this._vignetteEnabled !== e && (this._vignetteEnabled = e,
            this._updateParameters())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "skipFinalColorClamp", {
        get: function() {
            return this._skipFinalColorClamp
        },
        set: function(e) {
            this._skipFinalColorClamp !== e && (this._skipFinalColorClamp = e,
            this._updateParameters())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "applyByPostProcess", {
        get: function() {
            return this._applyByPostProcess
        },
        set: function(e) {
            this._applyByPostProcess !== e && (this._applyByPostProcess = e,
            this._updateParameters())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "isEnabled", {
        get: function() {
            return this._isEnabled
        },
        set: function(e) {
            this._isEnabled !== e && (this._isEnabled = e,
            this._updateParameters())
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype._updateParameters = function() {
        this.onUpdateParameters.notifyObservers(this)
    }
    ,
    i.prototype.getClassName = function() {
        return "ImageProcessingConfiguration"
    }
    ,
    i.PrepareUniforms = function(e, t) {
        t.EXPOSURE && e.push("exposureLinear"),
        t.CONTRAST && e.push("contrast"),
        t.COLORGRADING && e.push("colorTransformSettings"),
        t.VIGNETTE && (e.push("vInverseScreenSize"),
        e.push("vignetteSettings1"),
        e.push("vignetteSettings2")),
        t.COLORCURVES && ColorCurves.PrepareUniforms(e)
    }
    ,
    i.PrepareSamplers = function(e, t) {
        t.COLORGRADING && e.push("txColorTransform")
    }
    ,
    i.prototype.prepareDefines = function(e, t) {
        if (t === void 0 && (t = !1),
        t !== this.applyByPostProcess || !this._isEnabled) {
            e.VIGNETTE = !1,
            e.TONEMAPPING = !1,
            e.TONEMAPPING_ACES = !1,
            e.CONTRAST = !1,
            e.EXPOSURE = !1,
            e.COLORCURVES = !1,
            e.COLORGRADING = !1,
            e.COLORGRADING3D = !1,
            e.IMAGEPROCESSING = !1,
            e.SKIPFINALCOLORCLAMP = this.skipFinalColorClamp,
            e.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
            return
        }
        switch (e.VIGNETTE = this.vignetteEnabled,
        e.VIGNETTEBLENDMODEMULTIPLY = this.vignetteBlendMode === i._VIGNETTEMODE_MULTIPLY,
        e.VIGNETTEBLENDMODEOPAQUE = !e.VIGNETTEBLENDMODEMULTIPLY,
        e.TONEMAPPING = this.toneMappingEnabled,
        this._toneMappingType) {
        case i.TONEMAPPING_ACES:
            e.TONEMAPPING_ACES = !0;
            break;
        default:
            e.TONEMAPPING_ACES = !1;
            break
        }
        e.CONTRAST = this.contrast !== 1,
        e.EXPOSURE = this.exposure !== 1,
        e.COLORCURVES = this.colorCurvesEnabled && !!this.colorCurves,
        e.COLORGRADING = this.colorGradingEnabled && !!this.colorGradingTexture,
        e.COLORGRADING ? e.COLORGRADING3D = this.colorGradingTexture.is3D : e.COLORGRADING3D = !1,
        e.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth,
        e.SAMPLER3DBGRMAP = this.colorGradingBGR,
        e.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess,
        e.SKIPFINALCOLORCLAMP = this.skipFinalColorClamp,
        e.IMAGEPROCESSING = e.VIGNETTE || e.TONEMAPPING || e.CONTRAST || e.EXPOSURE || e.COLORCURVES || e.COLORGRADING
    }
    ,
    i.prototype.isReady = function() {
        return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady()
    }
    ,
    i.prototype.bind = function(e, t) {
        if (this._colorCurvesEnabled && this.colorCurves && ColorCurves.Bind(this.colorCurves, e),
        this._vignetteEnabled) {
            var r = 1 / e.getEngine().getRenderWidth()
              , n = 1 / e.getEngine().getRenderHeight();
            e.setFloat2("vInverseScreenSize", r, n);
            var o = t != null ? t : n / r
              , a = Math.tan(this.vignetteCameraFov * .5)
              , s = a * o
              , l = Math.sqrt(s * a);
            s = Tools.Mix(s, l, this.vignetteStretch),
            a = Tools.Mix(a, l, this.vignetteStretch),
            e.setFloat4("vignetteSettings1", s, a, -s * this.vignetteCentreX, -a * this.vignetteCentreY);
            var u = -2 * this.vignetteWeight;
            e.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, u)
        }
        if (e.setFloat("exposureLinear", this.exposure),
        e.setFloat("contrast", this.contrast),
        this.colorGradingTexture) {
            e.setTexture("txColorTransform", this.colorGradingTexture);
            var c = this.colorGradingTexture.getSize().height;
            e.setFloat4("colorTransformSettings", (c - 1) / c, .5 / c, c, this.colorGradingTexture.level)
        }
    }
    ,
    i.prototype.clone = function() {
        return SerializationHelper.Clone(function() {
            return new i
        }, this)
    }
    ,
    i.prototype.serialize = function() {
        return SerializationHelper.Serialize(this)
    }
    ,
    i.Parse = function(e) {
        return SerializationHelper.Parse(function() {
            return new i
        }, e, null, null)
    }
    ,
    Object.defineProperty(i, "VIGNETTEMODE_MULTIPLY", {
        get: function() {
            return this._VIGNETTEMODE_MULTIPLY
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i, "VIGNETTEMODE_OPAQUE", {
        get: function() {
            return this._VIGNETTEMODE_OPAQUE
        },
        enumerable: !1,
        configurable: !0
    }),
    i.TONEMAPPING_STANDARD = 0,
    i.TONEMAPPING_ACES = 1,
    i._VIGNETTEMODE_MULTIPLY = 0,
    i._VIGNETTEMODE_OPAQUE = 1,
    __decorate([serializeAsColorCurves()], i.prototype, "colorCurves", void 0),
    __decorate([serialize()], i.prototype, "_colorCurvesEnabled", void 0),
    __decorate([serializeAsTexture("colorGradingTexture")], i.prototype, "_colorGradingTexture", void 0),
    __decorate([serialize()], i.prototype, "_colorGradingEnabled", void 0),
    __decorate([serialize()], i.prototype, "_colorGradingWithGreenDepth", void 0),
    __decorate([serialize()], i.prototype, "_colorGradingBGR", void 0),
    __decorate([serialize()], i.prototype, "_exposure", void 0),
    __decorate([serialize()], i.prototype, "_toneMappingEnabled", void 0),
    __decorate([serialize()], i.prototype, "_toneMappingType", void 0),
    __decorate([serialize()], i.prototype, "_contrast", void 0),
    __decorate([serialize()], i.prototype, "vignetteStretch", void 0),
    __decorate([serialize()], i.prototype, "vignetteCentreX", void 0),
    __decorate([serialize()], i.prototype, "vignetteCentreY", void 0),
    __decorate([serialize()], i.prototype, "vignetteWeight", void 0),
    __decorate([serializeAsColor4()], i.prototype, "vignetteColor", void 0),
    __decorate([serialize()], i.prototype, "vignetteCameraFov", void 0),
    __decorate([serialize()], i.prototype, "_vignetteBlendMode", void 0),
    __decorate([serialize()], i.prototype, "_vignetteEnabled", void 0),
    __decorate([serialize()], i.prototype, "_skipFinalColorClamp", void 0),
    __decorate([serialize()], i.prototype, "_applyByPostProcess", void 0),
    __decorate([serialize()], i.prototype, "_isEnabled", void 0),
    i
}();
SerializationHelper._ImageProcessingConfigurationParser = ImageProcessingConfiguration.Parse;
ThinEngine.prototype.createUniformBuffer = function(i) {
    var e = this._gl.createBuffer();
    if (!e)
        throw new Error("Unable to create uniform buffer");
    var t = new WebGLDataBuffer(e);
    return this.bindUniformBuffer(t),
    i instanceof Float32Array ? this._gl.bufferData(this._gl.UNIFORM_BUFFER, i, this._gl.STATIC_DRAW) : this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(i), this._gl.STATIC_DRAW),
    this.bindUniformBuffer(null),
    t.references = 1,
    t
}
;
ThinEngine.prototype.createDynamicUniformBuffer = function(i) {
    var e = this._gl.createBuffer();
    if (!e)
        throw new Error("Unable to create dynamic uniform buffer");
    var t = new WebGLDataBuffer(e);
    return this.bindUniformBuffer(t),
    i instanceof Float32Array ? this._gl.bufferData(this._gl.UNIFORM_BUFFER, i, this._gl.DYNAMIC_DRAW) : this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(i), this._gl.DYNAMIC_DRAW),
    this.bindUniformBuffer(null),
    t.references = 1,
    t
}
;
ThinEngine.prototype.updateUniformBuffer = function(i, e, t, r) {
    this.bindUniformBuffer(i),
    t === void 0 && (t = 0),
    r === void 0 ? e instanceof Float32Array ? this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, t, e) : this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, t, new Float32Array(e)) : e instanceof Float32Array ? this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, e.subarray(t, t + r)) : this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(e).subarray(t, t + r)),
    this.bindUniformBuffer(null)
}
;
ThinEngine.prototype.bindUniformBuffer = function(i) {
    this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, i ? i.underlyingResource : null)
}
;
ThinEngine.prototype.bindUniformBufferBase = function(i, e, t) {
    this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, e, i ? i.underlyingResource : null)
}
;
ThinEngine.prototype.bindUniformBlock = function(i, e, t) {
    var r = i.program
      , n = this._gl.getUniformBlockIndex(r, e);
    this._gl.uniformBlockBinding(r, n, t)
}
;
var UniformBuffer = function() {
    function i(e, t, r, n) {
        this._valueCache = {},
        this._engine = e,
        this._noUBO = !e.supportsUniformBuffers,
        this._dynamic = r,
        this._name = n != null ? n : "no-name",
        this._data = t || [],
        this._uniformLocations = {},
        this._uniformSizes = {},
        this._uniformArraySizes = {},
        this._uniformLocationPointer = 0,
        this._needSync = !1,
        this._engine._features.trackUbosInFrame && (this._buffers = [],
        this._bufferIndex = -1,
        this._createBufferOnWrite = !1,
        this._currentFrameId = 0),
        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.updateFloatArray = this._updateFloatArrayForEffect,
        this.updateArray = this._updateArrayForEffect,
        this.updateIntArray = this._updateIntArrayForEffect,
        this.updateMatrix = this._updateMatrixForEffect,
        this.updateMatrices = this._updateMatricesForEffect,
        this.updateVector3 = this._updateVector3ForEffect,
        this.updateVector4 = this._updateVector4ForEffect,
        this.updateColor3 = this._updateColor3ForEffect,
        this.updateColor4 = this._updateColor4ForEffect,
        this.updateDirectColor4 = this._updateDirectColor4ForEffect,
        this.updateInt = this._updateIntForEffect,
        this.updateInt2 = this._updateInt2ForEffect,
        this.updateInt3 = this._updateInt3ForEffect,
        this.updateInt4 = this._updateInt4ForEffect) : (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.updateFloatArray = this._updateFloatArrayForUniform,
        this.updateArray = this._updateArrayForUniform,
        this.updateIntArray = this._updateIntArrayForUniform,
        this.updateMatrix = this._updateMatrixForUniform,
        this.updateMatrices = this._updateMatricesForUniform,
        this.updateVector3 = this._updateVector3ForUniform,
        this.updateVector4 = this._updateVector4ForUniform,
        this.updateColor3 = this._updateColor3ForUniform,
        this.updateColor4 = this._updateColor4ForUniform,
        this.updateDirectColor4 = this._updateDirectColor4ForUniform,
        this.updateInt = this._updateIntForUniform,
        this.updateInt2 = this._updateInt2ForUniform,
        this.updateInt3 = this._updateInt3ForUniform,
        this.updateInt4 = this._updateInt4ForUniform)
    }
    return Object.defineProperty(i.prototype, "useUbo", {
        get: function() {
            return !this._noUBO
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "isSync", {
        get: function() {
            return !this._needSync
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.isDynamic = function() {
        return this._dynamic !== void 0
    }
    ,
    i.prototype.getData = function() {
        return this._bufferData
    }
    ,
    i.prototype.getBuffer = function() {
        return this._buffer
    }
    ,
    i.prototype._fillAlignment = function(e) {
        var t;
        if (e <= 2 ? t = e : t = 4,
        this._uniformLocationPointer % t !== 0) {
            var r = this._uniformLocationPointer;
            this._uniformLocationPointer += t - this._uniformLocationPointer % t;
            for (var n = this._uniformLocationPointer - r, o = 0; o < n; o++)
                this._data.push(0)
        }
    }
    ,
    i.prototype.addUniform = function(e, t, r) {
        if (r === void 0 && (r = 0),
        !this._noUBO && this._uniformLocations[e] === void 0) {
            var n;
            if (r > 0) {
                if (t instanceof Array)
                    throw "addUniform should not be use with Array in UBO: " + e;
                if (this._fillAlignment(4),
                this._uniformArraySizes[e] = {
                    strideSize: t,
                    arraySize: r
                },
                t == 16)
                    t = t * r;
                else {
                    var o = 4 - t
                      , a = o * r;
                    t = t * r + a
                }
                n = [];
                for (var s = 0; s < t; s++)
                    n.push(0)
            } else {
                if (t instanceof Array)
                    n = t,
                    t = n.length;
                else {
                    t = t,
                    n = [];
                    for (var s = 0; s < t; s++)
                        n.push(0)
                }
                this._fillAlignment(t)
            }
            this._uniformSizes[e] = t,
            this._uniformLocations[e] = this._uniformLocationPointer,
            this._uniformLocationPointer += t;
            for (var s = 0; s < t; s++)
                this._data.push(n[s]);
            this._needSync = !0
        }
    }
    ,
    i.prototype.addMatrix = function(e, t) {
        this.addUniform(e, Array.prototype.slice.call(t.toArray()))
    }
    ,
    i.prototype.addFloat2 = function(e, t, r) {
        var n = [t, r];
        this.addUniform(e, n)
    }
    ,
    i.prototype.addFloat3 = function(e, t, r, n) {
        var o = [t, r, n];
        this.addUniform(e, o)
    }
    ,
    i.prototype.addColor3 = function(e, t) {
        var r = [t.r, t.g, t.b];
        this.addUniform(e, r)
    }
    ,
    i.prototype.addColor4 = function(e, t, r) {
        var n = [t.r, t.g, t.b, r];
        this.addUniform(e, n)
    }
    ,
    i.prototype.addVector3 = function(e, t) {
        var r = [t.x, t.y, t.z];
        this.addUniform(e, r)
    }
    ,
    i.prototype.addMatrix3x3 = function(e) {
        this.addUniform(e, 12)
    }
    ,
    i.prototype.addMatrix2x2 = function(e) {
        this.addUniform(e, 8)
    }
    ,
    i.prototype.create = function() {
        this._noUBO || this._buffer || (this._fillAlignment(4),
        this._bufferData = new Float32Array(this._data),
        this._rebuild(),
        this._needSync = !0)
    }
    ,
    i.prototype._rebuild = function() {
        this._noUBO || !this._bufferData || (this._dynamic ? this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData) : this._buffer = this._engine.createUniformBuffer(this._bufferData),
        this._engine._features.trackUbosInFrame && (this._buffers.push([this._buffer, this._engine._features.checkUbosContentBeforeUpload ? this._bufferData.slice() : void 0]),
        this._bufferIndex = this._buffers.length - 1,
        this._createBufferOnWrite = !1))
    }
    ,
    Object.defineProperty(i.prototype, "_numBuffers", {
        get: function() {
            return this._buffers.length
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "_indexBuffer", {
        get: function() {
            return this._bufferIndex
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "name", {
        get: function() {
            return this._name
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype._buffersEqual = function(e, t) {
        for (var r = 0; r < e.length; ++r)
            if (e[r] !== t[r])
                return !1;
        return !0
    }
    ,
    i.prototype._copyBuffer = function(e, t) {
        for (var r = 0; r < e.length; ++r)
            t[r] = e[r]
    }
    ,
    i.prototype.update = function() {
        if (this.bindUniformBuffer(),
        !this._buffer) {
            this.create();
            return
        }
        if (!this._dynamic && !this._needSync) {
            this._createBufferOnWrite = this._engine._features.trackUbosInFrame;
            return
        }
        if (this._buffers && this._buffers.length > 1 && this._buffers[this._bufferIndex][1])
            if (this._buffersEqual(this._bufferData, this._buffers[this._bufferIndex][1])) {
                this._needSync = !1,
                this._createBufferOnWrite = this._engine._features.trackUbosInFrame;
                return
            } else
                this._copyBuffer(this._bufferData, this._buffers[this._bufferIndex][1]);
        this._engine.updateUniformBuffer(this._buffer, this._bufferData),
        this._engine._features._collectUbosUpdatedInFrame && (i._updatedUbosInFrame[this._name] || (i._updatedUbosInFrame[this._name] = 0),
        i._updatedUbosInFrame[this._name]++),
        this._needSync = !1,
        this._createBufferOnWrite = this._engine._features.trackUbosInFrame
    }
    ,
    i.prototype._createNewBuffer = function() {
        this._bufferIndex + 1 < this._buffers.length ? (this._bufferIndex++,
        this._buffer = this._buffers[this._bufferIndex][0],
        this._createBufferOnWrite = !1,
        this._needSync = !0) : this._rebuild()
    }
    ,
    i.prototype._checkNewFrame = function() {
        this._engine._features.trackUbosInFrame && this._currentFrameId !== this._engine.frameId && (this._currentFrameId = this._engine.frameId,
        this._createBufferOnWrite = !1,
        this._buffers && this._buffers.length > 0 ? (this._needSync = this._bufferIndex !== 0,
        this._bufferIndex = 0,
        this._buffer = this._buffers[this._bufferIndex][0]) : this._bufferIndex = -1)
    }
    ,
    i.prototype.updateUniform = function(e, t, r) {
        this._checkNewFrame();
        var n = this._uniformLocations[e];
        if (n === void 0) {
            if (this._buffer) {
                Logger$2.Error("Cannot add an uniform after UBO has been created.");
                return
            }
            this.addUniform(e, r),
            n = this._uniformLocations[e]
        }
        if (this._buffer || this.create(),
        this._dynamic)
            for (var a = 0; a < r; a++)
                this._bufferData[n + a] = t[a];
        else {
            for (var o = !1, a = 0; a < r; a++)
                (r === 16 && !this._engine._features.uniformBufferHardCheckMatrix || this._bufferData[n + a] !== Tools.FloatRound(t[a])) && (o = !0,
                this._createBufferOnWrite && this._createNewBuffer(),
                this._bufferData[n + a] = t[a]);
            this._needSync = this._needSync || o
        }
    }
    ,
    i.prototype.updateUniformArray = function(e, t, r) {
        this._checkNewFrame();
        var n = this._uniformLocations[e];
        if (n === void 0) {
            Logger$2.Error("Cannot add an uniform Array dynamically. Please, add it using addUniform.");
            return
        }
        this._buffer || this.create();
        var o = this._uniformArraySizes[e];
        if (this._dynamic)
            for (var u = 0; u < r; u++)
                this._bufferData[n + u] = t[u];
        else {
            for (var a = !1, s = 0, l = 0, u = 0; u < r; u++)
                if (this._bufferData[n + l * 4 + s] !== Tools.FloatRound(t[u]) && (a = !0,
                this._createBufferOnWrite && this._createNewBuffer(),
                this._bufferData[n + l * 4 + s] = t[u]),
                s++,
                s === o.strideSize) {
                    for (; s < 4; s++)
                        this._bufferData[n + l * 4 + s] = 0;
                    s = 0,
                    l++
                }
            this._needSync = this._needSync || a
        }
    }
    ,
    i.prototype._cacheMatrix = function(e, t) {
        this._checkNewFrame();
        var r = this._valueCache[e]
          , n = t.updateFlag;
        return r !== void 0 && r === n ? !1 : (this._valueCache[e] = n,
        !0)
    }
    ,
    i.prototype._updateMatrix3x3ForUniform = function(e, t) {
        for (var r = 0; r < 3; r++)
            i._tempBuffer[r * 4] = t[r * 3],
            i._tempBuffer[r * 4 + 1] = t[r * 3 + 1],
            i._tempBuffer[r * 4 + 2] = t[r * 3 + 2],
            i._tempBuffer[r * 4 + 3] = 0;
        this.updateUniform(e, i._tempBuffer, 12)
    }
    ,
    i.prototype._updateMatrix3x3ForEffect = function(e, t) {
        this._currentEffect.setMatrix3x3(e, t)
    }
    ,
    i.prototype._updateMatrix2x2ForEffect = function(e, t) {
        this._currentEffect.setMatrix2x2(e, t)
    }
    ,
    i.prototype._updateMatrix2x2ForUniform = function(e, t) {
        for (var r = 0; r < 2; r++)
            i._tempBuffer[r * 4] = t[r * 2],
            i._tempBuffer[r * 4 + 1] = t[r * 2 + 1],
            i._tempBuffer[r * 4 + 2] = 0,
            i._tempBuffer[r * 4 + 3] = 0;
        this.updateUniform(e, i._tempBuffer, 8)
    }
    ,
    i.prototype._updateFloatForEffect = function(e, t) {
        this._currentEffect.setFloat(e, t)
    }
    ,
    i.prototype._updateFloatForUniform = function(e, t) {
        i._tempBuffer[0] = t,
        this.updateUniform(e, i._tempBuffer, 1)
    }
    ,
    i.prototype._updateFloat2ForEffect = function(e, t, r, n) {
        n === void 0 && (n = ""),
        this._currentEffect.setFloat2(e + n, t, r)
    }
    ,
    i.prototype._updateFloat2ForUniform = function(e, t, r) {
        i._tempBuffer[0] = t,
        i._tempBuffer[1] = r,
        this.updateUniform(e, i._tempBuffer, 2)
    }
    ,
    i.prototype._updateFloat3ForEffect = function(e, t, r, n, o) {
        o === void 0 && (o = ""),
        this._currentEffect.setFloat3(e + o, t, r, n)
    }
    ,
    i.prototype._updateFloat3ForUniform = function(e, t, r, n) {
        i._tempBuffer[0] = t,
        i._tempBuffer[1] = r,
        i._tempBuffer[2] = n,
        this.updateUniform(e, i._tempBuffer, 3)
    }
    ,
    i.prototype._updateFloat4ForEffect = function(e, t, r, n, o, a) {
        a === void 0 && (a = ""),
        this._currentEffect.setFloat4(e + a, t, r, n, o)
    }
    ,
    i.prototype._updateFloat4ForUniform = function(e, t, r, n, o) {
        i._tempBuffer[0] = t,
        i._tempBuffer[1] = r,
        i._tempBuffer[2] = n,
        i._tempBuffer[3] = o,
        this.updateUniform(e, i._tempBuffer, 4)
    }
    ,
    i.prototype._updateFloatArrayForEffect = function(e, t) {
        this._currentEffect.setFloatArray(e, t)
    }
    ,
    i.prototype._updateFloatArrayForUniform = function(e, t) {
        this.updateUniformArray(e, t, t.length)
    }
    ,
    i.prototype._updateArrayForEffect = function(e, t) {
        this._currentEffect.setArray(e, t)
    }
    ,
    i.prototype._updateArrayForUniform = function(e, t) {
        this.updateUniformArray(e, t, t.length)
    }
    ,
    i.prototype._updateIntArrayForEffect = function(e, t) {
        this._currentEffect.setIntArray(e, t)
    }
    ,
    i.prototype._updateIntArrayForUniform = function(e, t) {
        i._tempBufferInt32View.set(t),
        this.updateUniformArray(e, i._tempBuffer, t.length)
    }
    ,
    i.prototype._updateMatrixForEffect = function(e, t) {
        this._currentEffect.setMatrix(e, t)
    }
    ,
    i.prototype._updateMatrixForUniform = function(e, t) {
        this._cacheMatrix(e, t) && this.updateUniform(e, t.toArray(), 16)
    }
    ,
    i.prototype._updateMatricesForEffect = function(e, t) {
        this._currentEffect.setMatrices(e, t)
    }
    ,
    i.prototype._updateMatricesForUniform = function(e, t) {
        this.updateUniform(e, t, t.length)
    }
    ,
    i.prototype._updateVector3ForEffect = function(e, t) {
        this._currentEffect.setVector3(e, t)
    }
    ,
    i.prototype._updateVector3ForUniform = function(e, t) {
        i._tempBuffer[0] = t.x,
        i._tempBuffer[1] = t.y,
        i._tempBuffer[2] = t.z,
        this.updateUniform(e, i._tempBuffer, 3)
    }
    ,
    i.prototype._updateVector4ForEffect = function(e, t) {
        this._currentEffect.setVector4(e, t)
    }
    ,
    i.prototype._updateVector4ForUniform = function(e, t) {
        i._tempBuffer[0] = t.x,
        i._tempBuffer[1] = t.y,
        i._tempBuffer[2] = t.z,
        i._tempBuffer[3] = t.w,
        this.updateUniform(e, i._tempBuffer, 4)
    }
    ,
    i.prototype._updateColor3ForEffect = function(e, t, r) {
        r === void 0 && (r = ""),
        this._currentEffect.setColor3(e + r, t)
    }
    ,
    i.prototype._updateColor3ForUniform = function(e, t) {
        i._tempBuffer[0] = t.r,
        i._tempBuffer[1] = t.g,
        i._tempBuffer[2] = t.b,
        this.updateUniform(e, i._tempBuffer, 3)
    }
    ,
    i.prototype._updateColor4ForEffect = function(e, t, r, n) {
        n === void 0 && (n = ""),
        this._currentEffect.setColor4(e + n, t, r)
    }
    ,
    i.prototype._updateDirectColor4ForEffect = function(e, t, r) {
        r === void 0 && (r = ""),
        this._currentEffect.setDirectColor4(e + r, t)
    }
    ,
    i.prototype._updateColor4ForUniform = function(e, t, r) {
        i._tempBuffer[0] = t.r,
        i._tempBuffer[1] = t.g,
        i._tempBuffer[2] = t.b,
        i._tempBuffer[3] = r,
        this.updateUniform(e, i._tempBuffer, 4)
    }
    ,
    i.prototype._updateDirectColor4ForUniform = function(e, t) {
        i._tempBuffer[0] = t.r,
        i._tempBuffer[1] = t.g,
        i._tempBuffer[2] = t.b,
        i._tempBuffer[3] = t.a,
        this.updateUniform(e, i._tempBuffer, 4)
    }
    ,
    i.prototype._updateIntForEffect = function(e, t, r) {
        r === void 0 && (r = ""),
        this._currentEffect.setInt(e + r, t)
    }
    ,
    i.prototype._updateIntForUniform = function(e, t) {
        i._tempBufferInt32View[0] = t,
        this.updateUniform(e, i._tempBuffer, 1)
    }
    ,
    i.prototype._updateInt2ForEffect = function(e, t, r, n) {
        n === void 0 && (n = ""),
        this._currentEffect.setInt2(e + n, t, r)
    }
    ,
    i.prototype._updateInt2ForUniform = function(e, t, r) {
        i._tempBufferInt32View[0] = t,
        i._tempBufferInt32View[1] = r,
        this.updateUniform(e, i._tempBuffer, 2)
    }
    ,
    i.prototype._updateInt3ForEffect = function(e, t, r, n, o) {
        o === void 0 && (o = ""),
        this._currentEffect.setInt3(e + o, t, r, n)
    }
    ,
    i.prototype._updateInt3ForUniform = function(e, t, r, n) {
        i._tempBufferInt32View[0] = t,
        i._tempBufferInt32View[1] = r,
        i._tempBufferInt32View[2] = n,
        this.updateUniform(e, i._tempBuffer, 3)
    }
    ,
    i.prototype._updateInt4ForEffect = function(e, t, r, n, o, a) {
        a === void 0 && (a = ""),
        this._currentEffect.setInt4(e + a, t, r, n, o)
    }
    ,
    i.prototype._updateInt4ForUniform = function(e, t, r, n, o) {
        i._tempBufferInt32View[0] = t,
        i._tempBufferInt32View[1] = r,
        i._tempBufferInt32View[2] = n,
        i._tempBufferInt32View[3] = o,
        this.updateUniform(e, i._tempBuffer, 4)
    }
    ,
    i.prototype.setTexture = function(e, t) {
        this._currentEffect.setTexture(e, t)
    }
    ,
    i.prototype.updateUniformDirectly = function(e, t) {
        this.updateUniform(e, t, t.length),
        this.update()
    }
    ,
    i.prototype.bindToEffect = function(e, t) {
        this._currentEffect = e,
        this._currentEffectName = t
    }
    ,
    i.prototype.bindUniformBuffer = function() {
        !this._noUBO && this._buffer && this._currentEffect && this._currentEffect.bindUniformBuffer(this._buffer, this._currentEffectName)
    }
    ,
    i.prototype.unbindEffect = function() {
        this._currentEffect = void 0,
        this._currentEffectName = void 0
    }
    ,
    i.prototype.dispose = function() {
        if (!this._noUBO) {
            var e = this._engine._uniformBuffers
              , t = e.indexOf(this);
            if (t !== -1 && (e[t] = e[e.length - 1],
            e.pop()),
            this._engine._features.trackUbosInFrame && this._buffers)
                for (var r = 0; r < this._buffers.length; ++r) {
                    var n = this._buffers[r][0];
                    this._engine._releaseBuffer(n)
                }
            else
                this._buffer && this._engine._releaseBuffer(this._buffer) && (this._buffer = null)
        }
    }
    ,
    i._updatedUbosInFrame = {},
    i._MAX_UNIFORM_SIZE = 256,
    i._tempBuffer = new Float32Array(i._MAX_UNIFORM_SIZE),
    i._tempBufferInt32View = new Uint32Array(i._tempBuffer.buffer),
    i
}(), Buffer = function() {
    function i(e, t, r, n, o, a, s, l) {
        n === void 0 && (n = 0),
        o === void 0 && (o = !1),
        a === void 0 && (a = !1),
        s === void 0 && (s = !1),
        this._isAlreadyOwned = !1,
        e.getScene ? this._engine = e.getScene().getEngine() : this._engine = e,
        this._updatable = r,
        this._instanced = a,
        this._divisor = l || 1,
        t instanceof DataBuffer ? (this._data = null,
        this._buffer = t) : (this._data = t,
        this._buffer = null),
        this.byteStride = s ? n : n * Float32Array.BYTES_PER_ELEMENT,
        o || this.create()
    }
    return i.prototype.createVertexBuffer = function(e, t, r, n, o, a, s) {
        a === void 0 && (a = !1);
        var l = a ? t : t * Float32Array.BYTES_PER_ELEMENT
          , u = n ? a ? n : n * Float32Array.BYTES_PER_ELEMENT : this.byteStride;
        return new VertexBuffer(this._engine,this,e,this._updatable,!0,u,o === void 0 ? this._instanced : o,l,r,void 0,void 0,!0,this._divisor || s)
    }
    ,
    i.prototype.isUpdatable = function() {
        return this._updatable
    }
    ,
    i.prototype.getData = function() {
        return this._data
    }
    ,
    i.prototype.getBuffer = function() {
        return this._buffer
    }
    ,
    i.prototype.getStrideSize = function() {
        return this.byteStride / Float32Array.BYTES_PER_ELEMENT
    }
    ,
    i.prototype.create = function(e) {
        e === void 0 && (e = null),
        !(!e && this._buffer) && (e = e || this._data,
        e && (this._buffer ? this._updatable && (this._engine.updateDynamicVertexBuffer(this._buffer, e),
        this._data = e) : this._updatable ? (this._buffer = this._engine.createDynamicVertexBuffer(e),
        this._data = e) : this._buffer = this._engine.createVertexBuffer(e)))
    }
    ,
    i.prototype._rebuild = function() {
        this._buffer = null,
        this.create(this._data)
    }
    ,
    i.prototype.update = function(e) {
        this.create(e)
    }
    ,
    i.prototype.updateDirectly = function(e, t, r, n) {
        n === void 0 && (n = !1),
        !!this._buffer && this._updatable && (this._engine.updateDynamicVertexBuffer(this._buffer, e, n ? t : t * Float32Array.BYTES_PER_ELEMENT, r ? r * this.byteStride : void 0),
        this._data = null)
    }
    ,
    i.prototype._increaseReferences = function() {
        if (!!this._buffer) {
            if (!this._isAlreadyOwned) {
                this._isAlreadyOwned = !0;
                return
            }
            this._buffer.references++
        }
    }
    ,
    i.prototype.dispose = function() {
        !this._buffer || this._engine._releaseBuffer(this._buffer) && (this._buffer = null,
        this._data = null)
    }
    ,
    i
}(), VertexBuffer = function() {
    function i(e, t, r, n, o, a, s, l, u, c, h, f, d, _) {
        if (h === void 0 && (h = !1),
        f === void 0 && (f = !1),
        d === void 0 && (d = 1),
        _ === void 0 && (_ = !1),
        t instanceof Buffer ? (this._buffer = t,
        this._ownsBuffer = _) : (this._buffer = new Buffer(e,t,n,a,o,s,f),
        this._ownsBuffer = !0),
        this.uniqueId = i._Counter++,
        this._kind = r,
        c == null) {
            var g = this.getData();
            this.type = i.FLOAT,
            g instanceof Int8Array ? this.type = i.BYTE : g instanceof Uint8Array ? this.type = i.UNSIGNED_BYTE : g instanceof Int16Array ? this.type = i.SHORT : g instanceof Uint16Array ? this.type = i.UNSIGNED_SHORT : g instanceof Int32Array ? this.type = i.INT : g instanceof Uint32Array && (this.type = i.UNSIGNED_INT)
        } else
            this.type = c;
        var m = i.GetTypeByteLength(this.type);
        f ? (this._size = u || (a ? a / m : i.DeduceStride(r)),
        this.byteStride = a || this._buffer.byteStride || this._size * m,
        this.byteOffset = l || 0) : (this._size = u || a || i.DeduceStride(r),
        this.byteStride = a ? a * m : this._buffer.byteStride || this._size * m,
        this.byteOffset = (l || 0) * m),
        this.normalized = h,
        this._instanced = s !== void 0 ? s : !1,
        this._instanceDivisor = s ? d : 0,
        this._computeHashCode()
    }
    return Object.defineProperty(i.prototype, "instanceDivisor", {
        get: function() {
            return this._instanceDivisor
        },
        set: function(e) {
            this._instanceDivisor = e,
            e == 0 ? this._instanced = !1 : this._instanced = !0,
            this._computeHashCode()
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype._computeHashCode = function() {
        this.hashCode = (this.type - 5120 << 0) + ((this.normalized ? 1 : 0) << 3) + (this._size << 4) + ((this._instanced ? 1 : 0) << 6) + (this.byteStride << 12)
    }
    ,
    i.prototype._rebuild = function() {
        !this._buffer || this._buffer._rebuild()
    }
    ,
    i.prototype.getKind = function() {
        return this._kind
    }
    ,
    i.prototype.isUpdatable = function() {
        return this._buffer.isUpdatable()
    }
    ,
    i.prototype.getData = function() {
        return this._buffer.getData()
    }
    ,
    i.prototype.getFloatData = function(e, t) {
        var r = this.getData();
        if (!r)
            return null;
        var n = this.getSize() * i.GetTypeByteLength(this.type)
          , o = e * this.getSize();
        if (this.type !== i.FLOAT || this.byteStride !== n) {
            var a = new Float32Array(o);
            return this.forEach(o, function(h, f) {
                return a[f] = h
            }),
            a
        }
        if (!(r instanceof Array || r instanceof Float32Array) || this.byteOffset !== 0 || r.length !== o)
            if (r instanceof Array) {
                var s = this.byteOffset / 4;
                return SliceTools.Slice(r, s, s + o)
            } else {
                if (r instanceof ArrayBuffer)
                    return new Float32Array(r,this.byteOffset,o);
                var s = r.byteOffset + this.byteOffset;
                if (t) {
                    var l = new Float32Array(o)
                      , u = new Float32Array(r.buffer,s,o);
                    return l.set(u),
                    l
                }
                var c = s % 4;
                return c && (s = Math.max(0, s - c)),
                new Float32Array(r.buffer,s,o)
            }
        return t ? SliceTools.Slice(r) : r
    }
    ,
    i.prototype.getBuffer = function() {
        return this._buffer.getBuffer()
    }
    ,
    i.prototype.getStrideSize = function() {
        return this.byteStride / i.GetTypeByteLength(this.type)
    }
    ,
    i.prototype.getOffset = function() {
        return this.byteOffset / i.GetTypeByteLength(this.type)
    }
    ,
    i.prototype.getSize = function(e) {
        return e === void 0 && (e = !1),
        e ? this._size * i.GetTypeByteLength(this.type) : this._size
    }
    ,
    i.prototype.getIsInstanced = function() {
        return this._instanced
    }
    ,
    i.prototype.getInstanceDivisor = function() {
        return this._instanceDivisor
    }
    ,
    i.prototype.create = function(e) {
        this._buffer.create(e)
    }
    ,
    i.prototype.update = function(e) {
        this._buffer.update(e)
    }
    ,
    i.prototype.updateDirectly = function(e, t, r) {
        r === void 0 && (r = !1),
        this._buffer.updateDirectly(e, t, void 0, r)
    }
    ,
    i.prototype.dispose = function() {
        this._ownsBuffer && this._buffer.dispose()
    }
    ,
    i.prototype.forEach = function(e, t) {
        i.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, e, this.normalized, t)
    }
    ,
    i.DeduceStride = function(e) {
        switch (e) {
        case i.UVKind:
        case i.UV2Kind:
        case i.UV3Kind:
        case i.UV4Kind:
        case i.UV5Kind:
        case i.UV6Kind:
            return 2;
        case i.NormalKind:
        case i.PositionKind:
            return 3;
        case i.ColorKind:
        case i.MatricesIndicesKind:
        case i.MatricesIndicesExtraKind:
        case i.MatricesWeightsKind:
        case i.MatricesWeightsExtraKind:
        case i.TangentKind:
            return 4;
        default:
            throw new Error("Invalid kind '" + e + "'")
        }
    }
    ,
    i.GetTypeByteLength = function(e) {
        switch (e) {
        case i.BYTE:
        case i.UNSIGNED_BYTE:
            return 1;
        case i.SHORT:
        case i.UNSIGNED_SHORT:
            return 2;
        case i.INT:
        case i.UNSIGNED_INT:
        case i.FLOAT:
            return 4;
        default:
            throw new Error("Invalid type '" + e + "'")
        }
    }
    ,
    i.ForEach = function(e, t, r, n, o, a, s, l) {
        if (e instanceof Array)
            for (var u = t / 4, c = r / 4, h = 0; h < a; h += n) {
                for (var f = 0; f < n; f++)
                    l(e[u + f], h + f);
                u += c
            }
        else
            for (var d = e instanceof ArrayBuffer ? new DataView(e) : new DataView(e.buffer,e.byteOffset,e.byteLength), _ = i.GetTypeByteLength(o), h = 0; h < a; h += n) {
                for (var g = t, f = 0; f < n; f++) {
                    var m = i._GetFloatValue(d, o, g, s);
                    l(m, h + f),
                    g += _
                }
                t += r
            }
    }
    ,
    i._GetFloatValue = function(e, t, r, n) {
        switch (t) {
        case i.BYTE:
            {
                var o = e.getInt8(r);
                return n && (o = Math.max(o / 127, -1)),
                o
            }
        case i.UNSIGNED_BYTE:
            {
                var o = e.getUint8(r);
                return n && (o = o / 255),
                o
            }
        case i.SHORT:
            {
                var o = e.getInt16(r, !0);
                return n && (o = Math.max(o / 32767, -1)),
                o
            }
        case i.UNSIGNED_SHORT:
            {
                var o = e.getUint16(r, !0);
                return n && (o = o / 65535),
                o
            }
        case i.INT:
            return e.getInt32(r, !0);
        case i.UNSIGNED_INT:
            return e.getUint32(r, !0);
        case i.FLOAT:
            return e.getFloat32(r, !0);
        default:
            throw new Error("Invalid component type " + t)
        }
    }
    ,
    i._Counter = 0,
    i.BYTE = 5120,
    i.UNSIGNED_BYTE = 5121,
    i.SHORT = 5122,
    i.UNSIGNED_SHORT = 5123,
    i.INT = 5124,
    i.UNSIGNED_INT = 5125,
    i.FLOAT = 5126,
    i.PositionKind = "position",
    i.NormalKind = "normal",
    i.TangentKind = "tangent",
    i.UVKind = "uv",
    i.UV2Kind = "uv2",
    i.UV3Kind = "uv3",
    i.UV4Kind = "uv4",
    i.UV5Kind = "uv5",
    i.UV6Kind = "uv6",
    i.ColorKind = "color",
    i.MatricesIndicesKind = "matricesIndices",
    i.MatricesWeightsKind = "matricesWeights",
    i.MatricesIndicesExtraKind = "matricesIndicesExtra",
    i.MatricesWeightsExtraKind = "matricesWeightsExtra",
    i
}(), PickingInfo = function() {
    function i() {
        this._pickingUnavailable = !1,
        this.hit = !1,
        this.distance = 0,
        this.pickedPoint = null,
        this.pickedMesh = null,
        this.bu = 0,
        this.bv = 0,
        this.faceId = -1,
        this.subMeshFaceId = -1,
        this.subMeshId = 0,
        this.pickedSprite = null,
        this.thinInstanceIndex = -1,
        this.ray = null,
        this.originMesh = null,
        this.aimTransform = null,
        this.gripTransform = null
    }
    return i.prototype.getNormal = function(e, t) {
        if (e === void 0 && (e = !1),
        t === void 0 && (t = !0),
        !this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(VertexBuffer.NormalKind))
            return null;
        var r = this.pickedMesh.getIndices();
        if (!r)
            return null;
        var n;
        if (t) {
            var o = this.pickedMesh.getVerticesData(VertexBuffer.NormalKind)
              , a = Vector3.FromArray(o, r[this.faceId * 3] * 3)
              , s = Vector3.FromArray(o, r[this.faceId * 3 + 1] * 3)
              , l = Vector3.FromArray(o, r[this.faceId * 3 + 2] * 3);
            a = a.scale(this.bu),
            s = s.scale(this.bv),
            l = l.scale(1 - this.bu - this.bv),
            n = new Vector3(a.x + s.x + l.x,a.y + s.y + l.y,a.z + s.z + l.z)
        } else {
            var u = this.pickedMesh.getVerticesData(VertexBuffer.PositionKind)
              , c = Vector3.FromArray(u, r[this.faceId * 3] * 3)
              , h = Vector3.FromArray(u, r[this.faceId * 3 + 1] * 3)
              , f = Vector3.FromArray(u, r[this.faceId * 3 + 2] * 3)
              , d = c.subtract(h)
              , _ = f.subtract(h);
            n = Vector3.Cross(d, _)
        }
        if (e) {
            var g = this.pickedMesh.getWorldMatrix();
            this.pickedMesh.nonUniformScaling && (TmpVectors.Matrix[0].copyFrom(g),
            g = TmpVectors.Matrix[0],
            g.setTranslationFromFloats(0, 0, 0),
            g.invert(),
            g.transposeToRef(TmpVectors.Matrix[1]),
            g = TmpVectors.Matrix[1]),
            n = Vector3.TransformNormal(n, g)
        }
        return n.normalize(),
        n
    }
    ,
    i.prototype.getTextureCoordinates = function() {
        if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(VertexBuffer.UVKind))
            return null;
        var e = this.pickedMesh.getIndices();
        if (!e)
            return null;
        var t = this.pickedMesh.getVerticesData(VertexBuffer.UVKind);
        if (!t)
            return null;
        var r = Vector2.FromArray(t, e[this.faceId * 3] * 2)
          , n = Vector2.FromArray(t, e[this.faceId * 3 + 1] * 2)
          , o = Vector2.FromArray(t, e[this.faceId * 3 + 2] * 2);
        return r = r.scale(this.bu),
        n = n.scale(this.bv),
        o = o.scale(1 - this.bu - this.bv),
        new Vector2(r.x + n.x + o.x,r.y + n.y + o.y)
    }
    ,
    i
}(), ActionEvent = function() {
    function i(e, t, r, n, o, a) {
        this.source = e,
        this.pointerX = t,
        this.pointerY = r,
        this.meshUnderPointer = n,
        this.sourceEvent = o,
        this.additionalData = a
    }
    return i.CreateNew = function(e, t, r) {
        var n = e.getScene();
        return new i(e,n.pointerX,n.pointerY,n.meshUnderPointer || e,t,r)
    }
    ,
    i.CreateNewFromSprite = function(e, t, r, n) {
        return new i(e,t.pointerX,t.pointerY,t.meshUnderPointer,r,n)
    }
    ,
    i.CreateNewFromScene = function(e, t) {
        return new i(null,e.pointerX,e.pointerY,e.meshUnderPointer,t)
    }
    ,
    i.CreateNewFromPrimitive = function(e, t, r, n) {
        return new i(e,t.x,t.y,null,r,n)
    }
    ,
    i
}(), PostProcessManager = function() {
    function i(e) {
        this._vertexBuffers = {},
        this._scene = e
    }
    return i.prototype._prepareBuffers = function() {
        if (!this._vertexBuffers[VertexBuffer.PositionKind]) {
            var e = [];
            e.push(1, 1),
            e.push(-1, 1),
            e.push(-1, -1),
            e.push(1, -1),
            this._vertexBuffers[VertexBuffer.PositionKind] = new VertexBuffer(this._scene.getEngine(),e,VertexBuffer.PositionKind,!1,!1,2),
            this._buildIndexBuffer()
        }
    }
    ,
    i.prototype._buildIndexBuffer = function() {
        var e = [];
        e.push(0),
        e.push(1),
        e.push(2),
        e.push(0),
        e.push(2),
        e.push(3),
        this._indexBuffer = this._scene.getEngine().createIndexBuffer(e)
    }
    ,
    i.prototype._rebuild = function() {
        var e = this._vertexBuffers[VertexBuffer.PositionKind];
        !e || (e._rebuild(),
        this._buildIndexBuffer())
    }
    ,
    i.prototype._prepareFrame = function(e, t) {
        e === void 0 && (e = null),
        t === void 0 && (t = null);
        var r = this._scene.activeCamera;
        return !r || (t = t || r._postProcesses.filter(function(n) {
            return n != null
        }),
        !t || t.length === 0 || !this._scene.postProcessesEnabled) ? !1 : (t[0].activate(r, e, t != null),
        !0)
    }
    ,
    i.prototype.directRender = function(e, t, r, n, o, a) {
        var s;
        t === void 0 && (t = null),
        r === void 0 && (r = !1),
        n === void 0 && (n = 0),
        o === void 0 && (o = 0),
        a === void 0 && (a = !1);
        for (var l = this._scene.getEngine(), u = 0; u < e.length; u++) {
            u < e.length - 1 ? e[u + 1].activate(this._scene.activeCamera, t == null ? void 0 : t.texture) : (t ? l.bindFramebuffer(t, n, void 0, void 0, r, o) : a || l.restoreDefaultFramebuffer(),
            (s = l._debugInsertMarker) === null || s === void 0 || s.call(l, "post process " + e[u].name + " output"));
            var c = e[u]
              , h = c.apply();
            h && (c.onBeforeRenderObservable.notifyObservers(h),
            this._prepareBuffers(),
            l.bindBuffers(this._vertexBuffers, this._indexBuffer, h),
            l.drawElementsType(0, 0, 6),
            c.onAfterRenderObservable.notifyObservers(h))
        }
        l.setDepthBuffer(!0),
        l.setDepthWrite(!0)
    }
    ,
    i.prototype._finalizeFrame = function(e, t, r, n, o) {
        var a;
        o === void 0 && (o = !1);
        var s = this._scene.activeCamera;
        if (!!s && (n = n || s._postProcesses.filter(function(d) {
            return d != null
        }),
        !(n.length === 0 || !this._scene.postProcessesEnabled))) {
            for (var l = this._scene.getEngine(), u = 0, c = n.length; u < c; u++) {
                var h = n[u];
                if (u < c - 1 ? h._outputTexture = n[u + 1].activate(s, t == null ? void 0 : t.texture) : (t ? (l.bindFramebuffer(t, r, void 0, void 0, o),
                h._outputTexture = t) : (l.restoreDefaultFramebuffer(),
                h._outputTexture = null),
                (a = l._debugInsertMarker) === null || a === void 0 || a.call(l, "post process " + n[u].name + " output")),
                e)
                    break;
                var f = h.apply();
                f && (h.onBeforeRenderObservable.notifyObservers(f),
                this._prepareBuffers(),
                l.bindBuffers(this._vertexBuffers, this._indexBuffer, f),
                l.drawElementsType(0, 0, 6),
                h.onAfterRenderObservable.notifyObservers(f))
            }
            l.setDepthBuffer(!0),
            l.setDepthWrite(!0),
            l.setAlphaMode(0)
        }
    }
    ,
    i.prototype.dispose = function() {
        var e = this._vertexBuffers[VertexBuffer.PositionKind];
        e && (e.dispose(),
        this._vertexBuffers[VertexBuffer.PositionKind] = null),
        this._indexBuffer && (this._scene.getEngine()._releaseBuffer(this._indexBuffer),
        this._indexBuffer = null)
    }
    ,
    i
}(), RenderingGroup = function() {
    function i(e, t, r, n, o) {
        r === void 0 && (r = null),
        n === void 0 && (n = null),
        o === void 0 && (o = null),
        this.index = e,
        this._opaqueSubMeshes = new SmartArray(256),
        this._transparentSubMeshes = new SmartArray(256),
        this._alphaTestSubMeshes = new SmartArray(256),
        this._depthOnlySubMeshes = new SmartArray(256),
        this._particleSystems = new SmartArray(256),
        this._spriteManagers = new SmartArray(256),
        this._edgesRenderers = new SmartArrayNoDuplicate(16),
        this._scene = t,
        this.opaqueSortCompareFn = r,
        this.alphaTestSortCompareFn = n,
        this.transparentSortCompareFn = o
    }
    return Object.defineProperty(i.prototype, "opaqueSortCompareFn", {
        set: function(e) {
            this._opaqueSortCompareFn = e,
            e ? this._renderOpaque = this.renderOpaqueSorted : this._renderOpaque = i.renderUnsorted
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "alphaTestSortCompareFn", {
        set: function(e) {
            this._alphaTestSortCompareFn = e,
            e ? this._renderAlphaTest = this.renderAlphaTestSorted : this._renderAlphaTest = i.renderUnsorted
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "transparentSortCompareFn", {
        set: function(e) {
            e ? this._transparentSortCompareFn = e : this._transparentSortCompareFn = i.defaultTransparentSortCompare,
            this._renderTransparent = this.renderTransparentSorted
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.render = function(e, t, r, n) {
        if (e) {
            e(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
            return
        }
        var o = this._scene.getEngine();
        this._depthOnlySubMeshes.length !== 0 && (o.setColorWrite(!1),
        this._renderAlphaTest(this._depthOnlySubMeshes),
        o.setColorWrite(!0)),
        this._opaqueSubMeshes.length !== 0 && this._renderOpaque(this._opaqueSubMeshes),
        this._alphaTestSubMeshes.length !== 0 && this._renderAlphaTest(this._alphaTestSubMeshes);
        var a = o.getStencilBuffer();
        if (o.setStencilBuffer(!1),
        t && this._renderSprites(),
        r && this._renderParticles(n),
        this.onBeforeTransparentRendering && this.onBeforeTransparentRendering(),
        (this._transparentSubMeshes.length !== 0 || this._scene.useOrderIndependentTransparency) && (o.setStencilBuffer(a),
        this._scene.useOrderIndependentTransparency ? this._scene.depthPeelingRenderer.render(this._transparentSubMeshes) : this._renderTransparent(this._transparentSubMeshes),
        o.setAlphaMode(0)),
        o.setStencilBuffer(!1),
        this._edgesRenderers.length) {
            for (var s = 0; s < this._edgesRenderers.length; s++)
                this._edgesRenderers.data[s].render();
            o.setAlphaMode(0)
        }
        o.setStencilBuffer(a)
    }
    ,
    i.prototype.renderOpaqueSorted = function(e) {
        return i.renderSorted(e, this._opaqueSortCompareFn, this._scene.activeCamera, !1)
    }
    ,
    i.prototype.renderAlphaTestSorted = function(e) {
        return i.renderSorted(e, this._alphaTestSortCompareFn, this._scene.activeCamera, !1)
    }
    ,
    i.prototype.renderTransparentSorted = function(e) {
        return i.renderSorted(e, this._transparentSortCompareFn, this._scene.activeCamera, !0)
    }
    ,
    i.renderSorted = function(e, t, r, n) {
        for (var o = 0, a, s = r ? r.globalPosition : i._zeroVector; o < e.length; o++)
            a = e.data[o],
            a._alphaIndex = a.getMesh().alphaIndex,
            a._distanceToCamera = Vector3.Distance(a.getBoundingInfo().boundingSphere.centerWorld, s);
        var l = e.data.slice(0, e.length);
        for (t && l.sort(t),
        o = 0; o < l.length; o++) {
            if (a = l[o],
            n) {
                var u = a.getMaterial();
                if (u && u.needDepthPrePass) {
                    var c = u.getScene().getEngine();
                    c.setColorWrite(!1),
                    c.setAlphaMode(0),
                    a.render(!1),
                    c.setColorWrite(!0)
                }
            }
            a.render(n)
        }
    }
    ,
    i.renderUnsorted = function(e) {
        for (var t = 0; t < e.length; t++) {
            var r = e.data[t];
            r.render(!1)
        }
    }
    ,
    i.defaultTransparentSortCompare = function(e, t) {
        return e._alphaIndex > t._alphaIndex ? 1 : e._alphaIndex < t._alphaIndex ? -1 : i.backToFrontSortCompare(e, t)
    }
    ,
    i.backToFrontSortCompare = function(e, t) {
        return e._distanceToCamera < t._distanceToCamera ? 1 : e._distanceToCamera > t._distanceToCamera ? -1 : 0
    }
    ,
    i.frontToBackSortCompare = function(e, t) {
        return e._distanceToCamera < t._distanceToCamera ? -1 : e._distanceToCamera > t._distanceToCamera ? 1 : 0
    }
    ,
    i.prototype.prepare = function() {
        this._opaqueSubMeshes.reset(),
        this._transparentSubMeshes.reset(),
        this._alphaTestSubMeshes.reset(),
        this._depthOnlySubMeshes.reset(),
        this._particleSystems.reset(),
        this._spriteManagers.reset(),
        this._edgesRenderers.reset()
    }
    ,
    i.prototype.dispose = function() {
        this._opaqueSubMeshes.dispose(),
        this._transparentSubMeshes.dispose(),
        this._alphaTestSubMeshes.dispose(),
        this._depthOnlySubMeshes.dispose(),
        this._particleSystems.dispose(),
        this._spriteManagers.dispose(),
        this._edgesRenderers.dispose()
    }
    ,
    i.prototype.dispatch = function(e, t, r) {
        t === void 0 && (t = e.getMesh()),
        r === void 0 && (r = e.getMaterial()),
        r != null && (r.needAlphaBlendingForMesh(t) ? this._transparentSubMeshes.push(e) : r.needAlphaTesting() ? (r.needDepthPrePass && this._depthOnlySubMeshes.push(e),
        this._alphaTestSubMeshes.push(e)) : (r.needDepthPrePass && this._depthOnlySubMeshes.push(e),
        this._opaqueSubMeshes.push(e)),
        t._renderingGroup = this,
        t._edgesRenderer && t._edgesRenderer.isEnabled && this._edgesRenderers.pushNoDuplicate(t._edgesRenderer))
    }
    ,
    i.prototype.dispatchSprites = function(e) {
        this._spriteManagers.push(e)
    }
    ,
    i.prototype.dispatchParticles = function(e) {
        this._particleSystems.push(e)
    }
    ,
    i.prototype._renderParticles = function(e) {
        if (this._particleSystems.length !== 0) {
            var t = this._scene.activeCamera;
            this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
            for (var r = 0; r < this._particleSystems.length; r++) {
                var n = this._particleSystems.data[r];
                if ((t && t.layerMask & n.layerMask) !== 0) {
                    var o = n.emitter;
                    (!o.position || !e || e.indexOf(o) !== -1) && this._scene._activeParticles.addCount(n.render(), !1)
                }
            }
            this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene)
        }
    }
    ,
    i.prototype._renderSprites = function() {
        if (!(!this._scene.spritesEnabled || this._spriteManagers.length === 0)) {
            var e = this._scene.activeCamera;
            this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
            for (var t = 0; t < this._spriteManagers.length; t++) {
                var r = this._spriteManagers.data[t];
                (e && e.layerMask & r.layerMask) !== 0 && r.render()
            }
            this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene)
        }
    }
    ,
    i._zeroVector = Vector3.Zero(),
    i
}(), RenderingGroupInfo = function() {
    function i() {}
    return i
}(), RenderingManager = function() {
    function i(e) {
        this._useSceneAutoClearSetup = !1,
        this._renderingGroups = new Array,
        this._autoClearDepthStencil = {},
        this._customOpaqueSortCompareFn = {},
        this._customAlphaTestSortCompareFn = {},
        this._customTransparentSortCompareFn = {},
        this._renderingGroupInfo = new RenderingGroupInfo,
        this._scene = e;
        for (var t = i.MIN_RENDERINGGROUPS; t < i.MAX_RENDERINGGROUPS; t++)
            this._autoClearDepthStencil[t] = {
                autoClear: !0,
                depth: !0,
                stencil: !0
            }
    }
    return i.prototype._clearDepthStencilBuffer = function(e, t) {
        e === void 0 && (e = !0),
        t === void 0 && (t = !0),
        !this._depthStencilBufferAlreadyCleaned && (this._scene.getEngine().clear(null, !1, e, t),
        this._depthStencilBufferAlreadyCleaned = !0)
    }
    ,
    i.prototype.render = function(e, t, r, n) {
        var o = this._renderingGroupInfo;
        if (o.scene = this._scene,
        o.camera = this._scene.activeCamera,
        this._scene.spriteManagers && n)
            for (var a = 0; a < this._scene.spriteManagers.length; a++) {
                var s = this._scene.spriteManagers[a];
                this.dispatchSprites(s)
            }
        for (var a = i.MIN_RENDERINGGROUPS; a < i.MAX_RENDERINGGROUPS; a++) {
            this._depthStencilBufferAlreadyCleaned = a === i.MIN_RENDERINGGROUPS;
            var l = this._renderingGroups[a];
            if (!!l) {
                var u = Math.pow(2, a);
                if (o.renderingGroupId = a,
                this._scene.onBeforeRenderingGroupObservable.notifyObservers(o, u),
                i.AUTOCLEAR) {
                    var c = this._useSceneAutoClearSetup ? this._scene.getAutoClearDepthStencilSetup(a) : this._autoClearDepthStencil[a];
                    c && c.autoClear && this._clearDepthStencilBuffer(c.depth, c.stencil)
                }
                for (var h = 0, f = this._scene._beforeRenderingGroupDrawStage; h < f.length; h++) {
                    var d = f[h];
                    d.action(a)
                }
                l.render(e, n, r, t);
                for (var _ = 0, g = this._scene._afterRenderingGroupDrawStage; _ < g.length; _++) {
                    var d = g[_];
                    d.action(a)
                }
                this._scene.onAfterRenderingGroupObservable.notifyObservers(o, u)
            }
        }
    }
    ,
    i.prototype.reset = function() {
        for (var e = i.MIN_RENDERINGGROUPS; e < i.MAX_RENDERINGGROUPS; e++) {
            var t = this._renderingGroups[e];
            t && t.prepare()
        }
    }
    ,
    i.prototype.dispose = function() {
        this.freeRenderingGroups(),
        this._renderingGroups.length = 0,
        this._renderingGroupInfo = null
    }
    ,
    i.prototype.freeRenderingGroups = function() {
        for (var e = i.MIN_RENDERINGGROUPS; e < i.MAX_RENDERINGGROUPS; e++) {
            var t = this._renderingGroups[e];
            t && t.dispose()
        }
    }
    ,
    i.prototype._prepareRenderingGroup = function(e) {
        this._renderingGroups[e] === void 0 && (this._renderingGroups[e] = new RenderingGroup(e,this._scene,this._customOpaqueSortCompareFn[e],this._customAlphaTestSortCompareFn[e],this._customTransparentSortCompareFn[e]))
    }
    ,
    i.prototype.dispatchSprites = function(e) {
        var t = e.renderingGroupId || 0;
        this._prepareRenderingGroup(t),
        this._renderingGroups[t].dispatchSprites(e)
    }
    ,
    i.prototype.dispatchParticles = function(e) {
        var t = e.renderingGroupId || 0;
        this._prepareRenderingGroup(t),
        this._renderingGroups[t].dispatchParticles(e)
    }
    ,
    i.prototype.dispatch = function(e, t, r) {
        t === void 0 && (t = e.getMesh());
        var n = t.renderingGroupId || 0;
        this._prepareRenderingGroup(n),
        this._renderingGroups[n].dispatch(e, t, r)
    }
    ,
    i.prototype.setRenderingOrder = function(e, t, r, n) {
        if (t === void 0 && (t = null),
        r === void 0 && (r = null),
        n === void 0 && (n = null),
        this._customOpaqueSortCompareFn[e] = t,
        this._customAlphaTestSortCompareFn[e] = r,
        this._customTransparentSortCompareFn[e] = n,
        this._renderingGroups[e]) {
            var o = this._renderingGroups[e];
            o.opaqueSortCompareFn = this._customOpaqueSortCompareFn[e],
            o.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[e],
            o.transparentSortCompareFn = this._customTransparentSortCompareFn[e]
        }
    }
    ,
    i.prototype.setRenderingAutoClearDepthStencil = function(e, t, r, n) {
        r === void 0 && (r = !0),
        n === void 0 && (n = !0),
        this._autoClearDepthStencil[e] = {
            autoClear: t,
            depth: r,
            stencil: n
        }
    }
    ,
    i.prototype.getAutoClearDepthStencilSetup = function(e) {
        return this._autoClearDepthStencil[e]
    }
    ,
    i.MAX_RENDERINGGROUPS = 4,
    i.MIN_RENDERINGGROUPS = 0,
    i.AUTOCLEAR = !0,
    i
}(), SceneComponentConstants = function() {
    function i() {}
    return i.NAME_EFFECTLAYER = "EffectLayer",
    i.NAME_LAYER = "Layer",
    i.NAME_LENSFLARESYSTEM = "LensFlareSystem",
    i.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer",
    i.NAME_PARTICLESYSTEM = "ParticleSystem",
    i.NAME_GAMEPAD = "Gamepad",
    i.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue",
    i.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer",
    i.NAME_PREPASSRENDERER = "PrePassRenderer",
    i.NAME_DEPTHRENDERER = "DepthRenderer",
    i.NAME_DEPTHPEELINGRENDERER = "DepthPeelingRenderer",
    i.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager",
    i.NAME_SPRITE = "Sprite",
    i.NAME_SUBSURFACE = "SubSurface",
    i.NAME_OUTLINERENDERER = "Outline",
    i.NAME_PROCEDURALTEXTURE = "ProceduralTexture",
    i.NAME_SHADOWGENERATOR = "ShadowGenerator",
    i.NAME_OCTREE = "Octree",
    i.NAME_PHYSICSENGINE = "PhysicsEngine",
    i.NAME_AUDIO = "Audio",
    i.STEP_ISREADYFORMESH_EFFECTLAYER = 0,
    i.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0,
    i.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0,
    i.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER = 0,
    i.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1,
    i.STEP_BEFORECAMERADRAW_PREPASS = 0,
    i.STEP_BEFORECAMERADRAW_EFFECTLAYER = 1,
    i.STEP_BEFORECAMERADRAW_LAYER = 2,
    i.STEP_BEFORERENDERTARGETDRAW_PREPASS = 0,
    i.STEP_BEFORERENDERTARGETDRAW_LAYER = 1,
    i.STEP_BEFORERENDERINGMESH_PREPASS = 0,
    i.STEP_BEFORERENDERINGMESH_OUTLINE = 1,
    i.STEP_AFTERRENDERINGMESH_PREPASS = 0,
    i.STEP_AFTERRENDERINGMESH_OUTLINE = 1,
    i.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0,
    i.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER = 1,
    i.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0,
    i.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1,
    i.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0,
    i.STEP_AFTERRENDERTARGETDRAW_PREPASS = 0,
    i.STEP_AFTERRENDERTARGETDRAW_LAYER = 1,
    i.STEP_AFTERCAMERADRAW_PREPASS = 0,
    i.STEP_AFTERCAMERADRAW_EFFECTLAYER = 1,
    i.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 2,
    i.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 3,
    i.STEP_AFTERCAMERADRAW_LAYER = 4,
    i.STEP_AFTERRENDER_AUDIO = 0,
    i.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 0,
    i.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1,
    i.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 2,
    i.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3,
    i.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0,
    i.STEP_BEFORECLEARSTAGE_PREPASS = 0,
    i.STEP_BEFORERENDERTARGETCLEARSTAGE_PREPASS = 0,
    i.STEP_POINTERMOVE_SPRITE = 0,
    i.STEP_POINTERDOWN_SPRITE = 0,
    i.STEP_POINTERUP_SPRITE = 0,
    i
}(), Stage = function(i) {
    __extends(e, i);
    function e(t) {
        return i.apply(this, t) || this
    }
    return e.Create = function() {
        return Object.create(e.prototype)
    }
    ,
    e.prototype.registerStep = function(t, r, n) {
        for (var o = 0, a = Number.MAX_VALUE; o < this.length; o++) {
            var s = this[o];
            if (a = s.index,
            t < a)
                break
        }
        this.splice(o, 0, {
            index: t,
            component: r,
            action: n.bind(r)
        })
    }
    ,
    e.prototype.clear = function() {
        this.length = 0
    }
    ,
    e
}(Array), PointerEventTypes = function() {
    function i() {}
    return i.POINTERDOWN = 1,
    i.POINTERUP = 2,
    i.POINTERMOVE = 4,
    i.POINTERWHEEL = 8,
    i.POINTERPICK = 16,
    i.POINTERTAP = 32,
    i.POINTERDOUBLETAP = 64,
    i
}(), PointerInfoBase = function() {
    function i(e, t) {
        this.type = e,
        this.event = t
    }
    return i
}(), PointerInfoPre = function(i) {
    __extends(e, i);
    function e(t, r, n, o) {
        var a = i.call(this, t, r) || this;
        return a.ray = null,
        a.skipOnPointerObservable = !1,
        a.localPosition = new Vector2(n,o),
        a
    }
    return e
}(PointerInfoBase), PointerInfo = function(i) {
    __extends(e, i);
    function e(t, r, n) {
        var o = i.call(this, t, r) || this;
        return o.pickInfo = n,
        o
    }
    return e
}(PointerInfoBase), AbstractActionManager = function() {
    function i() {
        this.hoverCursor = "",
        this.actions = new Array,
        this.isRecursive = !1
    }
    return Object.defineProperty(i, "HasTriggers", {
        get: function() {
            for (var e in i.Triggers)
                if (i.Triggers.hasOwnProperty(e))
                    return !0;
            return !1
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i, "HasPickTriggers", {
        get: function() {
            for (var e in i.Triggers)
                if (i.Triggers.hasOwnProperty(e)) {
                    var t = parseInt(e);
                    if (t >= 1 && t <= 7)
                        return !0
                }
            return !1
        },
        enumerable: !1,
        configurable: !0
    }),
    i.HasSpecificTrigger = function(e) {
        for (var t in i.Triggers)
            if (i.Triggers.hasOwnProperty(t)) {
                var r = parseInt(t);
                if (r === e)
                    return !0
            }
        return !1
    }
    ,
    i.Triggers = {},
    i
}(), KeyboardEventTypes = function() {
    function i() {}
    return i.KEYDOWN = 1,
    i.KEYUP = 2,
    i
}(), KeyboardInfo = function() {
    function i(e, t) {
        this.type = e,
        this.event = t
    }
    return i
}(), KeyboardInfoPre = function(i) {
    __extends(e, i);
    function e(t, r) {
        var n = i.call(this, t, r) || this;
        return n.type = t,
        n.event = r,
        n.skipOnPointerObservable = !1,
        n
    }
    return e
}(KeyboardInfo), DeviceType;
(function(i) {
    i[i.Generic = 0] = "Generic",
    i[i.Keyboard = 1] = "Keyboard",
    i[i.Mouse = 2] = "Mouse",
    i[i.Touch = 3] = "Touch",
    i[i.DualShock = 4] = "DualShock",
    i[i.Xbox = 5] = "Xbox",
    i[i.Switch = 6] = "Switch"
}
)(DeviceType || (DeviceType = {}));
var PointerInput;
(function(i) {
    i[i.Horizontal = 0] = "Horizontal",
    i[i.Vertical = 1] = "Vertical",
    i[i.LeftClick = 2] = "LeftClick",
    i[i.MiddleClick = 3] = "MiddleClick",
    i[i.RightClick = 4] = "RightClick",
    i[i.BrowserBack = 5] = "BrowserBack",
    i[i.BrowserForward = 6] = "BrowserForward",
    i[i.MouseWheelX = 7] = "MouseWheelX",
    i[i.MouseWheelY = 8] = "MouseWheelY",
    i[i.MouseWheelZ = 9] = "MouseWheelZ",
    i[i.DeltaHorizontal = 10] = "DeltaHorizontal",
    i[i.DeltaVertical = 11] = "DeltaVertical"
}
)(PointerInput || (PointerInput = {}));
var DualShockInput;
(function(i) {
    i[i.Cross = 0] = "Cross",
    i[i.Circle = 1] = "Circle",
    i[i.Square = 2] = "Square",
    i[i.Triangle = 3] = "Triangle",
    i[i.L1 = 4] = "L1",
    i[i.R1 = 5] = "R1",
    i[i.L2 = 6] = "L2",
    i[i.R2 = 7] = "R2",
    i[i.Share = 8] = "Share",
    i[i.Options = 9] = "Options",
    i[i.L3 = 10] = "L3",
    i[i.R3 = 11] = "R3",
    i[i.DPadUp = 12] = "DPadUp",
    i[i.DPadDown = 13] = "DPadDown",
    i[i.DPadLeft = 14] = "DPadLeft",
    i[i.DPadRight = 15] = "DPadRight",
    i[i.Home = 16] = "Home",
    i[i.TouchPad = 17] = "TouchPad",
    i[i.LStickXAxis = 18] = "LStickXAxis",
    i[i.LStickYAxis = 19] = "LStickYAxis",
    i[i.RStickXAxis = 20] = "RStickXAxis",
    i[i.RStickYAxis = 21] = "RStickYAxis"
}
)(DualShockInput || (DualShockInput = {}));
var XboxInput;
(function(i) {
    i[i.A = 0] = "A",
    i[i.B = 1] = "B",
    i[i.X = 2] = "X",
    i[i.Y = 3] = "Y",
    i[i.LB = 4] = "LB",
    i[i.RB = 5] = "RB",
    i[i.LT = 6] = "LT",
    i[i.RT = 7] = "RT",
    i[i.Back = 8] = "Back",
    i[i.Start = 9] = "Start",
    i[i.LS = 10] = "LS",
    i[i.RS = 11] = "RS",
    i[i.DPadUp = 12] = "DPadUp",
    i[i.DPadDown = 13] = "DPadDown",
    i[i.DPadLeft = 14] = "DPadLeft",
    i[i.DPadRight = 15] = "DPadRight",
    i[i.Home = 16] = "Home",
    i[i.LStickXAxis = 17] = "LStickXAxis",
    i[i.LStickYAxis = 18] = "LStickYAxis",
    i[i.RStickXAxis = 19] = "RStickXAxis",
    i[i.RStickYAxis = 20] = "RStickYAxis"
}
)(XboxInput || (XboxInput = {}));
var SwitchInput;
(function(i) {
    i[i.B = 0] = "B",
    i[i.A = 1] = "A",
    i[i.Y = 2] = "Y",
    i[i.X = 3] = "X",
    i[i.L = 4] = "L",
    i[i.R = 5] = "R",
    i[i.ZL = 6] = "ZL",
    i[i.ZR = 7] = "ZR",
    i[i.Minus = 8] = "Minus",
    i[i.Plus = 9] = "Plus",
    i[i.LS = 10] = "LS",
    i[i.RS = 11] = "RS",
    i[i.DPadUp = 12] = "DPadUp",
    i[i.DPadDown = 13] = "DPadDown",
    i[i.DPadLeft = 14] = "DPadLeft",
    i[i.DPadRight = 15] = "DPadRight",
    i[i.Home = 16] = "Home",
    i[i.Capture = 17] = "Capture",
    i[i.LStickXAxis = 18] = "LStickXAxis",
    i[i.LStickYAxis = 19] = "LStickYAxis",
    i[i.RStickXAxis = 20] = "RStickXAxis",
    i[i.RStickYAxis = 21] = "RStickYAxis"
}
)(SwitchInput || (SwitchInput = {}));
var DeviceInputEventType;
(function(i) {
    i[i.PointerMove = 0] = "PointerMove",
    i[i.PointerDown = 1] = "PointerDown",
    i[i.PointerUp = 2] = "PointerUp"
}
)(DeviceInputEventType || (DeviceInputEventType = {}));
var EventConstants = function() {
    function i() {}
    return i.DOM_DELTA_PIXEL = 0,
    i.DOM_DELTA_LINE = 1,
    i.DOM_DELTA_PAGE = 2,
    i
}()
  , DeviceEventFactory = function() {
    function i() {}
    return i.CreateDeviceEvent = function(e, t, r, n, o, a) {
        switch (e) {
        case DeviceType.Keyboard:
            return this._createKeyboardEvent(r, n, o, a);
        case DeviceType.Mouse:
            if (r === PointerInput.MouseWheelX || r === PointerInput.MouseWheelY || r === PointerInput.MouseWheelZ)
                return this._createWheelEvent(e, t, r, n, o, a);
        case DeviceType.Touch:
            return this._createPointerEvent(e, t, r, n, o, a);
        default:
            throw "Unable to generate event for device " + DeviceType[e]
        }
    }
    ,
    i._createPointerEvent = function(e, t, r, n, o, a) {
        var s = this._createMouseEvent(e, t, r, n, o, a);
        return s.pointerId = e === DeviceType.Mouse ? 1 : t,
        r === PointerInput.Horizontal || r === PointerInput.Vertical || r === PointerInput.DeltaHorizontal || r === PointerInput.DeltaVertical ? s.type = "pointermove" : r >= PointerInput.LeftClick && r <= PointerInput.RightClick && (s.type = n === 1 ? "pointerdown" : "pointerup",
        s.button = r - 2),
        s
    }
    ,
    i._createWheelEvent = function(e, t, r, n, o, a) {
        var s = this._createMouseEvent(e, t, r, n, o, a);
        return s.type = "wheel",
        s.deltaMode = EventConstants.DOM_DELTA_PIXEL,
        s.deltaX = r === PointerInput.MouseWheelX ? n : o.pollInput(e, t, PointerInput.MouseWheelX),
        s.deltaY = r === PointerInput.MouseWheelY ? n : o.pollInput(e, t, PointerInput.MouseWheelY),
        s.deltaZ = r === PointerInput.MouseWheelZ ? n : o.pollInput(e, t, PointerInput.MouseWheelZ),
        s
    }
    ,
    i._createMouseEvent = function(e, t, r, n, o, a) {
        var s = this._createEvent(a)
          , l = o.pollInput(e, t, PointerInput.Horizontal)
          , u = o.pollInput(e, t, PointerInput.Vertical)
          , c = r === PointerInput.DeltaHorizontal ? n : 0
          , h = r === PointerInput.DeltaVertical ? n : 0
          , f = r === PointerInput.DeltaHorizontal && a ? c - a.getBoundingClientRect().x : 0
          , d = r === PointerInput.DeltaVertical && a ? h - a.getBoundingClientRect().y : 0;
        return this._checkNonCharacterKeys(s, o),
        s.clientX = l,
        s.clientY = u,
        s.movementX = c,
        s.movementY = h,
        s.offsetX = f,
        s.offsetY = d,
        s.x = l,
        s.y = u,
        s
    }
    ,
    i._createKeyboardEvent = function(e, t, r, n) {
        var o = this._createEvent(n);
        return this._checkNonCharacterKeys(o, r),
        o.type = t === 1 ? "keydown" : "keyup",
        o.key = String.fromCharCode(e),
        o.keyCode = e,
        o
    }
    ,
    i._checkNonCharacterKeys = function(e, t) {
        var r = t.isDeviceAvailable(DeviceType.Keyboard)
          , n = r && t.pollInput(DeviceType.Keyboard, 0, 18) === 1
          , o = r && t.pollInput(DeviceType.Keyboard, 0, 17) === 1
          , a = r && (t.pollInput(DeviceType.Keyboard, 0, 91) === 1 || t.pollInput(DeviceType.Keyboard, 0, 92) === 1 || t.pollInput(DeviceType.Keyboard, 0, 93) === 1)
          , s = r && t.pollInput(DeviceType.Keyboard, 0, 16) === 1;
        e.altKey = n,
        e.ctrlKey = o,
        e.metaKey = a,
        e.shiftKey = s
    }
    ,
    i._createEvent = function(e) {
        var t = {};
        return t.preventDefault = function() {}
        ,
        t.target = e,
        t
    }
    ,
    i
}()
  , NativeDeviceInputSystemImpl = function() {
    function i(e) {
        var t = this;
        this.onDeviceConnected = function(r, n) {}
        ,
        this.onDeviceDisconnected = function(r, n) {}
        ,
        this.onInputChanged = function(r) {}
        ,
        this._nativeInput = e || this._createDummyNativeInput(),
        this._nativeInput.onDeviceConnected = function(r, n) {
            t.onDeviceConnected(r, n)
        }
        ,
        this._nativeInput.onDeviceDisconnected = function(r, n) {
            t.onDeviceDisconnected(r, n)
        }
        ,
        this._nativeInput.onInputChanged = function(r, n, o, a, s, l) {
            var u = DeviceEventFactory.CreateDeviceEvent(r, n, o, s, t)
              , c = u;
            c.deviceType = r,
            c.deviceSlot = n,
            c.inputIndex = o,
            c.previousState = a,
            c.currentState = s,
            t.onInputChanged(c)
        }
    }
    return i.prototype.configureEvents = function() {}
    ,
    i.prototype.pollInput = function(e, t, r) {
        return this._nativeInput.pollInput(e, t, r)
    }
    ,
    i.prototype.isDeviceAvailable = function(e) {
        return e === DeviceType.Mouse || e === DeviceType.Touch
    }
    ,
    i.prototype.dispose = function() {
        this.onDeviceConnected = function() {}
        ,
        this.onDeviceDisconnected = function() {}
        ,
        this.onInputChanged = function() {}
    }
    ,
    i.prototype._createDummyNativeInput = function() {
        var e = {
            onDeviceConnected: function(t, r) {},
            onDeviceDisconnected: function(t, r) {},
            onInputChanged: function(t, r, n, o, a, s) {},
            pollInput: function() {
                return 0
            },
            isDeviceAvailable: function() {
                return !1
            },
            dispose: function() {}
        };
        return e
    }
    ,
    i
}()
  , WebDeviceInputSystemImpl = function() {
    function i(e) {
        this._inputs = [],
        this._keyboardActive = !1,
        this._pointerActive = !1,
        this._usingSafari = Tools.IsSafari(),
        this._keyboardDownEvent = function(t) {}
        ,
        this._keyboardUpEvent = function(t) {}
        ,
        this._keyboardBlurEvent = function(t) {}
        ,
        this._pointerMoveEvent = function(t) {}
        ,
        this._pointerDownEvent = function(t) {}
        ,
        this._pointerUpEvent = function(t) {}
        ,
        this._pointerWheelEvent = function(t) {}
        ,
        this._pointerBlurEvent = function(t) {}
        ,
        this._mouseId = -1,
        this._isUsingFirefox = navigator && navigator.userAgent && navigator.userAgent.indexOf("Firefox") !== -1,
        this._activeTouchIds = [],
        this._rollingTouchId = 0,
        this._pointerInputClearObserver = null,
        this._gamepadConnectedEvent = function(t) {}
        ,
        this._gamepadDisconnectedEvent = function(t) {}
        ,
        this._eventPrefix = Tools.GetPointerPrefix(e),
        this._engine = e,
        this.onDeviceConnected = function(t, r) {}
        ,
        this.onDeviceDisconnected = function(t, r) {}
        ,
        this.onInputChanged = function(t) {}
        ,
        this.configureEvents()
    }
    return Object.defineProperty(i.prototype, "onDeviceConnected", {
        get: function() {
            return this._onDeviceConnected
        },
        set: function(e) {
            this._onDeviceConnected = e;
            for (var t = 0; t < this._inputs.length; t++) {
                var r = this._inputs[t];
                if (r)
                    for (var n in r) {
                        var o = +n;
                        this._inputs[t][o] && this._onDeviceConnected(t, o)
                    }
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.configureEvents = function() {
        var e = this._engine.getInputElement();
        e && this._elementToAttachTo !== e && (this._elementToAttachTo && this._removeEvents(),
        this._elementToAttachTo = e,
        this._elementToAttachTo.tabIndex = this._elementToAttachTo.tabIndex !== -1 ? this._elementToAttachTo.tabIndex : this._engine.canvasTabIndex,
        this._handleKeyActions(),
        this._handlePointerActions(),
        this._handleGamepadActions(),
        this._checkForConnectedDevices())
    }
    ,
    i.prototype.pollInput = function(e, t, r) {
        var n = this._inputs[e][t];
        if (!n)
            throw "Unable to find device " + DeviceType[e];
        e >= DeviceType.Xbox && e <= DeviceType.Switch && navigator.getGamepads && this._updateDevice(e, t, r);
        var o = n[r];
        if (o === void 0)
            throw "Unable to find input " + r + " for device " + DeviceType[e] + " in slot " + t;
        return o
    }
    ,
    i.prototype.isDeviceAvailable = function(e) {
        return this._inputs[e] !== void 0
    }
    ,
    i.prototype.dispose = function() {
        this.onDeviceConnected = function() {}
        ,
        this.onDeviceDisconnected = function() {}
        ,
        this.onInputChanged = function() {}
        ,
        this._elementToAttachTo && (this._removeEvents(),
        window.removeEventListener("gamepadconnected", this._gamepadConnectedEvent),
        window.removeEventListener("gamepaddisconnected", this._gamepadDisconnectedEvent))
    }
    ,
    i.prototype._checkForConnectedDevices = function() {
        if (navigator.getGamepads)
            for (var e = navigator.getGamepads(), t = 0, r = e; t < r.length; t++) {
                var n = r[t];
                n && this._addGamePad(n)
            }
        matchMedia("(pointer:fine)").matches && this._addPointerDevice(DeviceType.Mouse, 0, 0, 0)
    }
    ,
    i.prototype._addGamePad = function(e) {
        var t = this._getGamepadDeviceType(e.id)
          , r = e.index;
        this._registerDevice(t, r, e.buttons.length + e.axes.length),
        this._gamepads = this._gamepads || new Array(e.index + 1),
        this._gamepads[r] = t
    }
    ,
    i.prototype._addPointerDevice = function(e, t, r, n) {
        this._pointerActive = !0,
        this._registerDevice(e, t, i.MAX_POINTER_INPUTS);
        var o = this._inputs[e][t];
        o[0] = r,
        o[1] = n
    }
    ,
    i.prototype._registerDevice = function(e, t, r) {
        if (t === void 0)
            throw "Unable to register device " + DeviceType[e] + " to undefined slot.";
        if (this._inputs[e] || (this._inputs[e] = {}),
        !this._inputs[e][t]) {
            for (var n = new Array(r), o = 0; o < r; o++)
                n[o] = 0;
            this._inputs[e][t] = n,
            this.onDeviceConnected(e, t)
        }
    }
    ,
    i.prototype._unregisterDevice = function(e, t) {
        this._inputs[e][t] && (delete this._inputs[e][t],
        this.onDeviceDisconnected(e, t))
    }
    ,
    i.prototype._handleKeyActions = function() {
        var e = this;
        this._keyboardDownEvent = function(t) {
            e._keyboardActive || (e._keyboardActive = !0,
            e._registerDevice(DeviceType.Keyboard, 0, i.MAX_KEYCODES));
            var r = e._inputs[DeviceType.Keyboard][0];
            if (r) {
                r[t.keyCode] = 1;
                var n = t;
                n.deviceType = DeviceType.Keyboard,
                n.deviceSlot = 0,
                n.inputIndex = t.keyCode,
                n.previousState = 0,
                n.currentState = r[t.keyCode],
                e.onInputChanged(n)
            }
        }
        ,
        this._keyboardUpEvent = function(t) {
            e._keyboardActive || (e._keyboardActive = !0,
            e._registerDevice(DeviceType.Keyboard, 0, i.MAX_KEYCODES));
            var r = e._inputs[DeviceType.Keyboard][0];
            if (r) {
                r[t.keyCode] = 0;
                var n = t;
                n.deviceType = DeviceType.Keyboard,
                n.deviceSlot = 0,
                n.inputIndex = t.keyCode,
                n.previousState = 1,
                n.currentState = r[t.keyCode],
                e.onInputChanged(n)
            }
        }
        ,
        this._keyboardBlurEvent = function(t) {
            if (e._keyboardActive) {
                for (var r = e._inputs[DeviceType.Keyboard][0], n = 0; n < r.length; n++)
                    if (r[n] !== 0) {
                        r[n] = 0;
                        var o = DeviceEventFactory.CreateDeviceEvent(DeviceType.Keyboard, 0, n, 1, e, e._elementToAttachTo)
                          , a = o;
                        a.deviceType = DeviceType.Keyboard,
                        a.deviceSlot = 0,
                        a.inputIndex = n,
                        a.currentState = 0,
                        a.previousState = 1,
                        e.onInputChanged(a)
                    }
            }
        }
        ,
        this._elementToAttachTo.addEventListener("keydown", this._keyboardDownEvent),
        this._elementToAttachTo.addEventListener("keyup", this._keyboardUpEvent),
        this._elementToAttachTo.addEventListener("blur", this._keyboardBlurEvent)
    }
    ,
    i.prototype._handlePointerActions = function() {
        var e = this;
        this._pointerMoveEvent = function(o) {
            var a = e._getPointerType(o)
              , s = a === DeviceType.Mouse ? 0 : e._activeTouchIds.indexOf(o.pointerId);
            e._inputs[a] || (e._inputs[a] = {}),
            e._inputs[a][s] || e._addPointerDevice(a, s, o.clientX, o.clientY);
            var l = e._inputs[a][s];
            if (l) {
                var u = l[PointerInput.Horizontal]
                  , c = l[PointerInput.Vertical]
                  , h = l[PointerInput.DeltaHorizontal]
                  , f = l[PointerInput.DeltaVertical];
                l[PointerInput.Horizontal] = o.clientX,
                l[PointerInput.Vertical] = o.clientY,
                l[PointerInput.DeltaHorizontal] = o.movementX,
                l[PointerInput.DeltaVertical] = o.movementY;
                var d = o;
                d.deviceType = a,
                d.deviceSlot = s,
                u !== o.clientX && (d.inputIndex = PointerInput.Horizontal,
                d.previousState = u,
                d.currentState = l[PointerInput.Horizontal],
                e.onInputChanged(d)),
                c !== o.clientY && (d.inputIndex = PointerInput.Vertical,
                d.previousState = c,
                d.currentState = l[PointerInput.Vertical],
                e.onInputChanged(d)),
                l[PointerInput.DeltaHorizontal] !== 0 && (d.inputIndex = PointerInput.DeltaHorizontal,
                d.previousState = h,
                d.currentState = l[PointerInput.DeltaHorizontal],
                e.onInputChanged(d)),
                l[PointerInput.DeltaVertical] !== 0 && (d.inputIndex = PointerInput.DeltaVertical,
                d.previousState = f,
                d.currentState = l[PointerInput.DeltaVertical],
                e.onInputChanged(d)),
                !e._usingSafari && o.button !== -1 && (d.inputIndex = o.button + 2,
                d.previousState = l[o.button + 2],
                l[o.button + 2] = l[o.button + 2] ? 0 : 1,
                d.currentState = l[o.button + 2],
                e.onInputChanged(d))
            }
        }
        ,
        this._pointerDownEvent = function(o) {
            var a = e._getPointerType(o)
              , s = a === DeviceType.Mouse ? 0 : o.pointerId;
            a === DeviceType.Touch && (s = e._rollingTouchId++,
            e._activeTouchIds[s] = o.pointerId),
            e._inputs[a] || (e._inputs[a] = {}),
            e._inputs[a][s] || e._addPointerDevice(a, s, o.clientX, o.clientY);
            var l = e._inputs[a][s];
            if (l) {
                var u = l[PointerInput.Horizontal]
                  , c = l[PointerInput.Vertical]
                  , h = l[o.button + 2];
                if (a === DeviceType.Mouse) {
                    if (e._mouseId === -1 && (o.pointerId === void 0 ? e._mouseId = e._isUsingFirefox ? 0 : 1 : e._mouseId = o.pointerId),
                    !document.pointerLockElement && e._elementToAttachTo.hasPointerCapture)
                        try {
                            e._elementToAttachTo.setPointerCapture(e._mouseId)
                        } catch {}
                } else if (o.pointerId && !document.pointerLockElement && e._elementToAttachTo.hasPointerCapture)
                    try {
                        e._elementToAttachTo.setPointerCapture(o.pointerId)
                    } catch {}
                l[PointerInput.Horizontal] = o.clientX,
                l[PointerInput.Vertical] = o.clientY,
                l[o.button + 2] = 1;
                var f = o;
                f.deviceType = a,
                f.deviceSlot = s,
                u !== o.clientX && (f.inputIndex = PointerInput.Horizontal,
                f.previousState = u,
                f.currentState = l[PointerInput.Horizontal],
                e.onInputChanged(f)),
                c !== o.clientY && (f.inputIndex = PointerInput.Vertical,
                f.previousState = c,
                f.currentState = l[PointerInput.Vertical],
                e.onInputChanged(f)),
                f.inputIndex = o.button + 2,
                f.previousState = h,
                f.currentState = l[o.button + 2],
                e.onInputChanged(f)
            }
        }
        ,
        this._pointerUpEvent = function(o) {
            var a, s, l, u, c, h = e._getPointerType(o), f = h === DeviceType.Mouse ? 0 : e._activeTouchIds.indexOf(o.pointerId), d = (a = e._inputs[h]) === null || a === void 0 ? void 0 : a[f];
            if (d && d[o.button + 2] !== 0) {
                var _ = d[PointerInput.Horizontal]
                  , g = d[PointerInput.Vertical]
                  , m = d[o.button + 2];
                d[PointerInput.Horizontal] = o.clientX,
                d[PointerInput.Vertical] = o.clientY,
                d[o.button + 2] = 0;
                var v = o;
                if (v.deviceType = h,
                v.deviceSlot = f,
                _ !== o.clientX && (v.inputIndex = PointerInput.Horizontal,
                v.previousState = _,
                v.currentState = d[PointerInput.Horizontal],
                e.onInputChanged(v)),
                g !== o.clientY && (v.inputIndex = PointerInput.Vertical,
                v.previousState = g,
                v.currentState = d[PointerInput.Vertical],
                e.onInputChanged(v)),
                v.inputIndex = o.button + 2,
                v.previousState = m,
                v.currentState = d[o.button + 2],
                h === DeviceType.Mouse && e._mouseId >= 0 && ((l = (s = e._elementToAttachTo).hasPointerCapture) === null || l === void 0 ? void 0 : l.call(s, e._mouseId)) ? e._elementToAttachTo.releasePointerCapture(e._mouseId) : o.pointerId && ((c = (u = e._elementToAttachTo).hasPointerCapture) === null || c === void 0 ? void 0 : c.call(u, o.pointerId)) && e._elementToAttachTo.releasePointerCapture(o.pointerId),
                e.onInputChanged(v),
                h !== DeviceType.Mouse) {
                    var y = e._activeTouchIds.indexOf(o.pointerId);
                    delete e._activeTouchIds[y],
                    e._unregisterDevice(h, f)
                }
            }
        }
        ,
        this._wheelEventName = "onwheel"in document.createElement("div") ? "wheel" : document.onmousewheel !== void 0 ? "mousewheel" : "DOMMouseScroll";
        var t = !1
          , r = function() {};
        try {
            var n = {
                passive: {
                    get: function() {
                        t = !0
                    }
                }
            };
            this._elementToAttachTo.addEventListener("test", r, n),
            this._elementToAttachTo.removeEventListener("test", r, n)
        } catch {}
        this._pointerBlurEvent = function(o) {
            var a, s, l, u, c;
            if (e.isDeviceAvailable(DeviceType.Mouse)) {
                var h = e._inputs[DeviceType.Mouse][0];
                e._mouseId >= 0 && ((s = (a = e._elementToAttachTo).hasPointerCapture) === null || s === void 0 ? void 0 : s.call(a, e._mouseId)) && e._elementToAttachTo.releasePointerCapture(e._mouseId);
                for (var f = 0; f <= PointerInput.BrowserForward; f++)
                    if (h[f + 2] === 1) {
                        h[f + 2] = 0;
                        var d = DeviceEventFactory.CreateDeviceEvent(DeviceType.Mouse, 0, f + 2, 1, e, e._elementToAttachTo)
                          , _ = d;
                        _.deviceType = DeviceType.Mouse,
                        _.deviceSlot = 0,
                        _.inputIndex = f + 2,
                        _.currentState = h[f + 2],
                        _.previousState = 1,
                        e.onInputChanged(_)
                    }
            }
            if (e.isDeviceAvailable(DeviceType.Touch)) {
                var h = e._inputs[DeviceType.Touch];
                for (var g in Object.keys(e._activeTouchIds)) {
                    var m = +g
                      , v = e._activeTouchIds[m];
                    if (!((u = (l = e._elementToAttachTo).hasPointerCapture) === null || u === void 0) && u.call(l, v) && e._elementToAttachTo.releasePointerCapture(v),
                    ((c = h[m]) === null || c === void 0 ? void 0 : c[PointerInput.LeftClick]) === 1) {
                        h[m][PointerInput.LeftClick] = 0;
                        var y = DeviceEventFactory.CreateDeviceEvent(DeviceType.Touch, v, PointerInput.LeftClick, 1, e, e._elementToAttachTo)
                          , _ = y;
                        _.deviceType = DeviceType.Mouse,
                        _.deviceSlot = m,
                        _.inputIndex = PointerInput.LeftClick,
                        _.currentState = h[m][PointerInput.LeftClick],
                        _.previousState = 1,
                        e.onInputChanged(_),
                        e._unregisterDevice(DeviceType.Touch, m)
                    }
                }
                for (; e._activeTouchIds.pop() !== void 0; )
                    ;
            }
        }
        ,
        this._pointerWheelEvent = function(o) {
            var a = DeviceType.Mouse
              , s = 0;
            e._inputs[a] || (e._inputs[a] = []),
            e._inputs[a][s] || (e._pointerActive = !0,
            e._registerDevice(a, s, i.MAX_POINTER_INPUTS));
            var l = e._inputs[a][s];
            if (l) {
                var u = l[PointerInput.MouseWheelX]
                  , c = l[PointerInput.MouseWheelY]
                  , h = l[PointerInput.MouseWheelZ];
                l[PointerInput.MouseWheelX] = o.deltaX || 0,
                l[PointerInput.MouseWheelY] = o.deltaY || o.wheelDelta || 0,
                l[PointerInput.MouseWheelZ] = o.deltaZ || 0;
                var f = o;
                f.deviceType = a,
                f.deviceSlot = s,
                l[PointerInput.MouseWheelX] !== 0 && (f.inputIndex = PointerInput.MouseWheelX,
                f.previousState = u,
                f.currentState = l[PointerInput.MouseWheelX],
                e.onInputChanged(f)),
                l[PointerInput.MouseWheelY] !== 0 && (f.inputIndex = PointerInput.MouseWheelY,
                f.previousState = c,
                f.currentState = l[PointerInput.MouseWheelY],
                e.onInputChanged(f)),
                l[PointerInput.MouseWheelZ] !== 0 && (f.inputIndex = PointerInput.MouseWheelZ,
                f.previousState = h,
                f.currentState = l[PointerInput.MouseWheelZ],
                e.onInputChanged(f))
            }
        }
        ,
        this._elementToAttachTo.addEventListener(this._eventPrefix + "move", this._pointerMoveEvent),
        this._elementToAttachTo.addEventListener(this._eventPrefix + "down", this._pointerDownEvent),
        this._elementToAttachTo.addEventListener(this._eventPrefix + "up", this._pointerUpEvent),
        this._elementToAttachTo.addEventListener("blur", this._pointerBlurEvent),
        this._elementToAttachTo.addEventListener(this._wheelEventName, this._pointerWheelEvent, t ? {
            passive: !1
        } : !1),
        this._pointerInputClearObserver = this._engine.onEndFrameObservable.add(function() {
            if (e.isDeviceAvailable(DeviceType.Mouse)) {
                var o = e._inputs[DeviceType.Mouse][0];
                o[PointerInput.MouseWheelX] = 0,
                o[PointerInput.MouseWheelY] = 0,
                o[PointerInput.MouseWheelZ] = 0,
                o[PointerInput.DeltaHorizontal] = 0,
                o[PointerInput.DeltaVertical] = 0
            }
        })
    }
    ,
    i.prototype._handleGamepadActions = function() {
        var e = this;
        this._gamepadConnectedEvent = function(t) {
            e._addGamePad(t.gamepad)
        }
        ,
        this._gamepadDisconnectedEvent = function(t) {
            if (e._gamepads) {
                var r = e._getGamepadDeviceType(t.gamepad.id)
                  , n = t.gamepad.index;
                e._unregisterDevice(r, n),
                delete e._gamepads[n]
            }
        }
        ,
        window.addEventListener("gamepadconnected", this._gamepadConnectedEvent),
        window.addEventListener("gamepaddisconnected", this._gamepadDisconnectedEvent)
    }
    ,
    i.prototype._updateDevice = function(e, t, r) {
        var n = navigator.getGamepads()[t];
        if (n && e === this._gamepads[t]) {
            var o = this._inputs[e][t];
            r >= n.buttons.length ? o[r] = n.axes[r - n.buttons.length].valueOf() : o[r] = n.buttons[r].value
        }
    }
    ,
    i.prototype._getGamepadDeviceType = function(e) {
        return e.indexOf("054c") !== -1 && e.indexOf("0ce6") === -1 ? DeviceType.DualShock : e.indexOf("Xbox One") !== -1 || e.search("Xbox 360") !== -1 || e.search("xinput") !== -1 ? DeviceType.Xbox : e.indexOf("057e") !== -1 ? DeviceType.Switch : DeviceType.Generic
    }
    ,
    i.prototype._getPointerType = function(e) {
        var t = DeviceType.Mouse;
        return (e.pointerType === "touch" || e.pointerType === "pen" || e.touches) && (t = DeviceType.Touch),
        t
    }
    ,
    i.prototype._removeEvents = function() {
        this._elementToAttachTo.removeEventListener("blur", this._keyboardBlurEvent),
        this._elementToAttachTo.removeEventListener("blur", this._pointerBlurEvent),
        this._keyboardActive && (this._elementToAttachTo.removeEventListener("keydown", this._keyboardDownEvent),
        this._elementToAttachTo.removeEventListener("keyup", this._keyboardUpEvent)),
        this._pointerActive && (this._elementToAttachTo.removeEventListener(this._eventPrefix + "move", this._pointerMoveEvent),
        this._elementToAttachTo.removeEventListener(this._eventPrefix + "down", this._pointerDownEvent),
        this._elementToAttachTo.removeEventListener(this._eventPrefix + "up", this._pointerUpEvent),
        this._elementToAttachTo.removeEventListener(this._wheelEventName, this._pointerWheelEvent),
        this._pointerInputClearObserver && this._engine.onEndFrameObservable.remove(this._pointerInputClearObserver))
    }
    ,
    i.MAX_KEYCODES = 255,
    i.MAX_POINTER_INPUTS = Object.keys(PointerInput).length / 2,
    i
}()
  , DeviceInputSystem = function() {
    function i(e) {
        var t = this;
        this._deviceInputSystem = e,
        this.onDeviceConnectedObservable = new Observable,
        this.onDeviceDisconnectedObservable = new Observable,
        this.onInputChangedObservable = new Observable,
        this._deviceInputSystem.onDeviceConnected = function(r, n) {
            t.onDeviceConnectedObservable.notifyObservers({
                deviceType: r,
                deviceSlot: n
            })
        }
        ,
        this._deviceInputSystem.onDeviceDisconnected = function(r, n) {
            t.onDeviceDisconnectedObservable.notifyObservers({
                deviceType: r,
                deviceSlot: n
            })
        }
        ,
        this._deviceInputSystem.onInputChanged = function(r) {
            t.onInputChangedObservable.notifyObservers(r)
        }
    }
    return i._Create = function(e) {
        if (!e.deviceInputSystem) {
            var t = void 0;
            typeof _native != "undefined" ? t = _native.DeviceInputSystem ? new NativeDeviceInputSystemImpl(new _native.DeviceInputSystem) : new NativeDeviceInputSystemImpl : t = new WebDeviceInputSystemImpl(e),
            t && (e.deviceInputSystem = new i(t))
        }
        return e.deviceInputSystem
    }
    ,
    i.prototype.configureEvents = function() {
        this._deviceInputSystem.configureEvents()
    }
    ,
    i.prototype.pollInput = function(e, t, r) {
        return this._deviceInputSystem.pollInput(e, t, r)
    }
    ,
    i.prototype.isDeviceAvailable = function(e) {
        return this._deviceInputSystem.isDeviceAvailable(e)
    }
    ,
    i.prototype.dispose = function() {
        this.onDeviceConnectedObservable.clear(),
        this.onDeviceDisconnectedObservable.clear(),
        this.onInputChangedObservable.clear(),
        this._deviceInputSystem.dispose()
    }
    ,
    i
}()
  , _ClickInfo = function() {
    function i() {
        this._singleClick = !1,
        this._doubleClick = !1,
        this._hasSwiped = !1,
        this._ignore = !1
    }
    return Object.defineProperty(i.prototype, "singleClick", {
        get: function() {
            return this._singleClick
        },
        set: function(e) {
            this._singleClick = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "doubleClick", {
        get: function() {
            return this._doubleClick
        },
        set: function(e) {
            this._doubleClick = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "hasSwiped", {
        get: function() {
            return this._hasSwiped
        },
        set: function(e) {
            this._hasSwiped = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "ignore", {
        get: function() {
            return this._ignore
        },
        set: function(e) {
            this._ignore = e
        },
        enumerable: !1,
        configurable: !0
    }),
    i
}()
  , InputManager = function() {
    function i(e) {
        this._alreadyAttached = !1,
        this._meshPickProceed = !1,
        this._currentPickResult = null,
        this._previousPickResult = null,
        this._totalPointersPressed = 0,
        this._doubleClickOccured = !1,
        this._pointerX = 0,
        this._pointerY = 0,
        this._startingPointerPosition = new Vector2(0,0),
        this._previousStartingPointerPosition = new Vector2(0,0),
        this._startingPointerTime = 0,
        this._previousStartingPointerTime = 0,
        this._pointerCaptures = {},
        this._meshUnderPointerId = {},
        this._scene = e
    }
    return Object.defineProperty(i.prototype, "meshUnderPointer", {
        get: function() {
            return this._pointerOverMesh
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.getMeshUnderPointerByPointerId = function(e) {
        return this._meshUnderPointerId[e] || null
    }
    ,
    Object.defineProperty(i.prototype, "unTranslatedPointer", {
        get: function() {
            return new Vector2(this._unTranslatedPointerX,this._unTranslatedPointerY)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "pointerX", {
        get: function() {
            return this._pointerX
        },
        set: function(e) {
            this._pointerX = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "pointerY", {
        get: function() {
            return this._pointerY
        },
        set: function(e) {
            this._pointerY = e
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype._updatePointerPosition = function(e) {
        var t = this._scene.getEngine().getInputElementClientRect();
        !t || (this._pointerX = e.clientX - t.left,
        this._pointerY = e.clientY - t.top,
        this._unTranslatedPointerX = this._pointerX,
        this._unTranslatedPointerY = this._pointerY)
    }
    ,
    i.prototype._processPointerMove = function(e, t) {
        var r = this._scene
          , n = r.getEngine()
          , o = n.getInputElement();
        o && (o.tabIndex = n.canvasTabIndex,
        r.doNotHandleCursors || (o.style.cursor = r.defaultCursor));
        var a = !!(e && e.hit && e.pickedMesh);
        a ? (r.setPointerOverMesh(e.pickedMesh, t.pointerId, e),
        this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers && !r.doNotHandleCursors && o && (this._pointerOverMesh.actionManager.hoverCursor ? o.style.cursor = this._pointerOverMesh.actionManager.hoverCursor : o.style.cursor = r.hoverCursor)) : r.setPointerOverMesh(null, t.pointerId, e);
        for (var s = 0, l = r._pointerMoveStage; s < l.length; s++) {
            var u = l[s];
            e = u.action(this._unTranslatedPointerX, this._unTranslatedPointerY, e, a, o)
        }
        if (e) {
            var c = t.type === "wheel" || t.type === "mousewheel" || t.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
            if (r.onPointerMove && r.onPointerMove(t, e, c),
            r.onPointerObservable.hasObservers()) {
                var h = new PointerInfo(c,t,e);
                this._setRayOnPointerInfo(h),
                r.onPointerObservable.notifyObservers(h, c)
            }
        }
    }
    ,
    i.prototype._setRayOnPointerInfo = function(e) {
        var t = this._scene;
        e.pickInfo && !e.pickInfo._pickingUnavailable && (e.pickInfo.ray || (e.pickInfo.ray = t.createPickingRay(e.event.offsetX, e.event.offsetY, Matrix.Identity(), t.activeCamera)))
    }
    ,
    i.prototype._checkPrePointerObservable = function(e, t, r) {
        var n = this._scene
          , o = new PointerInfoPre(r,t,this._unTranslatedPointerX,this._unTranslatedPointerY);
        return e && (o.ray = e.ray,
        e.originMesh && (o.nearInteractionPickingInfo = e)),
        n.onPrePointerObservable.notifyObservers(o, r),
        !!o.skipOnPointerObservable
    }
    ,
    i.prototype.simulatePointerMove = function(e, t) {
        var r = new PointerEvent("pointermove",t);
        this._checkPrePointerObservable(e, r, PointerEventTypes.POINTERMOVE) || this._processPointerMove(e, r)
    }
    ,
    i.prototype.simulatePointerDown = function(e, t) {
        var r = new PointerEvent("pointerdown",t);
        this._checkPrePointerObservable(e, r, PointerEventTypes.POINTERDOWN) || this._processPointerDown(e, r)
    }
    ,
    i.prototype._processPointerDown = function(e, t) {
        var r = this
          , n = this._scene;
        if (e && e.hit && e.pickedMesh) {
            this._pickedDownMesh = e.pickedMesh;
            var o = e.pickedMesh._getActionManagerForTrigger();
            if (o) {
                if (o.hasPickTriggers)
                    switch (o.processTrigger(5, ActionEvent.CreateNew(e.pickedMesh, t)),
                    t.button) {
                    case 0:
                        o.processTrigger(2, ActionEvent.CreateNew(e.pickedMesh, t));
                        break;
                    case 1:
                        o.processTrigger(4, ActionEvent.CreateNew(e.pickedMesh, t));
                        break;
                    case 2:
                        o.processTrigger(3, ActionEvent.CreateNew(e.pickedMesh, t));
                        break
                    }
                o.hasSpecificTrigger(8) && window.setTimeout(function() {
                    var h = n.pick(r._unTranslatedPointerX, r._unTranslatedPointerY, function(f) {
                        return f.isPickable && f.isVisible && f.isReady() && f.actionManager && f.actionManager.hasSpecificTrigger(8) && f === r._pickedDownMesh
                    }, !1, n.cameraToUseForPointers);
                    h && h.hit && h.pickedMesh && o && r._totalPointersPressed !== 0 && Date.now() - r._startingPointerTime > i.LongPressDelay && !r._isPointerSwiping() && (r._startingPointerTime = 0,
                    o.processTrigger(8, ActionEvent.CreateNew(h.pickedMesh, t)))
                }, i.LongPressDelay)
            }
        } else
            for (var a = 0, s = n._pointerDownStage; a < s.length; a++) {
                var l = s[a];
                e = l.action(this._unTranslatedPointerX, this._unTranslatedPointerY, e, t)
            }
        if (e) {
            var u = PointerEventTypes.POINTERDOWN;
            if (n.onPointerDown && n.onPointerDown(t, e, u),
            n.onPointerObservable.hasObservers()) {
                var c = new PointerInfo(u,t,e);
                this._setRayOnPointerInfo(c),
                n.onPointerObservable.notifyObservers(c, u)
            }
        }
    }
    ,
    i.prototype._isPointerSwiping = function() {
        return Math.abs(this._startingPointerPosition.x - this._pointerX) > i.DragMovementThreshold || Math.abs(this._startingPointerPosition.y - this._pointerY) > i.DragMovementThreshold
    }
    ,
    i.prototype.simulatePointerUp = function(e, t, r) {
        var n = new PointerEvent("pointerup",t)
          , o = new _ClickInfo;
        r ? o.doubleClick = !0 : o.singleClick = !0,
        !this._checkPrePointerObservable(e, n, PointerEventTypes.POINTERUP) && this._processPointerUp(e, n, o)
    }
    ,
    i.prototype._processPointerUp = function(e, t, r) {
        var n = this._scene;
        if (e && e && e.pickedMesh) {
            if (this._pickedUpMesh = e.pickedMesh,
            this._pickedDownMesh === this._pickedUpMesh && (n.onPointerPick && n.onPointerPick(t, e),
            r.singleClick && !r.ignore && n.onPointerObservable.hasObservers())) {
                var o = PointerEventTypes.POINTERPICK
                  , a = new PointerInfo(o,t,e);
                this._setRayOnPointerInfo(a),
                n.onPointerObservable.notifyObservers(a, o)
            }
            var s = e.pickedMesh._getActionManagerForTrigger();
            if (s && !r.ignore) {
                s.processTrigger(7, ActionEvent.CreateNew(e.pickedMesh, t, e)),
                !r.hasSwiped && r.singleClick && s.processTrigger(1, ActionEvent.CreateNew(e.pickedMesh, t, e));
                var l = e.pickedMesh._getActionManagerForTrigger(6);
                r.doubleClick && l && l.processTrigger(6, ActionEvent.CreateNew(e.pickedMesh, t, e))
            }
        } else if (!r.ignore)
            for (var u = 0, c = n._pointerUpStage; u < c.length; u++) {
                var h = c[u];
                e = h.action(this._unTranslatedPointerX, this._unTranslatedPointerY, e, t)
            }
        if (this._pickedDownMesh && this._pickedDownMesh !== this._pickedUpMesh) {
            var f = this._pickedDownMesh._getActionManagerForTrigger(16);
            f && f.processTrigger(16, ActionEvent.CreateNew(this._pickedDownMesh, t))
        }
        var d = 0;
        if (n.onPointerObservable.hasObservers()) {
            if (!r.ignore && !r.hasSwiped && (r.singleClick && n.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP) ? d = PointerEventTypes.POINTERTAP : r.doubleClick && n.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) && (d = PointerEventTypes.POINTERDOUBLETAP),
            d)) {
                var a = new PointerInfo(d,t,e);
                this._setRayOnPointerInfo(a),
                n.onPointerObservable.notifyObservers(a, d)
            }
            if (!r.ignore) {
                d = PointerEventTypes.POINTERUP;
                var a = new PointerInfo(d,t,e);
                this._setRayOnPointerInfo(a),
                n.onPointerObservable.notifyObservers(a, d)
            }
        }
        n.onPointerUp && !r.ignore && n.onPointerUp(t, e, d)
    }
    ,
    i.prototype.isPointerCaptured = function(e) {
        return e === void 0 && (e = 0),
        this._pointerCaptures[e]
    }
    ,
    i.prototype.attachControl = function(e, t, r, n) {
        var o = this;
        e === void 0 && (e = !0),
        t === void 0 && (t = !0),
        r === void 0 && (r = !0),
        n === void 0 && (n = null);
        var a = this._scene
          , s = a.getEngine();
        n || (n = s.getInputElement()),
        this._alreadyAttached && this.detachControl(),
        n && (this._alreadyAttachedTo = n),
        this._deviceInputSystem ? this._deviceInputSystem.configureEvents() : this._deviceInputSystem = DeviceInputSystem._Create(s),
        this._initActionManager = function(l, u) {
            if (!o._meshPickProceed) {
                var c = a.pick(o._unTranslatedPointerX, o._unTranslatedPointerY, a.pointerDownPredicate, !1, a.cameraToUseForPointers);
                o._currentPickResult = c,
                c && (l = c.hit && c.pickedMesh ? c.pickedMesh._getActionManagerForTrigger() : null),
                o._meshPickProceed = !0
            }
            return l
        }
        ,
        this._delayedSimpleClick = function(l, u, c) {
            (Date.now() - o._previousStartingPointerTime > i.DoubleClickDelay && !o._doubleClickOccured || l !== o._previousButtonPressed) && (o._doubleClickOccured = !1,
            u.singleClick = !0,
            u.ignore = !1,
            c(u, o._currentPickResult))
        }
        ,
        this._initClickEvent = function(l, u, c, h) {
            var f = new _ClickInfo;
            o._currentPickResult = null;
            var d = null
              , _ = l.hasSpecificMask(PointerEventTypes.POINTERPICK) || u.hasSpecificMask(PointerEventTypes.POINTERPICK) || l.hasSpecificMask(PointerEventTypes.POINTERTAP) || u.hasSpecificMask(PointerEventTypes.POINTERTAP) || l.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || u.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
            !_ && AbstractActionManager && (d = o._initActionManager(d, f),
            d && (_ = d.hasPickTriggers));
            var g = !1;
            if (_) {
                var m = c.button;
                if (f.hasSwiped = o._isPointerSwiping(),
                !f.hasSwiped) {
                    var v = !i.ExclusiveDoubleClickMode;
                    v || (v = !l.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) && !u.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP),
                    v && !AbstractActionManager.HasSpecificTrigger(6) && (d = o._initActionManager(d, f),
                    d && (v = !d.hasSpecificTrigger(6)))),
                    v ? (Date.now() - o._previousStartingPointerTime > i.DoubleClickDelay || m !== o._previousButtonPressed) && (f.singleClick = !0,
                    h(f, o._currentPickResult),
                    g = !0) : (o._previousDelayedSimpleClickTimeout = o._delayedSimpleClickTimeout,
                    o._delayedSimpleClickTimeout = window.setTimeout(o._delayedSimpleClick.bind(o, m, f, h), i.DoubleClickDelay));
                    var y = l.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || u.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
                    !y && AbstractActionManager.HasSpecificTrigger(6) && (d = o._initActionManager(d, f),
                    d && (y = d.hasSpecificTrigger(6))),
                    y && (m === o._previousButtonPressed && Date.now() - o._previousStartingPointerTime < i.DoubleClickDelay && !o._doubleClickOccured ? (!f.hasSwiped && !o._isPointerSwiping() ? (o._previousStartingPointerTime = 0,
                    o._doubleClickOccured = !0,
                    f.doubleClick = !0,
                    f.ignore = !1,
                    i.ExclusiveDoubleClickMode && o._previousDelayedSimpleClickTimeout && clearTimeout(o._previousDelayedSimpleClickTimeout),
                    o._previousDelayedSimpleClickTimeout = o._delayedSimpleClickTimeout,
                    h(f, o._currentPickResult)) : (o._doubleClickOccured = !1,
                    o._previousStartingPointerTime = o._startingPointerTime,
                    o._previousStartingPointerPosition.x = o._startingPointerPosition.x,
                    o._previousStartingPointerPosition.y = o._startingPointerPosition.y,
                    o._previousButtonPressed = m,
                    i.ExclusiveDoubleClickMode ? (o._previousDelayedSimpleClickTimeout && clearTimeout(o._previousDelayedSimpleClickTimeout),
                    o._previousDelayedSimpleClickTimeout = o._delayedSimpleClickTimeout,
                    h(f, o._previousPickResult)) : h(f, o._currentPickResult)),
                    g = !0) : (o._doubleClickOccured = !1,
                    o._previousStartingPointerTime = o._startingPointerTime,
                    o._previousStartingPointerPosition.x = o._startingPointerPosition.x,
                    o._previousStartingPointerPosition.y = o._startingPointerPosition.y,
                    o._previousButtonPressed = m))
                }
            }
            g || h(f, o._currentPickResult)
        }
        ,
        this._onPointerMove = function(l) {
            if (l.pointerId === void 0 && (l.pointerId = 0),
            o._updatePointerPosition(l),
            !o._checkPrePointerObservable(null, l, l.type === "wheel" || l.type === "mousewheel" || l.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE) && !(!a.cameraToUseForPointers && !a.activeCamera)) {
                if (a.skipPointerMovePicking) {
                    o._processPointerMove(new PickingInfo, l);
                    return
                }
                a.pointerMovePredicate || (a.pointerMovePredicate = function(c) {
                    return c.isPickable && c.isVisible && c.isReady() && c.isEnabled() && (c.enablePointerMoveEvents || a.constantlyUpdateMeshUnderPointer || c._getActionManagerForTrigger() !== null) && (!a.cameraToUseForPointers || (a.cameraToUseForPointers.layerMask & c.layerMask) !== 0)
                }
                );
                var u = a.pick(o._unTranslatedPointerX, o._unTranslatedPointerY, a.pointerMovePredicate, !1, a.cameraToUseForPointers, a.pointerMoveTrianglePredicate);
                o._processPointerMove(u, l)
            }
        }
        ,
        this._onPointerDown = function(l) {
            if (o._totalPointersPressed++,
            o._pickedDownMesh = null,
            o._meshPickProceed = !1,
            l.pointerId === void 0 && (l.pointerId = 0),
            o._updatePointerPosition(l),
            a.preventDefaultOnPointerDown && n && (l.preventDefault(),
            n.focus()),
            o._startingPointerPosition.x = o._pointerX,
            o._startingPointerPosition.y = o._pointerY,
            o._startingPointerTime = Date.now(),
            !o._checkPrePointerObservable(null, l, PointerEventTypes.POINTERDOWN) && !(!a.cameraToUseForPointers && !a.activeCamera)) {
                o._pointerCaptures[l.pointerId] = !0,
                a.pointerDownPredicate || (a.pointerDownPredicate = function(c) {
                    return c.isPickable && c.isVisible && c.isReady() && c.isEnabled() && (!a.cameraToUseForPointers || (a.cameraToUseForPointers.layerMask & c.layerMask) !== 0)
                }
                ),
                o._pickedDownMesh = null;
                var u = a.pick(o._unTranslatedPointerX, o._unTranslatedPointerY, a.pointerDownPredicate, !1, a.cameraToUseForPointers);
                o._processPointerDown(u, l)
            }
        }
        ,
        this._onPointerUp = function(l) {
            o._totalPointersPressed !== 0 && (o._totalPointersPressed--,
            o._pickedUpMesh = null,
            o._meshPickProceed = !1,
            l.pointerId === void 0 && (l.pointerId = 0),
            o._updatePointerPosition(l),
            a.preventDefaultOnPointerUp && n && (l.preventDefault(),
            n.focus()),
            o._initClickEvent(a.onPrePointerObservable, a.onPointerObservable, l, function(u, c) {
                a.onPrePointerObservable.hasObservers() && !u.ignore && (!u.hasSwiped && (u.singleClick && a.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP) && o._checkPrePointerObservable(null, l, PointerEventTypes.POINTERTAP) || u.doubleClick && a.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) && o._checkPrePointerObservable(null, l, PointerEventTypes.POINTERDOUBLETAP)) || o._checkPrePointerObservable(null, l, PointerEventTypes.POINTERUP)) || !o._pointerCaptures[l.pointerId] && l.buttons > 0 || (o._pointerCaptures[l.pointerId] = !1,
                !(!a.cameraToUseForPointers && !a.activeCamera) && (a.pointerUpPredicate || (a.pointerUpPredicate = function(h) {
                    return h.isPickable && h.isVisible && h.isReady() && h.isEnabled() && (!a.cameraToUseForPointers || (a.cameraToUseForPointers.layerMask & h.layerMask) !== 0)
                }
                ),
                !o._meshPickProceed && (AbstractActionManager && AbstractActionManager.HasTriggers || a.onPointerObservable.hasObservers()) && o._initActionManager(null, u),
                c || (c = o._currentPickResult),
                o._processPointerUp(c, l, u),
                o._previousPickResult = o._currentPickResult))
            }))
        }
        ,
        this._onKeyDown = function(l) {
            var u = KeyboardEventTypes.KEYDOWN;
            if (a.onPreKeyboardObservable.hasObservers()) {
                var c = new KeyboardInfoPre(u,l);
                if (a.onPreKeyboardObservable.notifyObservers(c, u),
                c.skipOnPointerObservable)
                    return
            }
            if (a.onKeyboardObservable.hasObservers()) {
                var c = new KeyboardInfo(u,l);
                a.onKeyboardObservable.notifyObservers(c, u)
            }
            a.actionManager && a.actionManager.processTrigger(14, ActionEvent.CreateNewFromScene(a, l))
        }
        ,
        this._onKeyUp = function(l) {
            var u = KeyboardEventTypes.KEYUP;
            if (a.onPreKeyboardObservable.hasObservers()) {
                var c = new KeyboardInfoPre(u,l);
                if (a.onPreKeyboardObservable.notifyObservers(c, u),
                c.skipOnPointerObservable)
                    return
            }
            if (a.onKeyboardObservable.hasObservers()) {
                var c = new KeyboardInfo(u,l);
                a.onKeyboardObservable.notifyObservers(c, u)
            }
            a.actionManager && a.actionManager.processTrigger(15, ActionEvent.CreateNewFromScene(a, l))
        }
        ,
        this._onInputObserver = this._deviceInputSystem.onInputChangedObservable.add(function(l) {
            var u = l;
            l.deviceType === DeviceType.Keyboard && (l.currentState === 1 && o._onKeyDown(u),
            l.currentState === 0 && o._onKeyUp(u)),
            (l.deviceType === DeviceType.Mouse || l.deviceType === DeviceType.Touch) && (t && l.inputIndex >= PointerInput.LeftClick && l.inputIndex <= PointerInput.RightClick && l.currentState === 1 && o._onPointerDown(u),
            e && l.inputIndex >= PointerInput.LeftClick && l.inputIndex <= PointerInput.RightClick && l.currentState === 0 && o._onPointerUp(u),
            r && (l.inputIndex === PointerInput.Horizontal || l.inputIndex === PointerInput.Vertical || l.inputIndex === PointerInput.DeltaHorizontal || l.inputIndex === PointerInput.DeltaVertical || l.inputIndex === PointerInput.MouseWheelX || l.inputIndex === PointerInput.MouseWheelY || l.inputIndex === PointerInput.MouseWheelZ) && o._onPointerMove(u))
        }),
        this._alreadyAttached = !0
    }
    ,
    i.prototype.detachControl = function() {
        this._alreadyAttached && (this._deviceInputSystem.onInputChangedObservable.remove(this._onInputObserver),
        this._alreadyAttachedTo && !this._scene.doNotHandleCursors && (this._alreadyAttachedTo.style.cursor = this._scene.defaultCursor),
        this._alreadyAttached = !1)
    }
    ,
    i.prototype.setPointerOverMesh = function(e, t, r) {
        if (t === void 0 && (t = 0),
        this._meshUnderPointerId[t] !== e) {
            var n = this._meshUnderPointerId[t], o;
            n && (o = n._getActionManagerForTrigger(10),
            o && o.processTrigger(10, ActionEvent.CreateNew(n, void 0, {
                pointerId: t
            }))),
            e ? (this._meshUnderPointerId[t] = e,
            this._pointerOverMesh = e,
            o = e._getActionManagerForTrigger(9),
            o && o.processTrigger(9, ActionEvent.CreateNew(e, void 0, {
                pointerId: t,
                pickResult: r
            }))) : (delete this._meshUnderPointerId[t],
            this._pointerOverMesh = null)
        }
    }
    ,
    i.prototype.getPointerOverMesh = function() {
        return this._pointerOverMesh
    }
    ,
    i.prototype._invalidateMesh = function(e) {
        this._pointerOverMesh === e && (this._pointerOverMesh = null),
        this._pickedDownMesh === e && (this._pickedDownMesh = null),
        this._pickedUpMesh === e && (this._pickedUpMesh = null);
        for (var t in this._meshUnderPointerId)
            this._meshUnderPointerId[t] === e && delete this._meshUnderPointerId[t]
    }
    ,
    i.DragMovementThreshold = 10,
    i.LongPressDelay = 500,
    i.DoubleClickDelay = 300,
    i.ExclusiveDoubleClickMode = !1,
    i
}()
  , PerfCounter = function() {
    function i() {
        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
    }
    return Object.defineProperty(i.prototype, "min", {
        get: function() {
            return this._min
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "max", {
        get: function() {
            return this._max
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "average", {
        get: function() {
            return this._average
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "lastSecAverage", {
        get: function() {
            return this._lastSecAverage
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "current", {
        get: function() {
            return this._current
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "total", {
        get: function() {
            return this._totalAccumulated
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "count", {
        get: function() {
            return this._totalValueCount
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.fetchNewFrame = function() {
        this._totalValueCount++,
        this._current = 0,
        this._lastSecValueCount++
    }
    ,
    i.prototype.addCount = function(e, t) {
        !i.Enabled || (this._current += e,
        t && this._fetchResult())
    }
    ,
    i.prototype.beginMonitoring = function() {
        !i.Enabled || (this._startMonitoringTime = PrecisionDate.Now)
    }
    ,
    i.prototype.endMonitoring = function(e) {
        if (e === void 0 && (e = !0),
        !!i.Enabled) {
            e && this.fetchNewFrame();
            var t = PrecisionDate.Now;
            this._current = t - this._startMonitoringTime,
            e && this._fetchResult()
        }
    }
    ,
    i.prototype._fetchResult = function() {
        this._totalAccumulated += this._current,
        this._lastSecAccumulated += this._current,
        this._min = Math.min(this._min, this._current),
        this._max = Math.max(this._max, this._current),
        this._average = this._totalAccumulated / this._totalValueCount;
        var e = PrecisionDate.Now;
        e - this._lastSecTime > 1e3 && (this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount,
        this._lastSecTime = e,
        this._lastSecAccumulated = 0,
        this._lastSecValueCount = 0)
    }
    ,
    i.Enabled = !0,
    i
}()
  , Plane = function() {
    function i(e, t, r, n) {
        this.normal = new Vector3(e,t,r),
        this.d = n
    }
    return i.prototype.asArray = function() {
        return [this.normal.x, this.normal.y, this.normal.z, this.d]
    }
    ,
    i.prototype.clone = function() {
        return new i(this.normal.x,this.normal.y,this.normal.z,this.d)
    }
    ,
    i.prototype.getClassName = function() {
        return "Plane"
    }
    ,
    i.prototype.getHashCode = function() {
        var e = this.normal.getHashCode();
        return e = e * 397 ^ (this.d | 0),
        e
    }
    ,
    i.prototype.normalize = function() {
        var e = Math.sqrt(this.normal.x * this.normal.x + this.normal.y * this.normal.y + this.normal.z * this.normal.z)
          , t = 0;
        return e !== 0 && (t = 1 / e),
        this.normal.x *= t,
        this.normal.y *= t,
        this.normal.z *= t,
        this.d *= t,
        this
    }
    ,
    i.prototype.transform = function(e) {
        var t = i._TmpMatrix;
        e.invertToRef(t);
        var r = t.m
          , n = this.normal.x
          , o = this.normal.y
          , a = this.normal.z
          , s = this.d
          , l = n * r[0] + o * r[1] + a * r[2] + s * r[3]
          , u = n * r[4] + o * r[5] + a * r[6] + s * r[7]
          , c = n * r[8] + o * r[9] + a * r[10] + s * r[11]
          , h = n * r[12] + o * r[13] + a * r[14] + s * r[15];
        return new i(l,u,c,h)
    }
    ,
    i.prototype.dotCoordinate = function(e) {
        return this.normal.x * e.x + this.normal.y * e.y + this.normal.z * e.z + this.d
    }
    ,
    i.prototype.copyFromPoints = function(e, t, r) {
        var n = t.x - e.x, o = t.y - e.y, a = t.z - e.z, s = r.x - e.x, l = r.y - e.y, u = r.z - e.z, c = o * u - a * l, h = a * s - n * u, f = n * l - o * s, d = Math.sqrt(c * c + h * h + f * f), _;
        return d !== 0 ? _ = 1 / d : _ = 0,
        this.normal.x = c * _,
        this.normal.y = h * _,
        this.normal.z = f * _,
        this.d = -(this.normal.x * e.x + this.normal.y * e.y + this.normal.z * e.z),
        this
    }
    ,
    i.prototype.isFrontFacingTo = function(e, t) {
        var r = Vector3.Dot(this.normal, e);
        return r <= t
    }
    ,
    i.prototype.signedDistanceTo = function(e) {
        return Vector3.Dot(e, this.normal) + this.d
    }
    ,
    i.FromArray = function(e) {
        return new i(e[0],e[1],e[2],e[3])
    }
    ,
    i.FromPoints = function(e, t, r) {
        var n = new i(0,0,0,0);
        return n.copyFromPoints(e, t, r),
        n
    }
    ,
    i.FromPositionAndNormal = function(e, t) {
        var r = new i(0,0,0,0);
        return t.normalize(),
        r.normal = t,
        r.d = -(t.x * e.x + t.y * e.y + t.z * e.z),
        r
    }
    ,
    i.SignedDistanceToPlaneFromPositionAndNormal = function(e, t, r) {
        var n = -(t.x * e.x + t.y * e.y + t.z * e.z);
        return Vector3.Dot(r, t) + n
    }
    ,
    i._TmpMatrix = Matrix.Identity(),
    i
}()
  , Frustum = function() {
    function i() {}
    return i.GetPlanes = function(e) {
        for (var t = [], r = 0; r < 6; r++)
            t.push(new Plane(0,0,0,0));
        return i.GetPlanesToRef(e, t),
        t
    }
    ,
    i.GetNearPlaneToRef = function(e, t) {
        var r = e.m;
        t.normal.x = r[3] + r[2],
        t.normal.y = r[7] + r[6],
        t.normal.z = r[11] + r[10],
        t.d = r[15] + r[14],
        t.normalize()
    }
    ,
    i.GetFarPlaneToRef = function(e, t) {
        var r = e.m;
        t.normal.x = r[3] - r[2],
        t.normal.y = r[7] - r[6],
        t.normal.z = r[11] - r[10],
        t.d = r[15] - r[14],
        t.normalize()
    }
    ,
    i.GetLeftPlaneToRef = function(e, t) {
        var r = e.m;
        t.normal.x = r[3] + r[0],
        t.normal.y = r[7] + r[4],
        t.normal.z = r[11] + r[8],
        t.d = r[15] + r[12],
        t.normalize()
    }
    ,
    i.GetRightPlaneToRef = function(e, t) {
        var r = e.m;
        t.normal.x = r[3] - r[0],
        t.normal.y = r[7] - r[4],
        t.normal.z = r[11] - r[8],
        t.d = r[15] - r[12],
        t.normalize()
    }
    ,
    i.GetTopPlaneToRef = function(e, t) {
        var r = e.m;
        t.normal.x = r[3] - r[1],
        t.normal.y = r[7] - r[5],
        t.normal.z = r[11] - r[9],
        t.d = r[15] - r[13],
        t.normalize()
    }
    ,
    i.GetBottomPlaneToRef = function(e, t) {
        var r = e.m;
        t.normal.x = r[3] + r[1],
        t.normal.y = r[7] + r[5],
        t.normal.z = r[11] + r[9],
        t.d = r[15] + r[13],
        t.normalize()
    }
    ,
    i.GetPlanesToRef = function(e, t) {
        i.GetNearPlaneToRef(e, t[0]),
        i.GetFarPlaneToRef(e, t[1]),
        i.GetLeftPlaneToRef(e, t[2]),
        i.GetRightPlaneToRef(e, t[3]),
        i.GetTopPlaneToRef(e, t[4]),
        i.GetBottomPlaneToRef(e, t[5])
    }
    ,
    i
}()
  , UniqueIdGenerator = function() {
    function i() {}
    return Object.defineProperty(i, "UniqueId", {
        get: function() {
            var e = this._UniqueIdCounter;
            return this._UniqueIdCounter++,
            e
        },
        enumerable: !1,
        configurable: !0
    }),
    i._UniqueIdCounter = 0,
    i
}()
  , LightConstants = function() {
    function i() {}
    return i.CompareLightsPriority = function(e, t) {
        return e.shadowEnabled !== t.shadowEnabled ? (t.shadowEnabled ? 1 : 0) - (e.shadowEnabled ? 1 : 0) : t.renderPriority - e.renderPriority
    }
    ,
    i.FALLOFF_DEFAULT = 0,
    i.FALLOFF_PHYSICAL = 1,
    i.FALLOFF_GLTF = 2,
    i.FALLOFF_STANDARD = 3,
    i.LIGHTMAP_DEFAULT = 0,
    i.LIGHTMAP_SPECULAR = 1,
    i.LIGHTMAP_SHADOWSONLY = 2,
    i.INTENSITYMODE_AUTOMATIC = 0,
    i.INTENSITYMODE_LUMINOUSPOWER = 1,
    i.INTENSITYMODE_LUMINOUSINTENSITY = 2,
    i.INTENSITYMODE_ILLUMINANCE = 3,
    i.INTENSITYMODE_LUMINANCE = 4,
    i.LIGHTTYPEID_POINTLIGHT = 0,
    i.LIGHTTYPEID_DIRECTIONALLIGHT = 1,
    i.LIGHTTYPEID_SPOTLIGHT = 2,
    i.LIGHTTYPEID_HEMISPHERICLIGHT = 3,
    i
}()
  , ComputePressureObserverWrapper = function() {
    function i(e, t) {
        i.IsAvailable && (this._observer = new window.ComputePressureObserver(e,t))
    }
    return Object.defineProperty(i, "IsAvailable", {
        get: function() {
            return IsWindowObjectExist() && "ComputePressureObserver"in window
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.observe = function() {
        var e, t;
        !((e = this._observer) === null || e === void 0) && e.observe && ((t = this._observer) === null || t === void 0 || t.observe())
    }
    ,
    i.prototype.unobserve = function() {
        var e, t;
        !((e = this._observer) === null || e === void 0) && e.unobserve && ((t = this._observer) === null || t === void 0 || t.unobserve())
    }
    ,
    i
}()
  , _injectLTSScene = function(i) {
    i.prototype.setActiveCameraByID = function(e) {
        return this.setActiveCameraById(e)
    }
    ,
    i.prototype.getLastMaterialByID = function(e) {
        return this.getLastMaterialById(e)
    }
    ,
    i.prototype.getMaterialByID = function(e) {
        return this.getMaterialById(e)
    }
    ,
    i.prototype.getTextureByUniqueID = function(e) {
        return this.getTextureByUniqueId(e)
    }
    ,
    i.prototype.getCameraByID = function(e) {
        return this.getCameraById(e)
    }
    ,
    i.prototype.getCameraByUniqueID = function(e) {
        return this.getCameraByUniqueId(e)
    }
    ,
    i.prototype.getBoneByID = function(e) {
        return this.getBoneById(e)
    }
    ,
    i.prototype.getLightByID = function(e) {
        return this.getLightById(e)
    }
    ,
    i.prototype.getLightByUniqueID = function(e) {
        return this.getLightByUniqueId(e)
    }
    ,
    i.prototype.getParticleSystemByID = function(e) {
        return this.getParticleSystemById(e)
    }
    ,
    i.prototype.getGeometryByID = function(e) {
        return this.getGeometryById(e)
    }
    ,
    i.prototype.getMeshByID = function(e) {
        return this.getMeshById(e)
    }
    ,
    i.prototype.getMeshesByID = function(e) {
        return this.getMeshesById(e)
    }
    ,
    i.prototype.getTransformNodeByID = function(e) {
        return this.getTransformNodeById(e)
    }
    ,
    i.prototype.getTransformNodeByUniqueID = function(e) {
        return this.getTransformNodeByUniqueId(e)
    }
    ,
    i.prototype.getTransformNodesByID = function(e) {
        return this.getTransformNodesById(e)
    }
    ,
    i.prototype.getMeshByUniqueID = function(e) {
        return this.getMeshByUniqueId(e)
    }
    ,
    i.prototype.getLastMeshByID = function(e) {
        return this.getLastMeshById(e)
    }
    ,
    i.prototype.getLastEntryByID = function(e) {
        return this.getLastEntryById(e)
    }
    ,
    i.prototype.getNodeByID = function(e) {
        return this.getNodeById(e)
    }
    ,
    i.prototype.getLastSkeletonByID = function(e) {
        return this.getLastSkeletonById(e)
    }
}
  , Scene = function(i) {
    __extends(e, i);
    function e(t, r) {
        var n = i.call(this) || this;
        n._inputManager = new InputManager(n),
        n.cameraToUseForPointers = null,
        n._isScene = !0,
        n._blockEntityCollection = !1,
        n.autoClear = !0,
        n.autoClearDepthAndStencil = !0,
        n.clearColor = new Color4(.2,.2,.3,1),
        n.ambientColor = new Color3(0,0,0),
        n._environmentIntensity = 1,
        n._forceWireframe = !1,
        n._skipFrustumClipping = !1,
        n._forcePointsCloud = !1,
        n.animationsEnabled = !0,
        n._animationPropertiesOverride = null,
        n.useConstantAnimationDeltaTime = !1,
        n.constantlyUpdateMeshUnderPointer = !1,
        n.hoverCursor = "pointer",
        n.defaultCursor = "",
        n.doNotHandleCursors = !1,
        n.preventDefaultOnPointerDown = !0,
        n.preventDefaultOnPointerUp = !0,
        n.metadata = null,
        n.reservedDataStore = null,
        n.disableOfflineSupportExceptionRules = new Array,
        n.onDisposeObservable = new Observable,
        n._onDisposeObserver = null,
        n.onBeforeRenderObservable = new Observable,
        n._onBeforeRenderObserver = null,
        n.onAfterRenderObservable = new Observable,
        n.onBeforeRunRegisterBeforeRenderObservable = new Observable,
        n.onAfterRunRegisterBeforeRenderObservable = new Observable,
        n.onBeforeRunRegisterAfterRenderObservable = new Observable,
        n.onAfterRunRegisterAfterRenderObservable = new Observable,
        n.onBeforeRTT1Observable = new Observable,
        n.onAfterRTT1Observable = new Observable,
        n.onAfterRenderCameraObservable = new Observable,
        n._onAfterRenderObserver = null,
        n.onBeforeAnimationsObservable = new Observable,
        n.onAfterAnimationsObservable = new Observable,
        n.onBeforeDrawPhaseObservable = new Observable,
        n.onAfterDrawPhaseObservable = new Observable,
        n.onReadyObservable = new Observable,
        n.onBeforeCameraRenderObservable = new Observable,
        n._onBeforeCameraRenderObserver = null,
        n.onAfterCameraRenderObservable = new Observable,
        n._onAfterCameraRenderObserver = null,
        n.onBeforeActiveMeshesEvaluationObservable = new Observable,
        n.onAfterActiveMeshesEvaluationObservable = new Observable,
        n.onBeforeParticlesRenderingObservable = new Observable,
        n.onAfterParticlesRenderingObservable = new Observable,
        n.onDataLoadedObservable = new Observable,
        n.onNewCameraAddedObservable = new Observable,
        n.onCameraRemovedObservable = new Observable,
        n.onNewLightAddedObservable = new Observable,
        n.onLightRemovedObservable = new Observable,
        n.onNewGeometryAddedObservable = new Observable,
        n.onGeometryRemovedObservable = new Observable,
        n.onNewTransformNodeAddedObservable = new Observable,
        n.onTransformNodeRemovedObservable = new Observable,
        n.onNewMeshAddedObservable = new Observable,
        n.onMeshRemovedObservable = new Observable,
        n.onNewSkeletonAddedObservable = new Observable,
        n.onSkeletonRemovedObservable = new Observable,
        n.onNewMaterialAddedObservable = new Observable,
        n.onNewMultiMaterialAddedObservable = new Observable,
        n.onMaterialRemovedObservable = new Observable,
        n.onMultiMaterialRemovedObservable = new Observable,
        n.onNewTextureAddedObservable = new Observable,
        n.onTextureRemovedObservable = new Observable,
        n.onBeforeRenderTargetsRenderObservable = new Observable,
        n.onAfterRenderTargetsRenderObservable = new Observable,
        n.onBeforeStepObservable = new Observable,
        n.onAfterStepObservable = new Observable,
        n.onActiveCameraChanged = new Observable,
        n.onBeforeRenderingGroupObservable = new Observable,
        n.onAfterRenderingGroupObservable = new Observable,
        n.onMeshImportedObservable = new Observable,
        n.onAnimationFileImportedObservable = new Observable,
        n._registeredForLateAnimationBindings = new SmartArrayNoDuplicate(256),
        n.skipPointerMovePicking = !1,
        n.onPrePointerObservable = new Observable,
        n.onPointerObservable = new Observable,
        n.onPreKeyboardObservable = new Observable,
        n.onKeyboardObservable = new Observable,
        n._useRightHandedSystem = !1,
        n._timeAccumulator = 0,
        n._currentStepId = 0,
        n._currentInternalStep = 0,
        n._fogEnabled = !0,
        n._fogMode = e.FOGMODE_NONE,
        n.fogColor = new Color3(.2,.2,.3),
        n.fogDensity = .1,
        n.fogStart = 0,
        n.fogEnd = 1e3,
        n.needsPreviousWorldMatrices = !1,
        n._shadowsEnabled = !0,
        n._lightsEnabled = !0,
        n.activeCameras = new Array,
        n._texturesEnabled = !0,
        n.physicsEnabled = !0,
        n.particlesEnabled = !0,
        n.spritesEnabled = !0,
        n._skeletonsEnabled = !0,
        n.lensFlaresEnabled = !0,
        n.collisionsEnabled = !0,
        n.gravity = new Vector3(0,-9.807,0),
        n.postProcessesEnabled = !0,
        n.renderTargetsEnabled = !0,
        n.dumpNextRenderTargets = !1,
        n.customRenderTargets = new Array,
        n.importedMeshesFiles = new Array,
        n.probesEnabled = !0,
        n._meshesForIntersections = new SmartArrayNoDuplicate(256),
        n.proceduralTexturesEnabled = !0,
        n._totalVertices = new PerfCounter,
        n._activeIndices = new PerfCounter,
        n._activeParticles = new PerfCounter,
        n._activeBones = new PerfCounter,
        n._animationTime = 0,
        n.animationTimeScale = 1,
        n._renderId = 0,
        n._frameId = 0,
        n._executeWhenReadyTimeoutId = -1,
        n._intermediateRendering = !1,
        n._defaultFrameBufferCleared = !1,
        n._viewUpdateFlag = -1,
        n._projectionUpdateFlag = -1,
        n._toBeDisposed = new Array(256),
        n._activeRequests = new Array,
        n._pendingData = new Array,
        n._isDisposed = !1,
        n.dispatchAllSubMeshesOfActiveMeshes = !1,
        n._activeMeshes = new SmartArray(256),
        n._processedMaterials = new SmartArray(256),
        n._renderTargets = new SmartArrayNoDuplicate(256),
        n._activeParticleSystems = new SmartArray(256),
        n._activeSkeletons = new SmartArrayNoDuplicate(32),
        n._softwareSkinnedMeshes = new SmartArrayNoDuplicate(32),
        n._activeAnimatables = new Array,
        n._transformMatrix = Matrix.Zero(),
        n.requireLightSorting = !1,
        n._components = [],
        n._serializableComponents = [],
        n._transientComponents = [],
        n._beforeCameraUpdateStage = Stage.Create(),
        n._beforeClearStage = Stage.Create(),
        n._beforeRenderTargetClearStage = Stage.Create(),
        n._gatherRenderTargetsStage = Stage.Create(),
        n._gatherActiveCameraRenderTargetsStage = Stage.Create(),
        n._isReadyForMeshStage = Stage.Create(),
        n._beforeEvaluateActiveMeshStage = Stage.Create(),
        n._evaluateSubMeshStage = Stage.Create(),
        n._preActiveMeshStage = Stage.Create(),
        n._cameraDrawRenderTargetStage = Stage.Create(),
        n._beforeCameraDrawStage = Stage.Create(),
        n._beforeRenderTargetDrawStage = Stage.Create(),
        n._beforeRenderingGroupDrawStage = Stage.Create(),
        n._beforeRenderingMeshStage = Stage.Create(),
        n._afterRenderingMeshStage = Stage.Create(),
        n._afterRenderingGroupDrawStage = Stage.Create(),
        n._afterCameraDrawStage = Stage.Create(),
        n._afterRenderTargetDrawStage = Stage.Create(),
        n._afterRenderStage = Stage.Create(),
        n._pointerMoveStage = Stage.Create(),
        n._pointerDownStage = Stage.Create(),
        n._pointerUpStage = Stage.Create(),
        n.geometriesByUniqueId = null,
        n._defaultMeshCandidates = {
            data: [],
            length: 0
        },
        n._defaultSubMeshCandidates = {
            data: [],
            length: 0
        },
        n._preventFreeActiveMeshesAndRenderingGroups = !1,
        n._activeMeshesFrozen = !1,
        n._skipEvaluateActiveMeshesCompletely = !1,
        n._allowPostProcessClearColor = !0,
        n.getDeterministicFrameTime = function() {
            return n._engine.getTimeStep()
        }
        ,
        n._blockMaterialDirtyMechanism = !1,
        n._perfCollector = null,
        n.onComputePressureChanged = new Observable;
        var o = __assign({
            useGeometryUniqueIdsMap: !0,
            useMaterialMeshMap: !0,
            useClonedMeshMap: !0,
            virtual: !1
        }, r);
        return n._engine = t || EngineStore.LastCreatedEngine,
        o.virtual ? n._engine._virtualScenes.push(n) : (EngineStore._LastCreatedScene = n,
        n._engine.scenes.push(n)),
        n._uid = null,
        n._renderingManager = new RenderingManager(n),
        PostProcessManager && (n.postProcessManager = new PostProcessManager(n)),
        IsWindowObjectExist() && n.attachControl(),
        n._createUbo(),
        ImageProcessingConfiguration && (n._imageProcessingConfiguration = new ImageProcessingConfiguration),
        n.setDefaultCandidateProviders(),
        o.useGeometryUniqueIdsMap && (n.geometriesByUniqueId = {}),
        n.useMaterialMeshMap = o.useMaterialMeshMap,
        n.useClonedMeshMap = o.useClonedMeshMap,
        (!r || !r.virtual) && n._engine.onNewSceneAddedObservable.notifyObservers(n),
        ComputePressureObserverWrapper.IsAvailable && (n._computePressureObserver = new ComputePressureObserverWrapper(function(a) {
            n.onComputePressureChanged.notifyObservers(a)
        }
        ,{
            cpuUtilizationThresholds: [.25, .5, .75, .9],
            cpuSpeedThresholds: [.5]
        }),
        n._computePressureObserver.observe()),
        n
    }
    return e.DefaultMaterialFactory = function(t) {
        throw _WarnImport("StandardMaterial")
    }
    ,
    e.CollisionCoordinatorFactory = function() {
        throw _WarnImport("DefaultCollisionCoordinator")
    }
    ,
    Object.defineProperty(e.prototype, "environmentTexture", {
        get: function() {
            return this._environmentTexture
        },
        set: function(t) {
            this._environmentTexture !== t && (this._environmentTexture = t,
            this.markAllMaterialsAsDirty(1))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "environmentIntensity", {
        get: function() {
            return this._environmentIntensity
        },
        set: function(t) {
            this._environmentIntensity !== t && (this._environmentIntensity = t,
            this.markAllMaterialsAsDirty(1))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "imageProcessingConfiguration", {
        get: function() {
            return this._imageProcessingConfiguration
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "forceWireframe", {
        get: function() {
            return this._forceWireframe
        },
        set: function(t) {
            this._forceWireframe !== t && (this._forceWireframe = t,
            this.markAllMaterialsAsDirty(16))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "skipFrustumClipping", {
        get: function() {
            return this._skipFrustumClipping
        },
        set: function(t) {
            this._skipFrustumClipping !== t && (this._skipFrustumClipping = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "forcePointsCloud", {
        get: function() {
            return this._forcePointsCloud
        },
        set: function(t) {
            this._forcePointsCloud !== t && (this._forcePointsCloud = t,
            this.markAllMaterialsAsDirty(16))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "animationPropertiesOverride", {
        get: function() {
            return this._animationPropertiesOverride
        },
        set: function(t) {
            this._animationPropertiesOverride = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "onDispose", {
        set: function(t) {
            this._onDisposeObserver && this.onDisposeObservable.remove(this._onDisposeObserver),
            this._onDisposeObserver = this.onDisposeObservable.add(t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "beforeRender", {
        set: function(t) {
            this._onBeforeRenderObserver && this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),
            t && (this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(t))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "afterRender", {
        set: function(t) {
            this._onAfterRenderObserver && this.onAfterRenderObservable.remove(this._onAfterRenderObserver),
            t && (this._onAfterRenderObserver = this.onAfterRenderObservable.add(t))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "beforeCameraRender", {
        set: function(t) {
            this._onBeforeCameraRenderObserver && this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),
            this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "afterCameraRender", {
        set: function(t) {
            this._onAfterCameraRenderObserver && this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),
            this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "unTranslatedPointer", {
        get: function() {
            return this._inputManager.unTranslatedPointer
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e, "DragMovementThreshold", {
        get: function() {
            return InputManager.DragMovementThreshold
        },
        set: function(t) {
            InputManager.DragMovementThreshold = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e, "LongPressDelay", {
        get: function() {
            return InputManager.LongPressDelay
        },
        set: function(t) {
            InputManager.LongPressDelay = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e, "DoubleClickDelay", {
        get: function() {
            return InputManager.DoubleClickDelay
        },
        set: function(t) {
            InputManager.DoubleClickDelay = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e, "ExclusiveDoubleClickMode", {
        get: function() {
            return InputManager.ExclusiveDoubleClickMode
        },
        set: function(t) {
            InputManager.ExclusiveDoubleClickMode = t
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.bindEyePosition = function(t, r, n) {
        var o;
        r === void 0 && (r = "vEyePosition"),
        n === void 0 && (n = !1);
        var a = this._forcedViewPosition ? this._forcedViewPosition : this._mirroredCameraPosition ? this._mirroredCameraPosition : (o = this.activeCamera.globalPosition) !== null && o !== void 0 ? o : this.activeCamera.devicePosition
          , s = this.useRightHandedSystem === (this._mirroredCameraPosition != null);
        return TmpVectors.Vector4[0].set(a.x, a.y, a.z, s ? -1 : 1),
        t && (n ? t.setFloat3(r, TmpVectors.Vector4[0].x, TmpVectors.Vector4[0].y, TmpVectors.Vector4[0].z) : t.setVector4(r, TmpVectors.Vector4[0])),
        TmpVectors.Vector4[0]
    }
    ,
    e.prototype.finalizeSceneUbo = function() {
        var t = this.getSceneUniformBuffer()
          , r = this.bindEyePosition(null);
        return t.updateFloat4("vEyePosition", r.x, r.y, r.z, r.w),
        t.update(),
        t
    }
    ,
    Object.defineProperty(e.prototype, "useRightHandedSystem", {
        get: function() {
            return this._useRightHandedSystem
        },
        set: function(t) {
            this._useRightHandedSystem !== t && (this._useRightHandedSystem = t,
            this.markAllMaterialsAsDirty(16))
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.setStepId = function(t) {
        this._currentStepId = t
    }
    ,
    e.prototype.getStepId = function() {
        return this._currentStepId
    }
    ,
    e.prototype.getInternalStep = function() {
        return this._currentInternalStep
    }
    ,
    Object.defineProperty(e.prototype, "fogEnabled", {
        get: function() {
            return this._fogEnabled
        },
        set: function(t) {
            this._fogEnabled !== t && (this._fogEnabled = t,
            this.markAllMaterialsAsDirty(16))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "fogMode", {
        get: function() {
            return this._fogMode
        },
        set: function(t) {
            this._fogMode !== t && (this._fogMode = t,
            this.markAllMaterialsAsDirty(16))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "prePass", {
        get: function() {
            return !!this.prePassRenderer && this.prePassRenderer.defaultRT.enabled
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "shadowsEnabled", {
        get: function() {
            return this._shadowsEnabled
        },
        set: function(t) {
            this._shadowsEnabled !== t && (this._shadowsEnabled = t,
            this.markAllMaterialsAsDirty(2))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "lightsEnabled", {
        get: function() {
            return this._lightsEnabled
        },
        set: function(t) {
            this._lightsEnabled !== t && (this._lightsEnabled = t,
            this.markAllMaterialsAsDirty(2))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "activeCamera", {
        get: function() {
            return this._activeCamera
        },
        set: function(t) {
            t !== this._activeCamera && (this._activeCamera = t,
            this.onActiveCameraChanged.notifyObservers(this))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "defaultMaterial", {
        get: function() {
            return this._defaultMaterial || (this._defaultMaterial = e.DefaultMaterialFactory(this)),
            this._defaultMaterial
        },
        set: function(t) {
            this._defaultMaterial = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "texturesEnabled", {
        get: function() {
            return this._texturesEnabled
        },
        set: function(t) {
            this._texturesEnabled !== t && (this._texturesEnabled = t,
            this.markAllMaterialsAsDirty(1))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "skeletonsEnabled", {
        get: function() {
            return this._skeletonsEnabled
        },
        set: function(t) {
            this._skeletonsEnabled !== t && (this._skeletonsEnabled = t,
            this.markAllMaterialsAsDirty(8))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "collisionCoordinator", {
        get: function() {
            return this._collisionCoordinator || (this._collisionCoordinator = e.CollisionCoordinatorFactory(),
            this._collisionCoordinator.init(this)),
            this._collisionCoordinator
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "frustumPlanes", {
        get: function() {
            return this._frustumPlanes
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._registerTransientComponents = function() {
        if (this._transientComponents.length > 0) {
            for (var t = 0, r = this._transientComponents; t < r.length; t++) {
                var n = r[t];
                n.register()
            }
            this._transientComponents = []
        }
    }
    ,
    e.prototype._addComponent = function(t) {
        this._components.push(t),
        this._transientComponents.push(t);
        var r = t;
        r.addFromContainer && r.serialize && this._serializableComponents.push(r)
    }
    ,
    e.prototype._getComponent = function(t) {
        for (var r = 0, n = this._components; r < n.length; r++) {
            var o = n[r];
            if (o.name === t)
                return o
        }
        return null
    }
    ,
    e.prototype.getClassName = function() {
        return "Scene"
    }
    ,
    e.prototype._getDefaultMeshCandidates = function() {
        return this._defaultMeshCandidates.data = this.meshes,
        this._defaultMeshCandidates.length = this.meshes.length,
        this._defaultMeshCandidates
    }
    ,
    e.prototype._getDefaultSubMeshCandidates = function(t) {
        return this._defaultSubMeshCandidates.data = t.subMeshes,
        this._defaultSubMeshCandidates.length = t.subMeshes.length,
        this._defaultSubMeshCandidates
    }
    ,
    e.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(e.prototype, "meshUnderPointer", {
        get: function() {
            return this._inputManager.meshUnderPointer
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "pointerX", {
        get: function() {
            return this._inputManager.pointerX
        },
        set: function(t) {
            this._inputManager.pointerX = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "pointerY", {
        get: function() {
            return this._inputManager.pointerY
        },
        set: function(t) {
            this._inputManager.pointerY = t
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getCachedMaterial = function() {
        return this._cachedMaterial
    }
    ,
    e.prototype.getCachedEffect = function() {
        return this._cachedEffect
    }
    ,
    e.prototype.getCachedVisibility = function() {
        return this._cachedVisibility
    }
    ,
    e.prototype.isCachedMaterialInvalid = function(t, r, n) {
        return n === void 0 && (n = 1),
        this._cachedEffect !== r || this._cachedMaterial !== t || this._cachedVisibility !== n
    }
    ,
    e.prototype.getEngine = function() {
        return this._engine
    }
    ,
    e.prototype.getTotalVertices = function() {
        return this._totalVertices.current
    }
    ,
    Object.defineProperty(e.prototype, "totalVerticesPerfCounter", {
        get: function() {
            return this._totalVertices
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getActiveIndices = function() {
        return this._activeIndices.current
    }
    ,
    Object.defineProperty(e.prototype, "totalActiveIndicesPerfCounter", {
        get: function() {
            return this._activeIndices
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getActiveParticles = function() {
        return this._activeParticles.current
    }
    ,
    Object.defineProperty(e.prototype, "activeParticlesPerfCounter", {
        get: function() {
            return this._activeParticles
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getActiveBones = function() {
        return this._activeBones.current
    }
    ,
    Object.defineProperty(e.prototype, "activeBonesPerfCounter", {
        get: function() {
            return this._activeBones
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getActiveMeshes = function() {
        return this._activeMeshes
    }
    ,
    e.prototype.getAnimationRatio = function() {
        return this._animationRatio !== void 0 ? this._animationRatio : 1
    }
    ,
    e.prototype.getRenderId = function() {
        return this._renderId
    }
    ,
    e.prototype.getFrameId = function() {
        return this._frameId
    }
    ,
    e.prototype.incrementRenderId = function() {
        this._renderId++
    }
    ,
    e.prototype._createUbo = function() {
        this.setSceneUniformBuffer(this.createSceneUniformBuffer())
    }
    ,
    e.prototype.simulatePointerMove = function(t, r) {
        return this._inputManager.simulatePointerMove(t, r),
        this
    }
    ,
    e.prototype.simulatePointerDown = function(t, r) {
        return this._inputManager.simulatePointerDown(t, r),
        this
    }
    ,
    e.prototype.simulatePointerUp = function(t, r, n) {
        return this._inputManager.simulatePointerUp(t, r, n),
        this
    }
    ,
    e.prototype.isPointerCaptured = function(t) {
        return t === void 0 && (t = 0),
        this._inputManager.isPointerCaptured(t)
    }
    ,
    e.prototype.attachControl = function(t, r, n) {
        t === void 0 && (t = !0),
        r === void 0 && (r = !0),
        n === void 0 && (n = !0),
        this._inputManager.attachControl(t, r, n)
    }
    ,
    e.prototype.detachControl = function() {
        this._inputManager.detachControl()
    }
    ,
    e.prototype.isReady = function(t) {
        if (t === void 0 && (t = !0),
        this._isDisposed)
            return !1;
        var r, n = this.getEngine();
        if (!n.areAllEffectsReady() || this._pendingData.length > 0)
            return !1;
        for (t && (this._processedMaterials.reset(),
        this._renderTargets.reset()),
        r = 0; r < this.meshes.length; r++) {
            var o = this.meshes[r];
            if (!!o.isEnabled() && !(!o.subMeshes || o.subMeshes.length === 0)) {
                if (!o.isReady(!0))
                    return !1;
                for (var a = o.hasThinInstances || o.getClassName() === "InstancedMesh" || o.getClassName() === "InstancedLinesMesh" || n.getCaps().instancedArrays && o.instances.length > 0, s = 0, l = this._isReadyForMeshStage; s < l.length; s++) {
                    var u = l[s];
                    if (!u.action(o, a))
                        return !1
                }
                if (!!t) {
                    var c = o.material || this.defaultMaterial;
                    if (c)
                        if (c._storeEffectOnSubMeshes)
                            for (var h = 0, f = o.subMeshes; h < f.length; h++) {
                                var d = f[h]
                                  , _ = d.getMaterial();
                                _ && _.hasRenderTargetTextures && _.getRenderTargetTextures != null && this._processedMaterials.indexOf(_) === -1 && (this._processedMaterials.push(_),
                                this._renderTargets.concatWithNoDuplicate(_.getRenderTargetTextures()))
                            }
                        else
                            c.hasRenderTargetTextures && c.getRenderTargetTextures != null && this._processedMaterials.indexOf(c) === -1 && (this._processedMaterials.push(c),
                            this._renderTargets.concatWithNoDuplicate(c.getRenderTargetTextures()))
                }
            }
        }
        if (t)
            for (r = 0; r < this._renderTargets.length; ++r) {
                var g = this._renderTargets.data[r];
                if (!g.isReadyForRendering())
                    return !1
            }
        for (r = 0; r < this.geometries.length; r++) {
            var m = this.geometries[r];
            if (m.delayLoadState === 2)
                return !1
        }
        if (this.activeCameras && this.activeCameras.length > 0)
            for (var v = 0, y = this.activeCameras; v < y.length; v++) {
                var b = y[v];
                if (!b.isReady(!0))
                    return !1
            }
        else if (this.activeCamera && !this.activeCamera.isReady(!0))
            return !1;
        for (var T = 0, C = this.particleSystems; T < C.length; T++) {
            var A = C[T];
            if (!A.isReady())
                return !1
        }
        return !0
    }
    ,
    e.prototype.resetCachedMaterial = function() {
        this._cachedMaterial = null,
        this._cachedEffect = null,
        this._cachedVisibility = null
    }
    ,
    e.prototype.registerBeforeRender = function(t) {
        this.onBeforeRenderObservable.add(t)
    }
    ,
    e.prototype.unregisterBeforeRender = function(t) {
        this.onBeforeRenderObservable.removeCallback(t)
    }
    ,
    e.prototype.registerAfterRender = function(t) {
        this.onAfterRenderObservable.add(t)
    }
    ,
    e.prototype.unregisterAfterRender = function(t) {
        this.onAfterRenderObservable.removeCallback(t)
    }
    ,
    e.prototype._executeOnceBeforeRender = function(t) {
        var r = this
          , n = function() {
            t(),
            setTimeout(function() {
                r.unregisterBeforeRender(n)
            })
        };
        this.registerBeforeRender(n)
    }
    ,
    e.prototype.executeOnceBeforeRender = function(t, r) {
        var n = this;
        r !== void 0 ? setTimeout(function() {
            n._executeOnceBeforeRender(t)
        }, r) : this._executeOnceBeforeRender(t)
    }
    ,
    e.prototype._addPendingData = function(t) {
        this._pendingData.push(t)
    }
    ,
    e.prototype._removePendingData = function(t) {
        var r = this.isLoading
          , n = this._pendingData.indexOf(t);
        n !== -1 && this._pendingData.splice(n, 1),
        r && !this.isLoading && this.onDataLoadedObservable.notifyObservers(this)
    }
    ,
    e.prototype.getWaitingItemsCount = function() {
        return this._pendingData.length
    }
    ,
    Object.defineProperty(e.prototype, "isLoading", {
        get: function() {
            return this._pendingData.length > 0
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.executeWhenReady = function(t, r) {
        var n = this;
        r === void 0 && (r = !1),
        this.onReadyObservable.add(t),
        this._executeWhenReadyTimeoutId === -1 && (this._executeWhenReadyTimeoutId = setTimeout(function() {
            n._checkIsReady(r)
        }, 150))
    }
    ,
    e.prototype.whenReadyAsync = function(t) {
        var r = this;
        return t === void 0 && (t = !1),
        new Promise(function(n) {
            r.executeWhenReady(function() {
                n()
            }, t)
        }
        )
    }
    ,
    e.prototype._checkIsReady = function(t) {
        var r = this;
        if (t === void 0 && (t = !1),
        this._registerTransientComponents(),
        this.isReady(t)) {
            this.onReadyObservable.notifyObservers(this),
            this.onReadyObservable.clear(),
            this._executeWhenReadyTimeoutId = -1;
            return
        }
        if (this._isDisposed) {
            this.onReadyObservable.clear(),
            this._executeWhenReadyTimeoutId = -1;
            return
        }
        this._executeWhenReadyTimeoutId = setTimeout(function() {
            r._checkIsReady(t)
        }, 150)
    }
    ,
    Object.defineProperty(e.prototype, "animatables", {
        get: function() {
            return this._activeAnimatables
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.resetLastAnimationTimeFrame = function() {
        this._animationTimeLast = PrecisionDate.Now
    }
    ,
    e.prototype.getViewMatrix = function() {
        return this._viewMatrix
    }
    ,
    e.prototype.getProjectionMatrix = function() {
        return this._projectionMatrix
    }
    ,
    e.prototype.getTransformMatrix = function() {
        return this._transformMatrix
    }
    ,
    e.prototype.setTransformMatrix = function(t, r, n, o) {
        this._viewUpdateFlag === t.updateFlag && this._projectionUpdateFlag === r.updateFlag || (this._viewUpdateFlag = t.updateFlag,
        this._projectionUpdateFlag = r.updateFlag,
        this._viewMatrix = t,
        this._projectionMatrix = r,
        this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix),
        this._frustumPlanes ? Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes) : this._frustumPlanes = Frustum.GetPlanes(this._transformMatrix),
        this._multiviewSceneUbo && this._multiviewSceneUbo.useUbo ? this._updateMultiviewUbo(n, o) : this._sceneUbo.useUbo && (this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix),
        this._sceneUbo.updateMatrix("view", this._viewMatrix),
        this._sceneUbo.updateMatrix("projection", this._projectionMatrix)))
    }
    ,
    e.prototype.getSceneUniformBuffer = function() {
        return this._multiviewSceneUbo ? this._multiviewSceneUbo : this._sceneUbo
    }
    ,
    e.prototype.createSceneUniformBuffer = function(t) {
        var r = new UniformBuffer(this._engine,void 0,!1,t != null ? t : "scene");
        return r.addUniform("viewProjection", 16),
        r.addUniform("view", 16),
        r.addUniform("projection", 16),
        r.addUniform("vEyePosition", 4),
        r
    }
    ,
    e.prototype.setSceneUniformBuffer = function(t) {
        this._sceneUbo = t,
        this._viewUpdateFlag = -1,
        this._projectionUpdateFlag = -1
    }
    ,
    e.prototype.getUniqueId = function() {
        return UniqueIdGenerator.UniqueId
    }
    ,
    e.prototype.addMesh = function(t, r) {
        var n = this;
        r === void 0 && (r = !1),
        !this._blockEntityCollection && (this.meshes.push(t),
        t._resyncLightSources(),
        t.parent || t._addToSceneRootNodes(),
        this.onNewMeshAddedObservable.notifyObservers(t),
        r && t.getChildMeshes().forEach(function(o) {
            n.addMesh(o)
        }))
    }
    ,
    e.prototype.removeMesh = function(t, r) {
        var n = this;
        r === void 0 && (r = !1);
        var o = this.meshes.indexOf(t);
        return o !== -1 && (this.meshes[o] = this.meshes[this.meshes.length - 1],
        this.meshes.pop(),
        t.parent || t._removeFromSceneRootNodes()),
        this._inputManager._invalidateMesh(t),
        this.onMeshRemovedObservable.notifyObservers(t),
        r && t.getChildMeshes().forEach(function(a) {
            n.removeMesh(a)
        }),
        o
    }
    ,
    e.prototype.addTransformNode = function(t) {
        this._blockEntityCollection || (t._indexInSceneTransformNodesArray = this.transformNodes.length,
        this.transformNodes.push(t),
        t.parent || t._addToSceneRootNodes(),
        this.onNewTransformNodeAddedObservable.notifyObservers(t))
    }
    ,
    e.prototype.removeTransformNode = function(t) {
        var r = t._indexInSceneTransformNodesArray;
        if (r !== -1) {
            if (r !== this.transformNodes.length - 1) {
                var n = this.transformNodes[this.transformNodes.length - 1];
                this.transformNodes[r] = n,
                n._indexInSceneTransformNodesArray = r
            }
            t._indexInSceneTransformNodesArray = -1,
            this.transformNodes.pop(),
            t.parent || t._removeFromSceneRootNodes()
        }
        return this.onTransformNodeRemovedObservable.notifyObservers(t),
        r
    }
    ,
    e.prototype.removeSkeleton = function(t) {
        var r = this.skeletons.indexOf(t);
        return r !== -1 && (this.skeletons.splice(r, 1),
        this.onSkeletonRemovedObservable.notifyObservers(t)),
        r
    }
    ,
    e.prototype.removeMorphTargetManager = function(t) {
        var r = this.morphTargetManagers.indexOf(t);
        return r !== -1 && this.morphTargetManagers.splice(r, 1),
        r
    }
    ,
    e.prototype.removeLight = function(t) {
        var r = this.lights.indexOf(t);
        if (r !== -1) {
            for (var n = 0, o = this.meshes; n < o.length; n++) {
                var a = o[n];
                a._removeLightSource(t, !1)
            }
            this.lights.splice(r, 1),
            this.sortLightsByPriority(),
            t.parent || t._removeFromSceneRootNodes()
        }
        return this.onLightRemovedObservable.notifyObservers(t),
        r
    }
    ,
    e.prototype.removeCamera = function(t) {
        var r = this.cameras.indexOf(t);
        if (r !== -1 && (this.cameras.splice(r, 1),
        t.parent || t._removeFromSceneRootNodes()),
        this.activeCameras) {
            var n = this.activeCameras.indexOf(t);
            n !== -1 && this.activeCameras.splice(n, 1)
        }
        return this.activeCamera === t && (this.cameras.length > 0 ? this.activeCamera = this.cameras[0] : this.activeCamera = null),
        this.onCameraRemovedObservable.notifyObservers(t),
        r
    }
    ,
    e.prototype.removeParticleSystem = function(t) {
        var r = this.particleSystems.indexOf(t);
        return r !== -1 && this.particleSystems.splice(r, 1),
        r
    }
    ,
    e.prototype.removeAnimation = function(t) {
        var r = this.animations.indexOf(t);
        return r !== -1 && this.animations.splice(r, 1),
        r
    }
    ,
    e.prototype.stopAnimation = function(t, r, n) {}
    ,
    e.prototype.removeAnimationGroup = function(t) {
        var r = this.animationGroups.indexOf(t);
        return r !== -1 && this.animationGroups.splice(r, 1),
        r
    }
    ,
    e.prototype.removeMultiMaterial = function(t) {
        var r = this.multiMaterials.indexOf(t);
        return r !== -1 && this.multiMaterials.splice(r, 1),
        this.onMultiMaterialRemovedObservable.notifyObservers(t),
        r
    }
    ,
    e.prototype.removeMaterial = function(t) {
        var r = t._indexInSceneMaterialArray;
        if (r !== -1 && r < this.materials.length) {
            if (r !== this.materials.length - 1) {
                var n = this.materials[this.materials.length - 1];
                this.materials[r] = n,
                n._indexInSceneMaterialArray = r
            }
            t._indexInSceneMaterialArray = -1,
            this.materials.pop()
        }
        return this.onMaterialRemovedObservable.notifyObservers(t),
        r
    }
    ,
    e.prototype.removeActionManager = function(t) {
        var r = this.actionManagers.indexOf(t);
        return r !== -1 && this.actionManagers.splice(r, 1),
        r
    }
    ,
    e.prototype.removeTexture = function(t) {
        var r = this.textures.indexOf(t);
        return r !== -1 && this.textures.splice(r, 1),
        this.onTextureRemovedObservable.notifyObservers(t),
        r
    }
    ,
    e.prototype.addLight = function(t) {
        if (!this._blockEntityCollection) {
            this.lights.push(t),
            this.sortLightsByPriority(),
            t.parent || t._addToSceneRootNodes();
            for (var r = 0, n = this.meshes; r < n.length; r++) {
                var o = n[r];
                o.lightSources.indexOf(t) === -1 && (o.lightSources.push(t),
                o._resyncLightSources())
            }
            this.onNewLightAddedObservable.notifyObservers(t)
        }
    }
    ,
    e.prototype.sortLightsByPriority = function() {
        this.requireLightSorting && this.lights.sort(LightConstants.CompareLightsPriority)
    }
    ,
    e.prototype.addCamera = function(t) {
        this._blockEntityCollection || (this.cameras.push(t),
        this.onNewCameraAddedObservable.notifyObservers(t),
        t.parent || t._addToSceneRootNodes())
    }
    ,
    e.prototype.addSkeleton = function(t) {
        this._blockEntityCollection || (this.skeletons.push(t),
        this.onNewSkeletonAddedObservable.notifyObservers(t))
    }
    ,
    e.prototype.addParticleSystem = function(t) {
        this._blockEntityCollection || this.particleSystems.push(t)
    }
    ,
    e.prototype.addAnimation = function(t) {
        this._blockEntityCollection || this.animations.push(t)
    }
    ,
    e.prototype.addAnimationGroup = function(t) {
        this._blockEntityCollection || this.animationGroups.push(t)
    }
    ,
    e.prototype.addMultiMaterial = function(t) {
        this._blockEntityCollection || (this.multiMaterials.push(t),
        this.onNewMultiMaterialAddedObservable.notifyObservers(t))
    }
    ,
    e.prototype.addMaterial = function(t) {
        this._blockEntityCollection || (t._indexInSceneMaterialArray = this.materials.length,
        this.materials.push(t),
        this.onNewMaterialAddedObservable.notifyObservers(t))
    }
    ,
    e.prototype.addMorphTargetManager = function(t) {
        this._blockEntityCollection || this.morphTargetManagers.push(t)
    }
    ,
    e.prototype.addGeometry = function(t) {
        this._blockEntityCollection || (this.geometriesByUniqueId && (this.geometriesByUniqueId[t.uniqueId] = this.geometries.length),
        this.geometries.push(t))
    }
    ,
    e.prototype.addActionManager = function(t) {
        this.actionManagers.push(t)
    }
    ,
    e.prototype.addTexture = function(t) {
        this._blockEntityCollection || (this.textures.push(t),
        this.onNewTextureAddedObservable.notifyObservers(t))
    }
    ,
    e.prototype.switchActiveCamera = function(t, r) {
        r === void 0 && (r = !0);
        var n = this._engine.getInputElement();
        !n || (this.activeCamera && this.activeCamera.detachControl(),
        this.activeCamera = t,
        r && t.attachControl())
    }
    ,
    e.prototype.setActiveCameraById = function(t) {
        var r = this.getCameraById(t);
        return r ? (this.activeCamera = r,
        r) : null
    }
    ,
    e.prototype.setActiveCameraByName = function(t) {
        var r = this.getCameraByName(t);
        return r ? (this.activeCamera = r,
        r) : null
    }
    ,
    e.prototype.getAnimationGroupByName = function(t) {
        for (var r = 0; r < this.animationGroups.length; r++)
            if (this.animationGroups[r].name === t)
                return this.animationGroups[r];
        return null
    }
    ,
    e.prototype.getMaterialByUniqueID = function(t) {
        for (var r = 0; r < this.materials.length; r++)
            if (this.materials[r].uniqueId === t)
                return this.materials[r];
        return null
    }
    ,
    e.prototype.getMaterialById = function(t) {
        for (var r = 0; r < this.materials.length; r++)
            if (this.materials[r].id === t)
                return this.materials[r];
        return null
    }
    ,
    e.prototype.getLastMaterialById = function(t) {
        for (var r = this.materials.length - 1; r >= 0; r--)
            if (this.materials[r].id === t)
                return this.materials[r];
        return null
    }
    ,
    e.prototype.getMaterialByName = function(t) {
        for (var r = 0; r < this.materials.length; r++)
            if (this.materials[r].name === t)
                return this.materials[r];
        return null
    }
    ,
    e.prototype.getTextureByUniqueId = function(t) {
        for (var r = 0; r < this.textures.length; r++)
            if (this.textures[r].uniqueId === t)
                return this.textures[r];
        return null
    }
    ,
    e.prototype.getTextureByName = function(t) {
        for (var r = 0; r < this.textures.length; r++)
            if (this.textures[r].name === t)
                return this.textures[r];
        return null
    }
    ,
    e.prototype.getCameraById = function(t) {
        for (var r = 0; r < this.cameras.length; r++)
            if (this.cameras[r].id === t)
                return this.cameras[r];
        return null
    }
    ,
    e.prototype.getCameraByUniqueId = function(t) {
        for (var r = 0; r < this.cameras.length; r++)
            if (this.cameras[r].uniqueId === t)
                return this.cameras[r];
        return null
    }
    ,
    e.prototype.getCameraByName = function(t) {
        for (var r = 0; r < this.cameras.length; r++)
            if (this.cameras[r].name === t)
                return this.cameras[r];
        return null
    }
    ,
    e.prototype.getBoneById = function(t) {
        for (var r = 0; r < this.skeletons.length; r++)
            for (var n = this.skeletons[r], o = 0; o < n.bones.length; o++)
                if (n.bones[o].id === t)
                    return n.bones[o];
        return null
    }
    ,
    e.prototype.getBoneByName = function(t) {
        for (var r = 0; r < this.skeletons.length; r++)
            for (var n = this.skeletons[r], o = 0; o < n.bones.length; o++)
                if (n.bones[o].name === t)
                    return n.bones[o];
        return null
    }
    ,
    e.prototype.getLightByName = function(t) {
        for (var r = 0; r < this.lights.length; r++)
            if (this.lights[r].name === t)
                return this.lights[r];
        return null
    }
    ,
    e.prototype.getLightById = function(t) {
        for (var r = 0; r < this.lights.length; r++)
            if (this.lights[r].id === t)
                return this.lights[r];
        return null
    }
    ,
    e.prototype.getLightByUniqueId = function(t) {
        for (var r = 0; r < this.lights.length; r++)
            if (this.lights[r].uniqueId === t)
                return this.lights[r];
        return null
    }
    ,
    e.prototype.getParticleSystemById = function(t) {
        for (var r = 0; r < this.particleSystems.length; r++)
            if (this.particleSystems[r].id === t)
                return this.particleSystems[r];
        return null
    }
    ,
    e.prototype.getGeometryById = function(t) {
        for (var r = 0; r < this.geometries.length; r++)
            if (this.geometries[r].id === t)
                return this.geometries[r];
        return null
    }
    ,
    e.prototype._getGeometryByUniqueId = function(t) {
        if (this.geometriesByUniqueId) {
            var r = this.geometriesByUniqueId[t];
            if (r !== void 0)
                return this.geometries[r]
        } else
            for (var n = 0; n < this.geometries.length; n++)
                if (this.geometries[n].uniqueId === t)
                    return this.geometries[n];
        return null
    }
    ,
    e.prototype.pushGeometry = function(t, r) {
        return !r && this._getGeometryByUniqueId(t.uniqueId) ? !1 : (this.addGeometry(t),
        this.onNewGeometryAddedObservable.notifyObservers(t),
        !0)
    }
    ,
    e.prototype.removeGeometry = function(t) {
        var r;
        if (this.geometriesByUniqueId) {
            if (r = this.geometriesByUniqueId[t.uniqueId],
            r === void 0)
                return !1
        } else if (r = this.geometries.indexOf(t),
        r < 0)
            return !1;
        if (r !== this.geometries.length - 1) {
            var n = this.geometries[this.geometries.length - 1];
            n && (this.geometries[r] = n,
            this.geometriesByUniqueId && (this.geometriesByUniqueId[n.uniqueId] = r,
            this.geometriesByUniqueId[t.uniqueId] = void 0))
        }
        return this.geometries.pop(),
        this.onGeometryRemovedObservable.notifyObservers(t),
        !0
    }
    ,
    e.prototype.getGeometries = function() {
        return this.geometries
    }
    ,
    e.prototype.getMeshById = function(t) {
        for (var r = 0; r < this.meshes.length; r++)
            if (this.meshes[r].id === t)
                return this.meshes[r];
        return null
    }
    ,
    e.prototype.getMeshesById = function(t) {
        return this.meshes.filter(function(r) {
            return r.id === t
        })
    }
    ,
    e.prototype.getTransformNodeById = function(t) {
        for (var r = 0; r < this.transformNodes.length; r++)
            if (this.transformNodes[r].id === t)
                return this.transformNodes[r];
        return null
    }
    ,
    e.prototype.getTransformNodeByUniqueId = function(t) {
        for (var r = 0; r < this.transformNodes.length; r++)
            if (this.transformNodes[r].uniqueId === t)
                return this.transformNodes[r];
        return null
    }
    ,
    e.prototype.getTransformNodesById = function(t) {
        return this.transformNodes.filter(function(r) {
            return r.id === t
        })
    }
    ,
    e.prototype.getMeshByUniqueId = function(t) {
        for (var r = 0; r < this.meshes.length; r++)
            if (this.meshes[r].uniqueId === t)
                return this.meshes[r];
        return null
    }
    ,
    e.prototype.getLastMeshById = function(t) {
        for (var r = this.meshes.length - 1; r >= 0; r--)
            if (this.meshes[r].id === t)
                return this.meshes[r];
        return null
    }
    ,
    e.prototype.getLastEntryById = function(t) {
        var r;
        for (r = this.meshes.length - 1; r >= 0; r--)
            if (this.meshes[r].id === t)
                return this.meshes[r];
        for (r = this.transformNodes.length - 1; r >= 0; r--)
            if (this.transformNodes[r].id === t)
                return this.transformNodes[r];
        for (r = this.cameras.length - 1; r >= 0; r--)
            if (this.cameras[r].id === t)
                return this.cameras[r];
        for (r = this.lights.length - 1; r >= 0; r--)
            if (this.lights[r].id === t)
                return this.lights[r];
        return null
    }
    ,
    e.prototype.getNodeById = function(t) {
        var r = this.getMeshById(t);
        if (r)
            return r;
        var n = this.getTransformNodeById(t);
        if (n)
            return n;
        var o = this.getLightById(t);
        if (o)
            return o;
        var a = this.getCameraById(t);
        if (a)
            return a;
        var s = this.getBoneById(t);
        return s || null
    }
    ,
    e.prototype.getNodeByName = function(t) {
        var r = this.getMeshByName(t);
        if (r)
            return r;
        var n = this.getTransformNodeByName(t);
        if (n)
            return n;
        var o = this.getLightByName(t);
        if (o)
            return o;
        var a = this.getCameraByName(t);
        if (a)
            return a;
        var s = this.getBoneByName(t);
        return s || null
    }
    ,
    e.prototype.getMeshByName = function(t) {
        for (var r = 0; r < this.meshes.length; r++)
            if (this.meshes[r].name === t)
                return this.meshes[r];
        return null
    }
    ,
    e.prototype.getTransformNodeByName = function(t) {
        for (var r = 0; r < this.transformNodes.length; r++)
            if (this.transformNodes[r].name === t)
                return this.transformNodes[r];
        return null
    }
    ,
    e.prototype.getLastSkeletonById = function(t) {
        for (var r = this.skeletons.length - 1; r >= 0; r--)
            if (this.skeletons[r].id === t)
                return this.skeletons[r];
        return null
    }
    ,
    e.prototype.getSkeletonByUniqueId = function(t) {
        for (var r = 0; r < this.skeletons.length; r++)
            if (this.skeletons[r].uniqueId === t)
                return this.skeletons[r];
        return null
    }
    ,
    e.prototype.getSkeletonById = function(t) {
        for (var r = 0; r < this.skeletons.length; r++)
            if (this.skeletons[r].id === t)
                return this.skeletons[r];
        return null
    }
    ,
    e.prototype.getSkeletonByName = function(t) {
        for (var r = 0; r < this.skeletons.length; r++)
            if (this.skeletons[r].name === t)
                return this.skeletons[r];
        return null
    }
    ,
    e.prototype.getMorphTargetManagerById = function(t) {
        for (var r = 0; r < this.morphTargetManagers.length; r++)
            if (this.morphTargetManagers[r].uniqueId === t)
                return this.morphTargetManagers[r];
        return null
    }
    ,
    e.prototype.getMorphTargetById = function(t) {
        for (var r = 0; r < this.morphTargetManagers.length; ++r)
            for (var n = this.morphTargetManagers[r], o = 0; o < n.numTargets; ++o) {
                var a = n.getTarget(o);
                if (a.id === t)
                    return a
            }
        return null
    }
    ,
    e.prototype.getMorphTargetByName = function(t) {
        for (var r = 0; r < this.morphTargetManagers.length; ++r)
            for (var n = this.morphTargetManagers[r], o = 0; o < n.numTargets; ++o) {
                var a = n.getTarget(o);
                if (a.name === t)
                    return a
            }
        return null
    }
    ,
    e.prototype.getPostProcessByName = function(t) {
        for (var r = 0; r < this.postProcesses.length; ++r) {
            var n = this.postProcesses[r];
            if (n.name === t)
                return n
        }
        return null
    }
    ,
    e.prototype.isActiveMesh = function(t) {
        return this._activeMeshes.indexOf(t) !== -1
    }
    ,
    Object.defineProperty(e.prototype, "uid", {
        get: function() {
            return this._uid || (this._uid = Tools.RandomId()),
            this._uid
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.addExternalData = function(t, r) {
        return this._externalData || (this._externalData = new StringDictionary),
        this._externalData.add(t, r)
    }
    ,
    e.prototype.getExternalData = function(t) {
        return this._externalData ? this._externalData.get(t) : null
    }
    ,
    e.prototype.getOrAddExternalDataWithFactory = function(t, r) {
        return this._externalData || (this._externalData = new StringDictionary),
        this._externalData.getOrAddWithFactory(t, r)
    }
    ,
    e.prototype.removeExternalData = function(t) {
        return this._externalData.remove(t)
    }
    ,
    e.prototype._evaluateSubMesh = function(t, r, n) {
        if (n.hasInstances || n.isAnInstance || this.dispatchAllSubMeshesOfActiveMeshes || this._skipFrustumClipping || r.alwaysSelectAsActiveMesh || r.subMeshes.length === 1 || t.isInFrustum(this._frustumPlanes)) {
            for (var o = 0, a = this._evaluateSubMeshStage; o < a.length; o++) {
                var s = a[o];
                s.action(r, t)
            }
            var l = t.getMaterial();
            l != null && (l.hasRenderTargetTextures && l.getRenderTargetTextures != null && this._processedMaterials.indexOf(l) === -1 && (this._processedMaterials.push(l),
            this._renderTargets.concatWithNoDuplicate(l.getRenderTargetTextures())),
            this._renderingManager.dispatch(t, r, l))
        }
    }
    ,
    e.prototype.freeProcessedMaterials = function() {
        this._processedMaterials.dispose()
    }
    ,
    Object.defineProperty(e.prototype, "blockfreeActiveMeshesAndRenderingGroups", {
        get: function() {
            return this._preventFreeActiveMeshesAndRenderingGroups
        },
        set: function(t) {
            this._preventFreeActiveMeshesAndRenderingGroups !== t && (t && (this.freeActiveMeshes(),
            this.freeRenderingGroups()),
            this._preventFreeActiveMeshesAndRenderingGroups = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.freeActiveMeshes = function() {
        if (!this.blockfreeActiveMeshesAndRenderingGroups && (this._activeMeshes.dispose(),
        this.activeCamera && this.activeCamera._activeMeshes && this.activeCamera._activeMeshes.dispose(),
        this.activeCameras))
            for (var t = 0; t < this.activeCameras.length; t++) {
                var r = this.activeCameras[t];
                r && r._activeMeshes && r._activeMeshes.dispose()
            }
    }
    ,
    e.prototype.freeRenderingGroups = function() {
        if (!this.blockfreeActiveMeshesAndRenderingGroups && (this._renderingManager && this._renderingManager.freeRenderingGroups(),
        this.textures))
            for (var t = 0; t < this.textures.length; t++) {
                var r = this.textures[t];
                r && r.renderList && r.freeRenderingGroups()
            }
    }
    ,
    e.prototype._isInIntermediateRendering = function() {
        return this._intermediateRendering
    }
    ,
    e.prototype.freezeActiveMeshes = function(t, r, n, o) {
        var a = this;
        return t === void 0 && (t = !1),
        o === void 0 && (o = !0),
        this.executeWhenReady(function() {
            if (!a.activeCamera) {
                n && n("No active camera found");
                return
            }
            if (a._frustumPlanes || a.setTransformMatrix(a.activeCamera.getViewMatrix(), a.activeCamera.getProjectionMatrix()),
            a._evaluateActiveMeshes(),
            a._activeMeshesFrozen = !0,
            a._skipEvaluateActiveMeshesCompletely = t,
            o)
                for (var s = 0; s < a._activeMeshes.length; s++)
                    a._activeMeshes.data[s]._freeze();
            r && r()
        }),
        this
    }
    ,
    e.prototype.unfreezeActiveMeshes = function() {
        for (var t = 0; t < this.meshes.length; t++) {
            var r = this.meshes[t];
            r._internalAbstractMeshDataInfo && (r._internalAbstractMeshDataInfo._isActive = !1)
        }
        for (var t = 0; t < this._activeMeshes.length; t++)
            this._activeMeshes.data[t]._unFreeze();
        return this._activeMeshesFrozen = !1,
        this
    }
    ,
    e.prototype._evaluateActiveMeshes = function() {
        var t;
        if (this._engine.snapshotRendering && this._engine.snapshotRenderingMode === 1) {
            this._activeMeshes.length > 0 && ((t = this.activeCamera) === null || t === void 0 || t._activeMeshes.reset(),
            this._activeMeshes.reset(),
            this._renderingManager.reset(),
            this._processedMaterials.reset(),
            this._activeParticleSystems.reset(),
            this._activeSkeletons.reset(),
            this._softwareSkinnedMeshes.reset());
            return
        }
        if (this._activeMeshesFrozen && this._activeMeshes.length) {
            if (!this._skipEvaluateActiveMeshesCompletely)
                for (var r = this._activeMeshes.length, n = 0; n < r; n++) {
                    var o = this._activeMeshes.data[n];
                    o.computeWorldMatrix()
                }
            if (this._activeParticleSystems)
                for (var a = this._activeParticleSystems.length, n = 0; n < a; n++)
                    this._activeParticleSystems.data[n].animate();
            return
        }
        if (!!this.activeCamera) {
            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 s = 0, l = this._beforeEvaluateActiveMeshStage; s < l.length; s++) {
                var u = l[s];
                u.action()
            }
            for (var c = this.getActiveMeshCandidates(), h = c.length, n = 0; n < h; n++) {
                var o = c.data[n];
                if (o._internalAbstractMeshDataInfo._currentLODIsUpToDate = !1,
                !o.isBlocked && (this._totalVertices.addCount(o.getTotalVertices(), !1),
                !(!o.isReady() || !o.isEnabled() || o.scaling.lengthSquared() === 0))) {
                    o.computeWorldMatrix(),
                    o.actionManager && o.actionManager.hasSpecificTriggers2(12, 13) && this._meshesForIntersections.pushNoDuplicate(o);
                    var f = this.customLODSelector ? this.customLODSelector(o, this.activeCamera) : o.getLOD(this.activeCamera);
                    if (o._internalAbstractMeshDataInfo._currentLOD = f,
                    o._internalAbstractMeshDataInfo._currentLODIsUpToDate = !0,
                    f != null && (f !== o && f.billboardMode !== 0 && f.computeWorldMatrix(),
                    o._preActivate(),
                    o.isVisible && o.visibility > 0 && (o.layerMask & this.activeCamera.layerMask) !== 0 && (this._skipFrustumClipping || o.alwaysSelectAsActiveMesh || o.isInFrustum(this._frustumPlanes)))) {
                        this._activeMeshes.push(o),
                        this.activeCamera._activeMeshes.push(o),
                        f !== o && f._activate(this._renderId, !1);
                        for (var d = 0, _ = this._preActiveMeshStage; d < _.length; d++) {
                            var u = _[d];
                            u.action(o)
                        }
                        o._activate(this._renderId, !1) && (o.isAnInstance ? o._internalAbstractMeshDataInfo._actAsRegularMesh && (f = o) : f._internalAbstractMeshDataInfo._onlyForInstances = !1,
                        f._internalAbstractMeshDataInfo._isActive = !0,
                        this._activeMesh(o, f)),
                        o._postActivate()
                    }
                }
            }
            if (this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this),
            this.particlesEnabled) {
                this.onBeforeParticlesRenderingObservable.notifyObservers(this);
                for (var g = 0; g < this.particleSystems.length; g++) {
                    var m = this.particleSystems[g];
                    if (!(!m.isStarted() || !m.emitter)) {
                        var v = m.emitter;
                        (!v.position || v.isEnabled()) && (this._activeParticleSystems.push(m),
                        m.animate(),
                        this._renderingManager.dispatchParticles(m))
                    }
                }
                this.onAfterParticlesRenderingObservable.notifyObservers(this)
            }
        }
    }
    ,
    e.prototype._activeMesh = function(t, r) {
        if (this._skeletonsEnabled && r.skeleton !== null && r.skeleton !== void 0 && (this._activeSkeletons.pushNoDuplicate(r.skeleton) && r.skeleton.prepare(),
        r.computeBonesUsingShaders || this._softwareSkinnedMeshes.pushNoDuplicate(r)),
        r != null && r.subMeshes !== void 0 && r.subMeshes !== null && r.subMeshes.length > 0)
            for (var n = this.getActiveSubMeshCandidates(r), o = n.length, a = 0; a < o; a++) {
                var s = n.data[a];
                this._evaluateSubMesh(s, r, t)
            }
    }
    ,
    e.prototype.updateTransformMatrix = function(t) {
        !this.activeCamera || this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(t))
    }
    ,
    e.prototype._bindFrameBuffer = function(t, r) {
        r === void 0 && (r = !0),
        t && t._multiviewTexture ? t._multiviewTexture._bindFrameBuffer() : t && t.outputRenderTarget ? t.outputRenderTarget._bindFrameBuffer() : this._engine._currentFrameBufferIsDefaultFrameBuffer() || this._engine.restoreDefaultFramebuffer(),
        r && this._clearFrameBuffer(t)
    }
    ,
    e.prototype._clearFrameBuffer = function(t) {
        if (!(t && t._multiviewTexture))
            if (t && t.outputRenderTarget) {
                var r = t.outputRenderTarget;
                r.onClearObservable.hasObservers() ? r.onClearObservable.notifyObservers(this._engine) : r.skipInitialClear || (this._engine.clear(r.clearColor || this.clearColor, !r._cleared, !0, !0),
                r._cleared = !0)
            } else
                this._defaultFrameBufferCleared ? this._engine.clear(null, !1, !0, !0) : (this._defaultFrameBufferCleared = !0,
                this._clear())
    }
    ,
    e.prototype._renderForCamera = function(t, r, n) {
        var o, a, s;
        if (n === void 0 && (n = !0),
        !(t && t._skipRendering)) {
            var l = this._engine;
            if (this._activeCamera = t,
            !this.activeCamera)
                throw new Error("Active camera not set");
            l.setViewport(this.activeCamera.viewport),
            this.resetCachedMaterial(),
            this._renderId++,
            !this.prePass && n && this._bindFrameBuffer(this._activeCamera);
            var u = this.getEngine().getCaps().multiview && t.outputRenderTarget && t.outputRenderTarget.getViewCount() > 1;
            u ? this.setTransformMatrix(t._rigCameras[0].getViewMatrix(), t._rigCameras[0].getProjectionMatrix(), t._rigCameras[1].getViewMatrix(), t._rigCameras[1].getProjectionMatrix()) : this.updateTransformMatrix(),
            this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera),
            this._evaluateActiveMeshes();
            for (var c = 0; c < this._softwareSkinnedMeshes.length; c++) {
                var h = this._softwareSkinnedMeshes.data[c];
                h.applySkeleton(h.skeleton)
            }
            this.onBeforeRenderTargetsRenderObservable.notifyObservers(this),
            t.customRenderTargets && t.customRenderTargets.length > 0 && this._renderTargets.concatWithNoDuplicate(t.customRenderTargets),
            r && r.customRenderTargets && r.customRenderTargets.length > 0 && this._renderTargets.concatWithNoDuplicate(r.customRenderTargets),
            this.environmentTexture && this.environmentTexture.isRenderTarget && this._renderTargets.pushNoDuplicate(this.environmentTexture);
            for (var f = 0, d = this._gatherActiveCameraRenderTargetsStage; f < d.length; f++) {
                var _ = d[f];
                _.action(this._renderTargets)
            }
            var g = !1;
            if (this.renderTargetsEnabled) {
                if (this._intermediateRendering = !0,
                this._renderTargets.length > 0) {
                    Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
                    for (var m = 0; m < this._renderTargets.length; m++) {
                        var v = this._renderTargets.data[m];
                        if (v._shouldRender()) {
                            this._renderId++;
                            var y = v.activeCamera && v.activeCamera !== this.activeCamera;
                            v.render(y, this.dumpNextRenderTargets),
                            g = !0
                        }
                    }
                    Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0),
                    this._renderId++
                }
                for (var b = 0, T = this._cameraDrawRenderTargetStage; b < T.length; b++) {
                    var _ = T[b];
                    g = _.action(this.activeCamera) || g
                }
                this._intermediateRendering = !1
            }
            this._engine.currentRenderPassId = (s = (a = (o = t.outputRenderTarget) === null || o === void 0 ? void 0 : o.renderPassId) !== null && a !== void 0 ? a : t.renderPassId) !== null && s !== void 0 ? s : 0,
            g && !this.prePass && this._bindFrameBuffer(this._activeCamera, !1),
            this.onAfterRenderTargetsRenderObservable.notifyObservers(this),
            this.postProcessManager && !t._multiviewTexture && !this.prePass && this.postProcessManager._prepareFrame();
            for (var C = 0, A = this._beforeCameraDrawStage; C < A.length; C++) {
                var _ = A[C];
                _.action(this.activeCamera)
            }
            this.onBeforeDrawPhaseObservable.notifyObservers(this),
            l.snapshotRendering && l.snapshotRenderingMode === 1 && this.finalizeSceneUbo(),
            this._renderingManager.render(null, null, !0, !0),
            this.onAfterDrawPhaseObservable.notifyObservers(this);
            for (var S = 0, P = this._afterCameraDrawStage; S < P.length; S++) {
                var _ = P[S];
                _.action(this.activeCamera)
            }
            if (this.postProcessManager && !t._multiviewTexture) {
                var R = t.outputRenderTarget ? t.outputRenderTarget.renderTarget : void 0;
                this.postProcessManager._finalizeFrame(t.isIntermediate, R)
            }
            this._renderTargets.reset(),
            this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera)
        }
    }
    ,
    e.prototype._processSubCameras = function(t, r) {
        if (r === void 0 && (r = !0),
        t.cameraRigMode === 0 || t.outputRenderTarget && t.outputRenderTarget.getViewCount() > 1 && this.getEngine().getCaps().multiview) {
            this._renderForCamera(t, void 0, r),
            this.onAfterRenderCameraObservable.notifyObservers(t);
            return
        }
        if (t._useMultiviewToSingleView)
            this._renderMultiviewToSingleView(t);
        else {
            this.onBeforeCameraRenderObservable.notifyObservers(t);
            for (var n = 0; n < t._rigCameras.length; n++)
                this._renderForCamera(t._rigCameras[n], t)
        }
        this._activeCamera = t,
        this.setTransformMatrix(this._activeCamera.getViewMatrix(), this._activeCamera.getProjectionMatrix()),
        this.onAfterRenderCameraObservable.notifyObservers(t)
    }
    ,
    e.prototype._checkIntersections = function() {
        for (var t = 0; t < this._meshesForIntersections.length; t++) {
            var r = this._meshesForIntersections.data[t];
            if (!!r.actionManager)
                for (var n = 0; r.actionManager && n < r.actionManager.actions.length; n++) {
                    var o = r.actionManager.actions[n];
                    if (o.trigger === 12 || o.trigger === 13) {
                        var a = o.getTriggerParameter()
                          , s = a.mesh ? a.mesh : a
                          , l = s.intersectsMesh(r, a.usePreciseIntersection)
                          , u = r._intersectionsInProgress.indexOf(s);
                        l && u === -1 ? o.trigger === 12 ? (o._executeCurrent(ActionEvent.CreateNew(r, void 0, s)),
                        r._intersectionsInProgress.push(s)) : o.trigger === 13 && r._intersectionsInProgress.push(s) : !l && u > -1 && (o.trigger === 13 && o._executeCurrent(ActionEvent.CreateNew(r, void 0, s)),
                        (!r.actionManager.hasSpecificTrigger(13, function(c) {
                            var h = c.mesh ? c.mesh : c;
                            return s === h
                        }) || o.trigger === 13) && r._intersectionsInProgress.splice(u, 1))
                    }
                }
        }
    }
    ,
    e.prototype._advancePhysicsEngineStep = function(t) {}
    ,
    e.prototype._animate = function() {}
    ,
    e.prototype.animate = function() {
        if (this._engine.isDeterministicLockStep()) {
            var t = Math.max(e.MinDeltaTime, Math.min(this._engine.getDeltaTime(), e.MaxDeltaTime)) + this._timeAccumulator
              , r = this._engine.getTimeStep()
              , n = 1e3 / r / 1e3
              , o = 0
              , a = this._engine.getLockstepMaxSteps()
              , s = Math.floor(t / r);
            for (s = Math.min(s, a); t > 0 && o < s; )
                this.onBeforeStepObservable.notifyObservers(this),
                this._animationRatio = r * n,
                this._animate(),
                this.onAfterAnimationsObservable.notifyObservers(this),
                this.physicsEnabled && this._advancePhysicsEngineStep(r),
                this.onAfterStepObservable.notifyObservers(this),
                this._currentStepId++,
                o++,
                t -= r;
            this._timeAccumulator = t < 0 ? 0 : t
        } else {
            var t = this.useConstantAnimationDeltaTime ? 16 : Math.max(e.MinDeltaTime, Math.min(this._engine.getDeltaTime(), e.MaxDeltaTime));
            this._animationRatio = t * (60 / 1e3),
            this._animate(),
            this.onAfterAnimationsObservable.notifyObservers(this),
            this.physicsEnabled && this._advancePhysicsEngineStep(t)
        }
    }
    ,
    e.prototype._clear = function() {
        (this.autoClearDepthAndStencil || this.autoClear) && this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil)
    }
    ,
    e.prototype.checkCameraRenderTarget = function(t) {
        var r;
        if ((t == null ? void 0 : t.outputRenderTarget) && !(t != null && t.isRigCamera) && (t.outputRenderTarget._cleared = !1),
        !((r = t == null ? void 0 : t.rigCameras) === null || r === void 0) && r.length)
            for (var n = 0; n < t.rigCameras.length; ++n) {
                var o = t.rigCameras[n].outputRenderTarget;
                o && (o._cleared = !1)
            }
    }
    ,
    e.prototype.resetDrawCache = function() {
        if (!!this.meshes)
            for (var t = 0, r = this.meshes; t < r.length; t++) {
                var n = r[t];
                n.resetDrawCache()
            }
    }
    ,
    e.prototype.render = function(t, r) {
        var n, o, a;
        if (t === void 0 && (t = !0),
        r === void 0 && (r = !1),
        !this.isDisposed) {
            this.onReadyObservable.hasObservers() && this._executeWhenReadyTimeoutId === -1 && this._checkIsReady(),
            this._frameId++,
            this._defaultFrameBufferCleared = !1,
            this.checkCameraRenderTarget(this.activeCamera),
            !((n = this.activeCameras) === null || n === void 0) && n.length && this.activeCameras.forEach(this.checkCameraRenderTarget),
            this._registerTransientComponents(),
            this._activeParticles.fetchNewFrame(),
            this._totalVertices.fetchNewFrame(),
            this._activeIndices.fetchNewFrame(),
            this._activeBones.fetchNewFrame(),
            this._meshesForIntersections.reset(),
            this.resetCachedMaterial(),
            this.onBeforeAnimationsObservable.notifyObservers(this),
            this.actionManager && this.actionManager.processTrigger(11),
            r || this.animate();
            for (var s = 0, l = this._beforeCameraUpdateStage; s < l.length; s++) {
                var u = l[s];
                u.action()
            }
            if (t) {
                if (this.activeCameras && this.activeCameras.length > 0)
                    for (var c = 0; c < this.activeCameras.length; c++) {
                        var h = this.activeCameras[c];
                        if (h.update(),
                        h.cameraRigMode !== 0)
                            for (var f = 0; f < h._rigCameras.length; f++)
                                h._rigCameras[f].update()
                    }
                else if (this.activeCamera && (this.activeCamera.update(),
                this.activeCamera.cameraRigMode !== 0))
                    for (var f = 0; f < this.activeCamera._rigCameras.length; f++)
                        this.activeCamera._rigCameras[f].update()
            }
            this.onBeforeRunRegisterBeforeRenderObservable.notifyObservers(this),
            this.onBeforeRenderObservable.notifyObservers(this),
            this.onAfterRunRegisterBeforeRenderObservable.notifyObservers(this),
            this.onBeforeRTT1Observable.notifyObservers(this);
            var d = this.getEngine();
            this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
            var _ = !((o = this.activeCameras) === null || o === void 0) && o.length ? this.activeCameras[0] : this.activeCamera;
            if (this.renderTargetsEnabled) {
                Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0),
                this._intermediateRendering = !0;
                for (var g = 0; g < this.customRenderTargets.length; g++) {
                    var m = this.customRenderTargets[g];
                    if (m._shouldRender()) {
                        if (this._renderId++,
                        this.activeCamera = m.activeCamera || this.activeCamera,
                        !this.activeCamera)
                            throw new Error("Active camera not set");
                        d.setViewport(this.activeCamera.viewport),
                        this.updateTransformMatrix(),
                        m.render(_ !== this.activeCamera, this.dumpNextRenderTargets)
                    }
                }
                Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0),
                this._intermediateRendering = !1,
                this._renderId++
            }
            this._engine.currentRenderPassId = (a = _ == null ? void 0 : _.renderPassId) !== null && a !== void 0 ? a : 0,
            this.activeCamera = _,
            this._activeCamera && this._activeCamera.cameraRigMode !== 22 && !this.prePass && this._bindFrameBuffer(this._activeCamera, !1),
            this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
            for (var v = 0, y = this._beforeClearStage; v < y.length; v++) {
                var u = y[v];
                u.action()
            }
            this._clearFrameBuffer(this.activeCamera);
            for (var b = 0, T = this._gatherRenderTargetsStage; b < T.length; b++) {
                var u = T[b];
                u.action(this._renderTargets)
            }
            if (this.onAfterRTT1Observable.notifyObservers(this),
            this.activeCameras && this.activeCameras.length > 0)
                for (var c = 0; c < this.activeCameras.length; c++)
                    this._processSubCameras(this.activeCameras[c], c > 0);
            else {
                if (!this.activeCamera)
                    throw new Error("No camera defined");
                this._processSubCameras(this.activeCamera, !1)
            }
            this.onBeforeRunRegisterAfterRenderObservable.notifyObservers(this),
            this._checkIntersections();
            for (var C = 0, A = this._afterRenderStage; C < A.length; C++) {
                var u = A[C];
                u.action()
            }
            if (this.afterRender && this.afterRender(),
            this.onAfterRenderObservable.notifyObservers(this),
            this.onAfterRunRegisterAfterRenderObservable.notifyObservers(this),
            this._toBeDisposed.length) {
                for (var f = 0; f < this._toBeDisposed.length; f++) {
                    var S = this._toBeDisposed[f];
                    S && S.dispose()
                }
                this._toBeDisposed = []
            }
            this.dumpNextRenderTargets && (this.dumpNextRenderTargets = !1),
            this._activeBones.addCount(0, !0),
            this._activeIndices.addCount(0, !0),
            this._activeParticles.addCount(0, !0),
            this._engine.restoreDefaultFramebuffer()
        }
    }
    ,
    e.prototype.freezeMaterials = function() {
        for (var t = 0; t < this.materials.length; t++)
            this.materials[t].freeze()
    }
    ,
    e.prototype.unfreezeMaterials = function() {
        for (var t = 0; t < this.materials.length; t++)
            this.materials[t].unfreeze()
    }
    ,
    e.prototype.dispose = function() {
        var t;
        if (!this.isDisposed) {
            this.beforeRender = null,
            this.afterRender = null,
            this.metadata = null,
            this.skeletons = [],
            this.morphTargetManagers = [],
            this._transientComponents = [],
            this._isReadyForMeshStage.clear(),
            this._beforeEvaluateActiveMeshStage.clear(),
            this._evaluateSubMeshStage.clear(),
            this._preActiveMeshStage.clear(),
            this._cameraDrawRenderTargetStage.clear(),
            this._beforeCameraDrawStage.clear(),
            this._beforeRenderTargetDrawStage.clear(),
            this._beforeRenderingGroupDrawStage.clear(),
            this._beforeRenderingMeshStage.clear(),
            this._afterRenderingMeshStage.clear(),
            this._afterRenderingGroupDrawStage.clear(),
            this._afterCameraDrawStage.clear(),
            this._afterRenderTargetDrawStage.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 r = 0, n = this._components; r < n.length; r++) {
                var o = n[r];
                o.dispose()
            }
            this.importedMeshesFiles = new Array,
            this.stopAllAnimations && this.stopAllAnimations(),
            this.resetCachedMaterial(),
            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 = [];
            for (var a = 0, s = this._activeRequests; a < s.length; a++) {
                var l = s[a];
                l.abort()
            }
            this.onBeforeRunRegisterBeforeRenderObservable.clear(),
            this.onAfterRunRegisterBeforeRenderObservable.clear(),
            this.onBeforeRTT1Observable.clear(),
            this.onAfterRTT1Observable.clear(),
            this.onBeforeRunRegisterAfterRenderObservable.clear(),
            this.onAfterRunRegisterAfterRenderObservable.clear(),
            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.onNewSkeletonAddedObservable.clear(),
            this.onSkeletonRemovedObservable.clear(),
            this.onNewMaterialAddedObservable.clear(),
            this.onNewMultiMaterialAddedObservable.clear(),
            this.onMaterialRemovedObservable.clear(),
            this.onMultiMaterialRemovedObservable.clear(),
            this.onNewTextureAddedObservable.clear(),
            this.onTextureRemovedObservable.clear(),
            this.onPrePointerObservable.clear(),
            this.onPointerObservable.clear(),
            this.onPreKeyboardObservable.clear(),
            this.onKeyboardObservable.clear(),
            this.onActiveCameraChanged.clear(),
            this.onComputePressureChanged.clear(),
            (t = this._computePressureObserver) === null || t === void 0 || t.unobserve(),
            this._computePressureObserver = void 0,
            this.detachControl();
            var u = this._engine.getInputElement();
            if (u) {
                var c;
                for (c = 0; c < this.cameras.length; c++)
                    this.cameras[c].detachControl()
            }
            for (; this.animationGroups.length; )
                this.animationGroups[0].dispose();
            for (; this.lights.length; )
                this.lights[0].dispose();
            for (; this.meshes.length; )
                this.meshes[0].dispose(!0);
            for (; this.transformNodes.length; )
                this.transformNodes[0].dispose(!0);
            for (; this.cameras.length; )
                this.cameras[0].dispose();
            for (this._defaultMaterial && this._defaultMaterial.dispose(); this.multiMaterials.length; )
                this.multiMaterials[0].dispose();
            for (; this.materials.length; )
                this.materials[0].dispose();
            for (; this.particleSystems.length; )
                this.particleSystems[0].dispose();
            for (; this.postProcesses.length; )
                this.postProcesses[0].dispose();
            for (; this.textures.length; )
                this.textures[0].dispose();
            for (; this.morphTargetManagers.length; )
                this.morphTargetManagers[0].dispose();
            this._sceneUbo.dispose(),
            this._multiviewSceneUbo && this._multiviewSceneUbo.dispose(),
            this.postProcessManager.dispose(),
            c = this._engine.scenes.indexOf(this),
            c > -1 && this._engine.scenes.splice(c, 1),
            EngineStore._LastCreatedScene === this && (this._engine.scenes.length > 0 ? EngineStore._LastCreatedScene = this._engine.scenes[this._engine.scenes.length - 1] : EngineStore._LastCreatedScene = null),
            c = this._engine._virtualScenes.indexOf(this),
            c > -1 && this._engine._virtualScenes.splice(c, 1),
            this._engine.wipeCaches(!0),
            this._isDisposed = !0
        }
    }
    ,
    Object.defineProperty(e.prototype, "isDisposed", {
        get: function() {
            return this._isDisposed
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.clearCachedVertexData = function() {
        for (var t = 0; t < this.meshes.length; t++) {
            var r = this.meshes[t]
              , n = r.geometry;
            n && n.clearCachedData()
        }
    }
    ,
    e.prototype.cleanCachedTextureBuffer = function() {
        for (var t = 0, r = this.textures; t < r.length; t++) {
            var n = r[t]
              , o = n._buffer;
            o && (n._buffer = null)
        }
    }
    ,
    e.prototype.getWorldExtends = function(t) {
        var r = new Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)
          , n = new Vector3(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);
        return t = t || function() {
            return !0
        }
        ,
        this.meshes.filter(t).forEach(function(o) {
            if (o.computeWorldMatrix(!0),
            !(!o.subMeshes || o.subMeshes.length === 0 || o.infiniteDistance)) {
                var a = o.getBoundingInfo()
                  , s = a.boundingBox.minimumWorld
                  , l = a.boundingBox.maximumWorld;
                Vector3.CheckExtends(s, r, n),
                Vector3.CheckExtends(l, r, n)
            }
        }),
        {
            min: r,
            max: n
        }
    }
    ,
    e.prototype.createPickingRay = function(t, r, n, o, a) {
        throw _WarnImport("Ray")
    }
    ,
    e.prototype.createPickingRayToRef = function(t, r, n, o, a, s) {
        throw _WarnImport("Ray")
    }
    ,
    e.prototype.createPickingRayInCameraSpace = function(t, r, n) {
        throw _WarnImport("Ray")
    }
    ,
    e.prototype.createPickingRayInCameraSpaceToRef = function(t, r, n, o) {
        throw _WarnImport("Ray")
    }
    ,
    e.prototype.pick = function(t, r, n, o, a, s) {
        var l = new PickingInfo;
        return l._pickingUnavailable = !0,
        l
    }
    ,
    e.prototype.pickWithBoundingInfo = function(t, r, n, o, a) {
        var s = new PickingInfo;
        return s._pickingUnavailable = !0,
        s
    }
    ,
    e.prototype.pickWithRay = function(t, r, n, o) {
        throw _WarnImport("Ray")
    }
    ,
    e.prototype.multiPick = function(t, r, n, o, a) {
        throw _WarnImport("Ray")
    }
    ,
    e.prototype.multiPickWithRay = function(t, r, n) {
        throw _WarnImport("Ray")
    }
    ,
    e.prototype.setPointerOverMesh = function(t, r, n) {
        this._inputManager.setPointerOverMesh(t, r, n)
    }
    ,
    e.prototype.getPointerOverMesh = function() {
        return this._inputManager.getPointerOverMesh()
    }
    ,
    e.prototype._rebuildGeometries = function() {
        for (var t = 0, r = this.geometries; t < r.length; t++) {
            var n = r[t];
            n._rebuild()
        }
        for (var o = 0, a = this.meshes; o < a.length; o++) {
            var s = a[o];
            s._rebuild()
        }
        this.postProcessManager && this.postProcessManager._rebuild();
        for (var l = 0, u = this._components; l < u.length; l++) {
            var c = u[l];
            c.rebuild()
        }
        for (var h = 0, f = this.particleSystems; h < f.length; h++) {
            var d = f[h];
            d.rebuild()
        }
        if (this.spriteManagers)
            for (var _ = 0, g = this.spriteManagers; _ < g.length; _++) {
                var m = g[_];
                m.rebuild()
            }
    }
    ,
    e.prototype._rebuildTextures = function() {
        for (var t = 0, r = this.textures; t < r.length; t++) {
            var n = r[t];
            n._rebuild()
        }
        this.markAllMaterialsAsDirty(1)
    }
    ,
    e.prototype._getByTags = function(t, r, n) {
        if (r === void 0)
            return t;
        var o = [];
        n = n || function(l) {}
        ;
        for (var a in t) {
            var s = t[a];
            Tags && Tags.MatchesQuery(s, r) && (o.push(s),
            n(s))
        }
        return o
    }
    ,
    e.prototype.getMeshesByTags = function(t, r) {
        return this._getByTags(this.meshes, t, r)
    }
    ,
    e.prototype.getCamerasByTags = function(t, r) {
        return this._getByTags(this.cameras, t, r)
    }
    ,
    e.prototype.getLightsByTags = function(t, r) {
        return this._getByTags(this.lights, t, r)
    }
    ,
    e.prototype.getMaterialByTags = function(t, r) {
        return this._getByTags(this.materials, t, r).concat(this._getByTags(this.multiMaterials, t, r))
    }
    ,
    e.prototype.getTransformNodesByTags = function(t, r) {
        return this._getByTags(this.transformNodes, t, r)
    }
    ,
    e.prototype.setRenderingOrder = function(t, r, n, o) {
        r === void 0 && (r = null),
        n === void 0 && (n = null),
        o === void 0 && (o = null),
        this._renderingManager.setRenderingOrder(t, r, n, o)
    }
    ,
    e.prototype.setRenderingAutoClearDepthStencil = function(t, r, n, o) {
        n === void 0 && (n = !0),
        o === void 0 && (o = !0),
        this._renderingManager.setRenderingAutoClearDepthStencil(t, r, n, o)
    }
    ,
    e.prototype.getAutoClearDepthStencilSetup = function(t) {
        return this._renderingManager.getAutoClearDepthStencilSetup(t)
    }
    ,
    Object.defineProperty(e.prototype, "blockMaterialDirtyMechanism", {
        get: function() {
            return this._blockMaterialDirtyMechanism
        },
        set: function(t) {
            this._blockMaterialDirtyMechanism !== t && (this._blockMaterialDirtyMechanism = t,
            t || this.markAllMaterialsAsDirty(63))
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.markAllMaterialsAsDirty = function(t, r) {
        if (!this._blockMaterialDirtyMechanism)
            for (var n = 0, o = this.materials; n < o.length; n++) {
                var a = o[n];
                r && !r(a) || a.markAsDirty(t)
            }
    }
    ,
    e.prototype._loadFile = function(t, r, n, o, a, s, l) {
        var u = this
          , c = LoadFile(t, r, n, o ? this.offlineProvider : void 0, a, s, l);
        return this._activeRequests.push(c),
        c.onCompleteObservable.add(function(h) {
            u._activeRequests.splice(u._activeRequests.indexOf(h), 1)
        }),
        c
    }
    ,
    e.prototype._loadFileAsync = function(t, r, n, o, a) {
        var s = this;
        return new Promise(function(l, u) {
            s._loadFile(t, function(c) {
                l(c)
            }, r, n, o, function(c, h) {
                u(h)
            }, a)
        }
        )
    }
    ,
    e.prototype._requestFile = function(t, r, n, o, a, s, l) {
        var u = this
          , c = RequestFile(t, r, n, o ? this.offlineProvider : void 0, a, s, l);
        return this._activeRequests.push(c),
        c.onCompleteObservable.add(function(h) {
            u._activeRequests.splice(u._activeRequests.indexOf(h), 1)
        }),
        c
    }
    ,
    e.prototype._requestFileAsync = function(t, r, n, o, a) {
        var s = this;
        return new Promise(function(l, u) {
            s._requestFile(t, function(c) {
                l(c)
            }, r, n, o, function(c) {
                u(c)
            }, a)
        }
        )
    }
    ,
    e.prototype._readFile = function(t, r, n, o, a) {
        var s = this
          , l = ReadFile(t, r, n, o, a);
        return this._activeRequests.push(l),
        l.onCompleteObservable.add(function(u) {
            s._activeRequests.splice(s._activeRequests.indexOf(u), 1)
        }),
        l
    }
    ,
    e.prototype._readFileAsync = function(t, r, n) {
        var o = this;
        return new Promise(function(a, s) {
            o._readFile(t, function(l) {
                a(l)
            }, r, n, function(l) {
                s(l)
            })
        }
        )
    }
    ,
    e.prototype.getPerfCollector = function() {
        throw _WarnImport("performanceViewerSceneExtension")
    }
    ,
    e.FOGMODE_NONE = 0,
    e.FOGMODE_EXP = 1,
    e.FOGMODE_EXP2 = 2,
    e.FOGMODE_LINEAR = 3,
    e.MinDeltaTime = 1,
    e.MaxDeltaTime = 1e3,
    e
}(AbstractScene);
_injectLTSScene(Scene);
var PerformanceMonitor = function() {
    function i(e) {
        e === void 0 && (e = 30),
        this._enabled = !0,
        this._rollingFrameTime = new RollingAverage(e)
    }
    return i.prototype.sampleFrame = function(e) {
        if (e === void 0 && (e = PrecisionDate.Now),
        !!this._enabled) {
            if (this._lastFrameTimeMs != null) {
                var t = e - this._lastFrameTimeMs;
                this._rollingFrameTime.add(t)
            }
            this._lastFrameTimeMs = e
        }
    }
    ,
    Object.defineProperty(i.prototype, "averageFrameTime", {
        get: function() {
            return this._rollingFrameTime.average
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "averageFrameTimeVariance", {
        get: function() {
            return this._rollingFrameTime.variance
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "instantaneousFrameTime", {
        get: function() {
            return this._rollingFrameTime.history(0)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "averageFPS", {
        get: function() {
            return 1e3 / this._rollingFrameTime.average
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "instantaneousFPS", {
        get: function() {
            var e = this._rollingFrameTime.history(0);
            return e === 0 ? 0 : 1e3 / e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "isSaturated", {
        get: function() {
            return this._rollingFrameTime.isSaturated()
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.enable = function() {
        this._enabled = !0
    }
    ,
    i.prototype.disable = function() {
        this._enabled = !1,
        this._lastFrameTimeMs = null
    }
    ,
    Object.defineProperty(i.prototype, "isEnabled", {
        get: function() {
            return this._enabled
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.reset = function() {
        this._lastFrameTimeMs = null,
        this._rollingFrameTime.reset()
    }
    ,
    i
}()
  , RollingAverage = function() {
    function i(e) {
        this._samples = new Array(e),
        this.reset()
    }
    return i.prototype.add = function(e) {
        var t;
        if (this.isSaturated()) {
            var r = this._samples[this._pos];
            t = r - this.average,
            this.average -= t / (this._sampleCount - 1),
            this._m2 -= t * (r - this.average)
        } else
            this._sampleCount++;
        t = e - this.average,
        this.average += t / this._sampleCount,
        this._m2 += t * (e - this.average),
        this.variance = this._m2 / (this._sampleCount - 1),
        this._samples[this._pos] = e,
        this._pos++,
        this._pos %= this._samples.length
    }
    ,
    i.prototype.history = function(e) {
        if (e >= this._sampleCount || e >= this._samples.length)
            return 0;
        var t = this._wrapPosition(this._pos - 1);
        return this._samples[this._wrapPosition(t - e)]
    }
    ,
    i.prototype.isSaturated = function() {
        return this._sampleCount >= this._samples.length
    }
    ,
    i.prototype.reset = function() {
        this.average = 0,
        this.variance = 0,
        this._sampleCount = 0,
        this._pos = 0,
        this._m2 = 0
    }
    ,
    i.prototype._wrapPosition = function(e) {
        var t = this._samples.length;
        return (e % t + t) % t
    }
    ,
    i
}();
ThinEngine.prototype.setAlphaConstants = function(i, e, t, r) {
    this._alphaState.setAlphaBlendConstants(i, e, t, r)
}
;
ThinEngine.prototype.setAlphaMode = function(i, e) {
    if (e === void 0 && (e = !1),
    this._alphaMode !== i) {
        switch (i) {
        case 0:
            this._alphaState.alphaBlend = !1;
            break;
        case 7:
            this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE),
            this._alphaState.alphaBlend = !0;
            break;
        case 8:
            this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA),
            this._alphaState.alphaBlend = !0;
            break;
        case 2:
            this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE),
            this._alphaState.alphaBlend = !0;
            break;
        case 6:
            this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE),
            this._alphaState.alphaBlend = !0;
            break;
        case 1:
            this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE),
            this._alphaState.alphaBlend = !0;
            break;
        case 3:
            this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE),
            this._alphaState.alphaBlend = !0;
            break;
        case 4:
            this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE),
            this._alphaState.alphaBlend = !0;
            break;
        case 5:
            this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE),
            this._alphaState.alphaBlend = !0;
            break;
        case 9:
            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 = !0;
            break;
        case 10:
            this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA),
            this._alphaState.alphaBlend = !0;
            break;
        case 11:
            this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ONE, this._gl.ONE),
            this._alphaState.alphaBlend = !0;
            break;
        case 12:
            this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ZERO),
            this._alphaState.alphaBlend = !0;
            break;
        case 13:
            this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE_MINUS_DST_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA),
            this._alphaState.alphaBlend = !0;
            break;
        case 14:
            this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA),
            this._alphaState.alphaBlend = !0;
            break;
        case 15:
            this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ONE, this._gl.ZERO),
            this._alphaState.alphaBlend = !0;
            break;
        case 16:
            this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ZERO, this._gl.ONE),
            this._alphaState.alphaBlend = !0;
            break;
        case 17:
            this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA),
            this._alphaState.alphaBlend = !0;
            break
        }
        e || (this.depthCullingState.depthMask = i === 0),
        this._alphaMode = i
    }
}
;
ThinEngine.prototype.getAlphaMode = function() {
    return this._alphaMode
}
;
ThinEngine.prototype.setAlphaEquation = function(i) {
    if (this._alphaEquation !== i) {
        switch (i) {
        case 0:
            this._alphaState.setAlphaEquationParameters(32774, 32774);
            break;
        case 1:
            this._alphaState.setAlphaEquationParameters(32778, 32778);
            break;
        case 2:
            this._alphaState.setAlphaEquationParameters(32779, 32779);
            break;
        case 3:
            this._alphaState.setAlphaEquationParameters(32776, 32776);
            break;
        case 4:
            this._alphaState.setAlphaEquationParameters(32775, 32775);
            break;
        case 5:
            this._alphaState.setAlphaEquationParameters(32775, 32774);
            break
        }
        this._alphaEquation = i
    }
}
;
ThinEngine.prototype.getAlphaEquation = function() {
    return this._alphaEquation
}
;
function allocateAndCopyTypedBuffer(i, e, t, r) {
    switch (t === void 0 && (t = !1),
    i) {
    case 3:
        {
            var n = e instanceof ArrayBuffer ? new Int8Array(e) : new Int8Array(e);
            return r && n.set(new Int8Array(r)),
            n
        }
    case 0:
        {
            var o = e instanceof ArrayBuffer ? new Uint8Array(e) : new Uint8Array(e);
            return r && o.set(new Uint8Array(r)),
            o
        }
    case 4:
        {
            var a = e instanceof ArrayBuffer ? new Int16Array(e) : new Int16Array(t ? e / 2 : e);
            return r && a.set(new Int16Array(r)),
            a
        }
    case 5:
    case 8:
    case 9:
    case 10:
    case 2:
        {
            var s = e instanceof ArrayBuffer ? new Uint16Array(e) : new Uint16Array(t ? e / 2 : e);
            return r && s.set(new Uint16Array(r)),
            s
        }
    case 6:
        {
            var l = e instanceof ArrayBuffer ? new Int32Array(e) : new Int32Array(t ? e / 4 : e);
            return r && l.set(new Int32Array(r)),
            l
        }
    case 7:
    case 11:
    case 12:
    case 13:
    case 14:
    case 15:
        {
            var u = e instanceof ArrayBuffer ? new Uint32Array(e) : new Uint32Array(t ? e / 4 : e);
            return r && u.set(new Uint32Array(r)),
            u
        }
    case 1:
        {
            var c = e instanceof ArrayBuffer ? new Float32Array(e) : new Float32Array(t ? e / 4 : e);
            return r && c.set(new Float32Array(r)),
            c
        }
    }
    var h = e instanceof ArrayBuffer ? new Uint8Array(e) : new Uint8Array(e);
    return r && h.set(new Uint8Array(r)),
    h
}
ThinEngine.prototype._readTexturePixelsSync = function(i, e, t, r, n, o, a, s) {
    var l, u;
    r === void 0 && (r = -1),
    n === void 0 && (n = 0),
    o === void 0 && (o = null),
    a === void 0 && (a = !0),
    s === void 0 && (s = !1);
    var c = this._gl;
    if (!c)
        throw new Error("Engine does not have gl rendering context.");
    if (!this._dummyFramebuffer) {
        var h = c.createFramebuffer();
        if (!h)
            throw new Error("Unable to create dummy framebuffer");
        this._dummyFramebuffer = h
    }
    c.bindFramebuffer(c.FRAMEBUFFER, this._dummyFramebuffer),
    r > -1 ? c.framebufferTexture2D(c.FRAMEBUFFER, c.COLOR_ATTACHMENT0, c.TEXTURE_CUBE_MAP_POSITIVE_X + r, (l = i._hardwareTexture) === null || l === void 0 ? void 0 : l.underlyingResource, n) : c.framebufferTexture2D(c.FRAMEBUFFER, c.COLOR_ATTACHMENT0, c.TEXTURE_2D, (u = i._hardwareTexture) === null || u === void 0 ? void 0 : u.underlyingResource, n);
    var f = i.type !== void 0 ? this._getWebGLTextureType(i.type) : c.UNSIGNED_BYTE;
    if (s)
        o || (o = allocateAndCopyTypedBuffer(i.type, 4 * e * t));
    else
        switch (f) {
        case c.UNSIGNED_BYTE:
            o || (o = new Uint8Array(4 * e * t)),
            f = c.UNSIGNED_BYTE;
            break;
        default:
            o || (o = new Float32Array(4 * e * t)),
            f = c.FLOAT;
            break
        }
    return a && this.flushFramebuffer(),
    c.readPixels(0, 0, e, t, c.RGBA, f, o),
    c.bindFramebuffer(c.FRAMEBUFFER, this._currentFramebuffer),
    o
}
;
ThinEngine.prototype._readTexturePixels = function(i, e, t, r, n, o, a, s) {
    return r === void 0 && (r = -1),
    n === void 0 && (n = 0),
    o === void 0 && (o = null),
    a === void 0 && (a = !0),
    s === void 0 && (s = !1),
    Promise.resolve(this._readTexturePixelsSync(i, e, t, r, n, o, a, s))
}
;
ThinEngine.prototype.updateDynamicIndexBuffer = function(i, e, t) {
    this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null,
    this.bindIndexBuffer(i);
    var r;
    e instanceof Uint16Array || e instanceof Uint32Array ? r = e : r = i.is32Bits ? new Uint32Array(e) : new Uint16Array(e),
    this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, r, this._gl.DYNAMIC_DRAW),
    this._resetIndexBufferBinding()
}
;
ThinEngine.prototype.updateDynamicVertexBuffer = function(i, e, t, r) {
    this.bindArrayBuffer(i),
    t === void 0 && (t = 0);
    var n = e.length || e.byteLength;
    r === void 0 || r >= n && t === 0 ? e instanceof Array ? this._gl.bufferSubData(this._gl.ARRAY_BUFFER, t, new Float32Array(e)) : this._gl.bufferSubData(this._gl.ARRAY_BUFFER, t, e) : e instanceof Array ? this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(e).subarray(t, t + r)) : (e instanceof ArrayBuffer ? e = new Uint8Array(e,t,r) : e = new Uint8Array(e.buffer,e.byteOffset + t,r),
    this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, e)),
    this._resetVertexBufferBinding()
}
;
var Engine = function(i) {
    __extends(e, i);
    function e(t, r, n, o) {
        o === void 0 && (o = !1);
        var a = i.call(this, t, r, n, o) || this;
        if (a.enableOfflineSupport = !1,
        a.disableManifestCheck = !1,
        a.scenes = new Array,
        a._virtualScenes = new Array,
        a.onNewSceneAddedObservable = new Observable,
        a.postProcesses = new Array,
        a.isPointerLock = !1,
        a.onResizeObservable = new Observable,
        a.onCanvasBlurObservable = new Observable,
        a.onCanvasFocusObservable = new Observable,
        a.onCanvasPointerOutObservable = new Observable,
        a.onBeginFrameObservable = new Observable,
        a.customAnimationFrameRequester = null,
        a.onEndFrameObservable = new Observable,
        a.onBeforeShaderCompilationObservable = new Observable,
        a.onAfterShaderCompilationObservable = new Observable,
        a._deterministicLockstep = !1,
        a._lockstepMaxSteps = 4,
        a._timeStep = 1 / 60,
        a._fps = 60,
        a._deltaTime = 0,
        a._drawCalls = new PerfCounter,
        a.canvasTabIndex = 1,
        a.disablePerformanceMonitorInBackground = !1,
        a._performanceMonitor = new PerformanceMonitor,
        a._compatibilityMode = !0,
        a.currentRenderPassId = 0,
        a._renderPassNames = ["main"],
        e.Instances.push(a),
        !t)
            return a;
        if (a._features.supportRenderPasses = !0,
        n = a._creationOptions,
        t.getContext) {
            var s = t;
            if (a._sharedInit(s, !!n.doNotHandleTouchAction, n.audioEngine),
            IsWindowObjectExist()) {
                var l = document;
                a._onFullscreenChange = function() {
                    l.fullscreen !== void 0 ? a.isFullscreen = l.fullscreen : l.mozFullScreen !== void 0 ? a.isFullscreen = l.mozFullScreen : l.webkitIsFullScreen !== void 0 ? a.isFullscreen = l.webkitIsFullScreen : l.msIsFullScreen !== void 0 && (a.isFullscreen = l.msIsFullScreen),
                    a.isFullscreen && a._pointerLockRequested && s && e._RequestPointerlock(s)
                }
                ,
                document.addEventListener("fullscreenchange", a._onFullscreenChange, !1),
                document.addEventListener("mozfullscreenchange", a._onFullscreenChange, !1),
                document.addEventListener("webkitfullscreenchange", a._onFullscreenChange, !1),
                document.addEventListener("msfullscreenchange", a._onFullscreenChange, !1),
                a._onPointerLockChange = function() {
                    a.isPointerLock = l.mozPointerLockElement === s || l.webkitPointerLockElement === s || l.msPointerLockElement === s || l.pointerLockElement === s
                }
                ,
                document.addEventListener("pointerlockchange", a._onPointerLockChange, !1),
                document.addEventListener("mspointerlockchange", a._onPointerLockChange, !1),
                document.addEventListener("mozpointerlockchange", a._onPointerLockChange, !1),
                document.addEventListener("webkitpointerlockchange", a._onPointerLockChange, !1),
                !e.audioEngine && n.audioEngine && e.AudioEngineFactory && (e.audioEngine = e.AudioEngineFactory(a.getRenderingCanvas(), a.getAudioContext(), a.getAudioDestination()))
            }
            a._connectVREvents(),
            a.enableOfflineSupport = e.OfflineProviderFactory !== void 0,
            a._deterministicLockstep = !!n.deterministicLockstep,
            a._lockstepMaxSteps = n.lockstepMaxSteps || 0,
            a._timeStep = n.timeStep || 1 / 60
        }
        return a._prepareVRComponent(),
        n.autoEnableWebVR && a.initWebVR(),
        a
    }
    return Object.defineProperty(e, "NpmPackage", {
        get: function() {
            return ThinEngine.NpmPackage
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e, "Version", {
        get: function() {
            return ThinEngine.Version
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e, "Instances", {
        get: function() {
            return EngineStore.Instances
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e, "LastCreatedEngine", {
        get: function() {
            return EngineStore.LastCreatedEngine
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e, "LastCreatedScene", {
        get: function() {
            return EngineStore.LastCreatedScene
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.createImageBitmap = function(t, r) {
        return createImageBitmap(t, r)
    }
    ,
    e.prototype.resizeImageBitmap = function(t, r, n) {
        var o = this.createCanvas(r, n)
          , a = o.getContext("2d");
        if (!a)
            throw new Error("Unable to get 2d context for resizeImageBitmap");
        a.drawImage(t, 0, 0);
        var s = a.getImageData(0, 0, r, n).data;
        return s
    }
    ,
    e.MarkAllMaterialsAsDirty = function(t, r) {
        for (var n = 0; n < e.Instances.length; n++)
            for (var o = e.Instances[n], a = 0; a < o.scenes.length; a++)
                o.scenes[a].markAllMaterialsAsDirty(t, r)
    }
    ,
    e.DefaultLoadingScreenFactory = function(t) {
        throw _WarnImport("LoadingScreen")
    }
    ,
    Object.defineProperty(e.prototype, "_supportsHardwareTextureRescaling", {
        get: function() {
            return !!e._RescalePostProcessFactory
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "performanceMonitor", {
        get: function() {
            return this._performanceMonitor
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "compatibilityMode", {
        get: function() {
            return this._compatibilityMode
        },
        set: function(t) {
            this._compatibilityMode = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getInputElement = function() {
        return this._renderingCanvas
    }
    ,
    e.prototype._sharedInit = function(t, r, n) {
        var o = this;
        if (i.prototype._sharedInit.call(this, t, r, n),
        this._onCanvasFocus = function() {
            o.onCanvasFocusObservable.notifyObservers(o)
        }
        ,
        this._onCanvasBlur = function() {
            o.onCanvasBlurObservable.notifyObservers(o)
        }
        ,
        t.addEventListener("focus", this._onCanvasFocus),
        t.addEventListener("blur", this._onCanvasBlur),
        this._onBlur = function() {
            o.disablePerformanceMonitorInBackground && o._performanceMonitor.disable(),
            o._windowIsBackground = !0
        }
        ,
        this._onFocus = function() {
            o.disablePerformanceMonitorInBackground && o._performanceMonitor.enable(),
            o._windowIsBackground = !1
        }
        ,
        this._onCanvasPointerOut = function(s) {
            document.elementFromPoint(s.clientX, s.clientY) !== t && o.onCanvasPointerOutObservable.notifyObservers(s)
        }
        ,
        IsWindowObjectExist()) {
            var a = this.getHostWindow();
            a && (a.addEventListener("blur", this._onBlur),
            a.addEventListener("focus", this._onFocus))
        }
        t.addEventListener("pointerout", this._onCanvasPointerOut),
        r || this._disableTouchAction(),
        !e.audioEngine && n && e.AudioEngineFactory && (e.audioEngine = e.AudioEngineFactory(this.getRenderingCanvas(), this.getAudioContext(), this.getAudioDestination()))
    }
    ,
    e.prototype.getAspectRatio = function(t, r) {
        r === void 0 && (r = !1);
        var n = t.viewport;
        return this.getRenderWidth(r) * n.width / (this.getRenderHeight(r) * n.height)
    }
    ,
    e.prototype.getScreenAspectRatio = function() {
        return this.getRenderWidth(!0) / this.getRenderHeight(!0)
    }
    ,
    e.prototype.getRenderingCanvasClientRect = function() {
        return this._renderingCanvas ? this._renderingCanvas.getBoundingClientRect() : null
    }
    ,
    e.prototype.getInputElementClientRect = function() {
        return this._renderingCanvas ? this.getInputElement().getBoundingClientRect() : null
    }
    ,
    e.prototype.isDeterministicLockStep = function() {
        return this._deterministicLockstep
    }
    ,
    e.prototype.getLockstepMaxSteps = function() {
        return this._lockstepMaxSteps
    }
    ,
    e.prototype.getTimeStep = function() {
        return this._timeStep * 1e3
    }
    ,
    e.prototype.generateMipMapsForCubemap = function(t, r) {
        if (r === void 0 && (r = !0),
        t.generateMipMaps) {
            var n = this._gl;
            this._bindTextureDirectly(n.TEXTURE_CUBE_MAP, t, !0),
            n.generateMipmap(n.TEXTURE_CUBE_MAP),
            r && this._bindTextureDirectly(n.TEXTURE_CUBE_MAP, null)
        }
    }
    ,
    e.prototype.getDepthBuffer = function() {
        return this._depthCullingState.depthTest
    }
    ,
    e.prototype.setDepthBuffer = function(t) {
        this._depthCullingState.depthTest = t
    }
    ,
    e.prototype.getDepthWrite = function() {
        return this._depthCullingState.depthMask
    }
    ,
    e.prototype.setDepthWrite = function(t) {
        this._depthCullingState.depthMask = t
    }
    ,
    e.prototype.getStencilBuffer = function() {
        return this._stencilState.stencilTest
    }
    ,
    e.prototype.setStencilBuffer = function(t) {
        this._stencilState.stencilTest = t
    }
    ,
    e.prototype.getStencilMask = function() {
        return this._stencilState.stencilMask
    }
    ,
    e.prototype.setStencilMask = function(t) {
        this._stencilState.stencilMask = t
    }
    ,
    e.prototype.getStencilFunction = function() {
        return this._stencilState.stencilFunc
    }
    ,
    e.prototype.getStencilFunctionReference = function() {
        return this._stencilState.stencilFuncRef
    }
    ,
    e.prototype.getStencilFunctionMask = function() {
        return this._stencilState.stencilFuncMask
    }
    ,
    e.prototype.setStencilFunction = function(t) {
        this._stencilState.stencilFunc = t
    }
    ,
    e.prototype.setStencilFunctionReference = function(t) {
        this._stencilState.stencilFuncRef = t
    }
    ,
    e.prototype.setStencilFunctionMask = function(t) {
        this._stencilState.stencilFuncMask = t
    }
    ,
    e.prototype.getStencilOperationFail = function() {
        return this._stencilState.stencilOpStencilFail
    }
    ,
    e.prototype.getStencilOperationDepthFail = function() {
        return this._stencilState.stencilOpDepthFail
    }
    ,
    e.prototype.getStencilOperationPass = function() {
        return this._stencilState.stencilOpStencilDepthPass
    }
    ,
    e.prototype.setStencilOperationFail = function(t) {
        this._stencilState.stencilOpStencilFail = t
    }
    ,
    e.prototype.setStencilOperationDepthFail = function(t) {
        this._stencilState.stencilOpDepthFail = t
    }
    ,
    e.prototype.setStencilOperationPass = function(t) {
        this._stencilState.stencilOpStencilDepthPass = t
    }
    ,
    e.prototype.setDitheringState = function(t) {
        t ? this._gl.enable(this._gl.DITHER) : this._gl.disable(this._gl.DITHER)
    }
    ,
    e.prototype.setRasterizerState = function(t) {
        t ? this._gl.disable(this._gl.RASTERIZER_DISCARD) : this._gl.enable(this._gl.RASTERIZER_DISCARD)
    }
    ,
    e.prototype.getDepthFunction = function() {
        return this._depthCullingState.depthFunc
    }
    ,
    e.prototype.setDepthFunction = function(t) {
        this._depthCullingState.depthFunc = t
    }
    ,
    e.prototype.setDepthFunctionToGreater = function() {
        this.setDepthFunction(516)
    }
    ,
    e.prototype.setDepthFunctionToGreaterOrEqual = function() {
        this.setDepthFunction(518)
    }
    ,
    e.prototype.setDepthFunctionToLess = function() {
        this.setDepthFunction(513)
    }
    ,
    e.prototype.setDepthFunctionToLessOrEqual = function() {
        this.setDepthFunction(515)
    }
    ,
    e.prototype.cacheStencilState = function() {
        this._cachedStencilBuffer = this.getStencilBuffer(),
        this._cachedStencilFunction = this.getStencilFunction(),
        this._cachedStencilMask = this.getStencilMask(),
        this._cachedStencilOperationPass = this.getStencilOperationPass(),
        this._cachedStencilOperationFail = this.getStencilOperationFail(),
        this._cachedStencilOperationDepthFail = this.getStencilOperationDepthFail(),
        this._cachedStencilReference = this.getStencilFunctionReference()
    }
    ,
    e.prototype.restoreStencilState = function() {
        this.setStencilFunction(this._cachedStencilFunction),
        this.setStencilMask(this._cachedStencilMask),
        this.setStencilBuffer(this._cachedStencilBuffer),
        this.setStencilOperationPass(this._cachedStencilOperationPass),
        this.setStencilOperationFail(this._cachedStencilOperationFail),
        this.setStencilOperationDepthFail(this._cachedStencilOperationDepthFail),
        this.setStencilFunctionReference(this._cachedStencilReference)
    }
    ,
    e.prototype.setDirectViewport = function(t, r, n, o) {
        var a = this._cachedViewport;
        return this._cachedViewport = null,
        this._viewport(t, r, n, o),
        a
    }
    ,
    e.prototype.scissorClear = function(t, r, n, o, a) {
        this.enableScissor(t, r, n, o),
        this.clear(a, !0, !0, !0),
        this.disableScissor()
    }
    ,
    e.prototype.enableScissor = function(t, r, n, o) {
        var a = this._gl;
        a.enable(a.SCISSOR_TEST),
        a.scissor(t, r, n, o)
    }
    ,
    e.prototype.disableScissor = function() {
        var t = this._gl;
        t.disable(t.SCISSOR_TEST)
    }
    ,
    e.prototype._reportDrawCall = function(t) {
        t === void 0 && (t = 1),
        this._drawCalls.addCount(t, !1)
    }
    ,
    e.prototype.initWebVR = function() {
        throw _WarnImport("WebVRCamera")
    }
    ,
    e.prototype._prepareVRComponent = function() {}
    ,
    e.prototype._connectVREvents = function(t, r) {}
    ,
    e.prototype._submitVRFrame = function() {}
    ,
    e.prototype.disableVR = function() {}
    ,
    e.prototype.isVRPresenting = function() {
        return !1
    }
    ,
    e.prototype._requestVRFrame = function() {}
    ,
    e.prototype._loadFileAsync = function(t, r, n) {
        var o = this;
        return new Promise(function(a, s) {
            o._loadFile(t, function(l) {
                a(l)
            }, void 0, r, n, function(l, u) {
                s(u)
            })
        }
        )
    }
    ,
    e.prototype.getVertexShaderSource = function(t) {
        var r = this._gl.getAttachedShaders(t);
        return r ? this._gl.getShaderSource(r[0]) : null
    }
    ,
    e.prototype.getFragmentShaderSource = function(t) {
        var r = this._gl.getAttachedShaders(t);
        return r ? this._gl.getShaderSource(r[1]) : null
    }
    ,
    e.prototype.setDepthStencilTexture = function(t, r, n, o) {
        t !== void 0 && (r && (this._boundUniforms[t] = r),
        !n || !n.depthStencilTexture ? this._setTexture(t, null, void 0, void 0, o) : this._setTexture(t, n, !1, !0, o))
    }
    ,
    e.prototype.setTextureFromPostProcess = function(t, r, n) {
        var o, a = null;
        r && (r._textures.data[r._currentRenderTextureInd] ? a = r._textures.data[r._currentRenderTextureInd] : r._forcedOutputTexture && (a = r._forcedOutputTexture)),
        this._bindTexture(t, (o = a == null ? void 0 : a.texture) !== null && o !== void 0 ? o : null, n)
    }
    ,
    e.prototype.setTextureFromPostProcessOutput = function(t, r, n) {
        var o, a;
        this._bindTexture(t, (a = (o = r == null ? void 0 : r._outputTexture) === null || o === void 0 ? void 0 : o.texture) !== null && a !== void 0 ? a : null, n)
    }
    ,
    e.prototype._rebuildBuffers = function() {
        for (var t = 0, r = this.scenes; t < r.length; t++) {
            var n = r[t];
            n.resetCachedMaterial(),
            n._rebuildGeometries(),
            n._rebuildTextures()
        }
        for (var o = 0, a = this._virtualScenes; o < a.length; o++) {
            var n = a[o];
            n.resetCachedMaterial(),
            n._rebuildGeometries(),
            n._rebuildTextures()
        }
        i.prototype._rebuildBuffers.call(this)
    }
    ,
    e.prototype._renderFrame = function() {
        for (var t = 0; t < this._activeRenderLoops.length; t++) {
            var r = this._activeRenderLoops[t];
            r()
        }
    }
    ,
    e.prototype._renderLoop = function() {
        if (!this._contextWasLost) {
            var t = !0;
            !this.renderEvenInBackground && this._windowIsBackground && (t = !1),
            t && (this.beginFrame(),
            this._renderViews() || this._renderFrame(),
            this.endFrame())
        }
        this._activeRenderLoops.length > 0 ? this.customAnimationFrameRequester ? (this.customAnimationFrameRequester.requestID = this._queueNewFrame(this.customAnimationFrameRequester.renderFunction || this._boundRenderFunction, this.customAnimationFrameRequester),
        this._frameHandler = this.customAnimationFrameRequester.requestID) : this.isVRPresenting() ? this._requestVRFrame() : this._frameHandler = this._queueNewFrame(this._boundRenderFunction, this.getHostWindow()) : this._renderingQueueLaunched = !1
    }
    ,
    e.prototype._renderViews = function() {
        return !1
    }
    ,
    e.prototype.switchFullscreen = function(t) {
        this.isFullscreen ? this.exitFullscreen() : this.enterFullscreen(t)
    }
    ,
    e.prototype.enterFullscreen = function(t) {
        this.isFullscreen || (this._pointerLockRequested = t,
        this._renderingCanvas && e._RequestFullscreen(this._renderingCanvas))
    }
    ,
    e.prototype.exitFullscreen = function() {
        this.isFullscreen && e._ExitFullscreen()
    }
    ,
    e.prototype.enterPointerlock = function() {
        this._renderingCanvas && e._RequestPointerlock(this._renderingCanvas)
    }
    ,
    e.prototype.exitPointerlock = function() {
        e._ExitPointerlock()
    }
    ,
    e.prototype.beginFrame = function() {
        this._measureFps(),
        this.onBeginFrameObservable.notifyObservers(this),
        i.prototype.beginFrame.call(this)
    }
    ,
    e.prototype.endFrame = function() {
        i.prototype.endFrame.call(this),
        this._submitVRFrame(),
        this.onEndFrameObservable.notifyObservers(this)
    }
    ,
    e.prototype.resize = function(t) {
        t === void 0 && (t = !1),
        !this.isVRPresenting() && i.prototype.resize.call(this, t)
    }
    ,
    e.prototype.setSize = function(t, r, n) {
        if (n === void 0 && (n = !1),
        !this._renderingCanvas || !i.prototype.setSize.call(this, t, r, n))
            return !1;
        if (this.scenes) {
            for (var o = 0; o < this.scenes.length; o++)
                for (var a = this.scenes[o], s = 0; s < a.cameras.length; s++) {
                    var l = a.cameras[s];
                    l._currentRenderId = 0
                }
            this.onResizeObservable.hasObservers() && this.onResizeObservable.notifyObservers(this)
        }
        return !0
    }
    ,
    e.prototype._deletePipelineContext = function(t) {
        var r = t;
        r && r.program && r.transformFeedback && (this.deleteTransformFeedback(r.transformFeedback),
        r.transformFeedback = null),
        i.prototype._deletePipelineContext.call(this, t)
    }
    ,
    e.prototype.createShaderProgram = function(t, r, n, o, a, s) {
        s === void 0 && (s = null),
        a = a || this._gl,
        this.onBeforeShaderCompilationObservable.notifyObservers(this);
        var l = i.prototype.createShaderProgram.call(this, t, r, n, o, a, s);
        return this.onAfterShaderCompilationObservable.notifyObservers(this),
        l
    }
    ,
    e.prototype._createShaderProgram = function(t, r, n, o, a) {
        a === void 0 && (a = null);
        var s = o.createProgram();
        if (t.program = s,
        !s)
            throw new Error("Unable to create program");
        if (o.attachShader(s, r),
        o.attachShader(s, n),
        this.webGLVersion > 1 && a) {
            var l = this.createTransformFeedback();
            this.bindTransformFeedback(l),
            this.setTranformFeedbackVaryings(s, a),
            t.transformFeedback = l
        }
        return o.linkProgram(s),
        this.webGLVersion > 1 && a && this.bindTransformFeedback(null),
        t.context = o,
        t.vertexShader = r,
        t.fragmentShader = n,
        t.isParallelCompiled || this._finalizePipelineContext(t),
        s
    }
    ,
    e.prototype._releaseTexture = function(t) {
        i.prototype._releaseTexture.call(this, t)
    }
    ,
    e.prototype._releaseRenderTargetWrapper = function(t) {
        i.prototype._releaseRenderTargetWrapper.call(this, t),
        this.scenes.forEach(function(r) {
            r.postProcesses.forEach(function(n) {
                n._outputTexture === t && (n._outputTexture = null)
            }),
            r.cameras.forEach(function(n) {
                n._postProcesses.forEach(function(o) {
                    o && o._outputTexture === t && (o._outputTexture = null)
                })
            })
        })
    }
    ,
    e.prototype.getRenderPassNames = function() {
        return this._renderPassNames
    }
    ,
    e.prototype.getCurrentRenderPassName = function() {
        return this._renderPassNames[this.currentRenderPassId]
    }
    ,
    e.prototype.createRenderPassId = function(t) {
        var r = ++e._RenderPassIdCounter;
        return this._renderPassNames[r] = t != null ? t : "NONAME",
        r
    }
    ,
    e.prototype.releaseRenderPassId = function(t) {
        this._renderPassNames[t] = void 0;
        for (var r = 0; r < this.scenes.length; ++r)
            for (var n = this.scenes[r], o = 0; o < n.meshes.length; ++o) {
                var a = n.meshes[o];
                if (a.subMeshes)
                    for (var s = 0; s < a.subMeshes.length; ++s) {
                        var l = a.subMeshes[s];
                        l._removeDrawWrapper(t)
                    }
            }
    }
    ,
    e.prototype._rescaleTexture = function(t, r, n, o, a) {
        var s = this;
        this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, this._gl.LINEAR),
        this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, this._gl.LINEAR),
        this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE),
        this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
        var l = this.createRenderTargetTexture({
            width: r.width,
            height: r.height
        }, {
            generateMipMaps: !1,
            type: 0,
            samplingMode: 2,
            generateDepthBuffer: !1,
            generateStencilBuffer: !1
        });
        !this._rescalePostProcess && e._RescalePostProcessFactory && (this._rescalePostProcess = e._RescalePostProcessFactory(this)),
        this._rescalePostProcess.externalTextureSamplerBinding = !0,
        this._rescalePostProcess.getEffect().executeWhenCompiled(function() {
            s._rescalePostProcess.onApply = function(c) {
                c._bindTexture("textureSampler", t)
            }
            ;
            var u = n;
            u || (u = s.scenes[s.scenes.length - 1]),
            u.postProcessManager.directRender([s._rescalePostProcess], l, !0),
            s._bindTextureDirectly(s._gl.TEXTURE_2D, r, !0),
            s._gl.copyTexImage2D(s._gl.TEXTURE_2D, 0, o, 0, 0, r.width, r.height, 0),
            s.unBindFramebuffer(l),
            l.dispose(),
            a && a()
        })
    }
    ,
    e.prototype.getFps = function() {
        return this._fps
    }
    ,
    e.prototype.getDeltaTime = function() {
        return this._deltaTime
    }
    ,
    e.prototype._measureFps = function() {
        this._performanceMonitor.sampleFrame(),
        this._fps = this._performanceMonitor.averageFPS,
        this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0
    }
    ,
    e.prototype._uploadImageToTexture = function(t, r, n, o) {
        n === void 0 && (n = 0),
        o === void 0 && (o = 0);
        var a = this._gl
          , s = this._getWebGLTextureType(t.type)
          , l = this._getInternalFormat(t.format)
          , u = this._getRGBABufferInternalSizedFormat(t.type, l)
          , c = t.isCube ? a.TEXTURE_CUBE_MAP : a.TEXTURE_2D;
        this._bindTextureDirectly(c, t, !0),
        this._unpackFlipY(t.invertY);
        var h = a.TEXTURE_2D;
        t.isCube && (h = a.TEXTURE_CUBE_MAP_POSITIVE_X + n),
        a.texImage2D(h, o, u, l, s, r),
        this._bindTextureDirectly(c, null, !0)
    }
    ,
    e.prototype.updateTextureComparisonFunction = function(t, r) {
        if (this.webGLVersion === 1) {
            Logger$2.Error("WebGL 1 does not support texture comparison.");
            return
        }
        var n = this._gl;
        t.isCube ? (this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, t, !0),
        r === 0 ? (n.texParameteri(n.TEXTURE_CUBE_MAP, n.TEXTURE_COMPARE_FUNC, 515),
        n.texParameteri(n.TEXTURE_CUBE_MAP, n.TEXTURE_COMPARE_MODE, n.NONE)) : (n.texParameteri(n.TEXTURE_CUBE_MAP, n.TEXTURE_COMPARE_FUNC, r),
        n.texParameteri(n.TEXTURE_CUBE_MAP, n.TEXTURE_COMPARE_MODE, n.COMPARE_REF_TO_TEXTURE)),
        this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null)) : (this._bindTextureDirectly(this._gl.TEXTURE_2D, t, !0),
        r === 0 ? (n.texParameteri(n.TEXTURE_2D, n.TEXTURE_COMPARE_FUNC, 515),
        n.texParameteri(n.TEXTURE_2D, n.TEXTURE_COMPARE_MODE, n.NONE)) : (n.texParameteri(n.TEXTURE_2D, n.TEXTURE_COMPARE_FUNC, r),
        n.texParameteri(n.TEXTURE_2D, n.TEXTURE_COMPARE_MODE, n.COMPARE_REF_TO_TEXTURE)),
        this._bindTextureDirectly(this._gl.TEXTURE_2D, null)),
        t._comparisonFunction = r
    }
    ,
    e.prototype.createInstancesBuffer = function(t) {
        var r = this._gl.createBuffer();
        if (!r)
            throw new Error("Unable to create instance buffer");
        var n = new WebGLDataBuffer(r);
        return n.capacity = t,
        this.bindArrayBuffer(n),
        this._gl.bufferData(this._gl.ARRAY_BUFFER, t, this._gl.DYNAMIC_DRAW),
        n.references = 1,
        n
    }
    ,
    e.prototype.deleteInstancesBuffer = function(t) {
        this._gl.deleteBuffer(t)
    }
    ,
    e.prototype._clientWaitAsync = function(t, r, n) {
        r === void 0 && (r = 0),
        n === void 0 && (n = 10);
        var o = this._gl;
        return new Promise(function(a, s) {
            var l = function() {
                var u = o.clientWaitSync(t, r, 0);
                if (u == o.WAIT_FAILED) {
                    s();
                    return
                }
                if (u == o.TIMEOUT_EXPIRED) {
                    setTimeout(l, n);
                    return
                }
                a()
            };
            l()
        }
        )
    }
    ,
    e.prototype._readPixelsAsync = function(t, r, n, o, a, s, l) {
        if (this._webGLVersion < 2)
            throw new Error("_readPixelsAsync only work on WebGL2+");
        var u = this._gl
          , c = u.createBuffer();
        u.bindBuffer(u.PIXEL_PACK_BUFFER, c),
        u.bufferData(u.PIXEL_PACK_BUFFER, l.byteLength, u.STREAM_READ),
        u.readPixels(t, r, n, o, a, s, 0),
        u.bindBuffer(u.PIXEL_PACK_BUFFER, null);
        var h = u.fenceSync(u.SYNC_GPU_COMMANDS_COMPLETE, 0);
        return h ? (u.flush(),
        this._clientWaitAsync(h, 0, 10).then(function() {
            return u.deleteSync(h),
            u.bindBuffer(u.PIXEL_PACK_BUFFER, c),
            u.getBufferSubData(u.PIXEL_PACK_BUFFER, 0, l),
            u.bindBuffer(u.PIXEL_PACK_BUFFER, null),
            u.deleteBuffer(c),
            l
        })) : null
    }
    ,
    e.prototype.dispose = function() {
        for (this.hideLoadingUI(),
        this.onNewSceneAddedObservable.clear(); this.postProcesses.length; )
            this.postProcesses[0].dispose();
        for (this._rescalePostProcess && this._rescalePostProcess.dispose(); this.scenes.length; )
            this.scenes[0].dispose();
        for (; this._virtualScenes.length; )
            this._virtualScenes[0].dispose();
        e.Instances.length === 1 && e.audioEngine && (e.audioEngine.dispose(),
        e.audioEngine = null),
        this.disableVR(),
        this.deviceInputSystem && this.deviceInputSystem.dispose(),
        IsWindowObjectExist() && (window.removeEventListener("blur", this._onBlur),
        window.removeEventListener("focus", this._onFocus),
        this._renderingCanvas && (this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus),
        this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur),
        this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut)),
        IsDocumentAvailable() && (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))),
        i.prototype.dispose.call(this);
        var t = e.Instances.indexOf(this);
        t >= 0 && e.Instances.splice(t, 1),
        this.onResizeObservable.clear(),
        this.onCanvasBlurObservable.clear(),
        this.onCanvasFocusObservable.clear(),
        this.onCanvasPointerOutObservable.clear(),
        this.onBeginFrameObservable.clear(),
        this.onEndFrameObservable.clear()
    }
    ,
    e.prototype._disableTouchAction = function() {
        !this._renderingCanvas || !this._renderingCanvas.setAttribute || (this._renderingCanvas.setAttribute("touch-action", "none"),
        this._renderingCanvas.style.touchAction = "none",
        this._renderingCanvas.style.msTouchAction = "none")
    }
    ,
    e.prototype.displayLoadingUI = function() {
        if (!!IsWindowObjectExist()) {
            var t = this.loadingScreen;
            t && t.displayLoadingUI()
        }
    }
    ,
    e.prototype.hideLoadingUI = function() {
        if (!!IsWindowObjectExist()) {
            var t = this._loadingScreen;
            t && t.hideLoadingUI()
        }
    }
    ,
    Object.defineProperty(e.prototype, "loadingScreen", {
        get: function() {
            return !this._loadingScreen && this._renderingCanvas && (this._loadingScreen = e.DefaultLoadingScreenFactory(this._renderingCanvas)),
            this._loadingScreen
        },
        set: function(t) {
            this._loadingScreen = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "loadingUIText", {
        set: function(t) {
            this.loadingScreen.loadingUIText = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "loadingUIBackgroundColor", {
        set: function(t) {
            this.loadingScreen.loadingUIBackgroundColor = t
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.createVideoElement = function(t) {
        return document.createElement("video")
    }
    ,
    e._RequestPointerlock = function(t) {
        t.requestPointerLock = t.requestPointerLock || t.msRequestPointerLock || t.mozRequestPointerLock || t.webkitRequestPointerLock,
        t.requestPointerLock && t.requestPointerLock()
    }
    ,
    e._ExitPointerlock = function() {
        var t = document;
        document.exitPointerLock = document.exitPointerLock || t.msExitPointerLock || t.mozExitPointerLock || t.webkitExitPointerLock,
        document.exitPointerLock && document.exitPointerLock()
    }
    ,
    e._RequestFullscreen = function(t) {
        var r = t.requestFullscreen || t.msRequestFullscreen || t.webkitRequestFullscreen || t.mozRequestFullScreen;
        !r || r.call(t)
    }
    ,
    e._ExitFullscreen = function() {
        var t = document;
        document.exitFullscreen ? document.exitFullscreen() : t.mozCancelFullScreen ? t.mozCancelFullScreen() : t.webkitCancelFullScreen ? t.webkitCancelFullScreen() : t.msCancelFullScreen && t.msCancelFullScreen()
    }
    ,
    e.prototype.getFontOffset = function(t) {
        var r = document.createElement("span");
        r.innerHTML = "Hg",
        r.setAttribute("style", "font: " + t + " !important");
        var n = document.createElement("div");
        n.style.display = "inline-block",
        n.style.width = "1px",
        n.style.height = "0px",
        n.style.verticalAlign = "bottom";
        var o = document.createElement("div");
        o.style.whiteSpace = "nowrap",
        o.appendChild(r),
        o.appendChild(n),
        document.body.appendChild(o);
        var a = 0
          , s = 0;
        try {
            s = n.getBoundingClientRect().top - r.getBoundingClientRect().top,
            n.style.verticalAlign = "baseline",
            a = n.getBoundingClientRect().top - r.getBoundingClientRect().top
        } finally {
            document.body.removeChild(o)
        }
        return {
            ascent: a,
            height: s,
            descent: s - a
        }
    }
    ,
    e.ALPHA_DISABLE = 0,
    e.ALPHA_ADD = 1,
    e.ALPHA_COMBINE = 2,
    e.ALPHA_SUBTRACT = 3,
    e.ALPHA_MULTIPLY = 4,
    e.ALPHA_MAXIMIZED = 5,
    e.ALPHA_ONEONE = 6,
    e.ALPHA_PREMULTIPLIED = 7,
    e.ALPHA_PREMULTIPLIED_PORTERDUFF = 8,
    e.ALPHA_INTERPOLATE = 9,
    e.ALPHA_SCREENMODE = 10,
    e.DELAYLOADSTATE_NONE = 0,
    e.DELAYLOADSTATE_LOADED = 1,
    e.DELAYLOADSTATE_LOADING = 2,
    e.DELAYLOADSTATE_NOTLOADED = 4,
    e.NEVER = 512,
    e.ALWAYS = 519,
    e.LESS = 513,
    e.EQUAL = 514,
    e.LEQUAL = 515,
    e.GREATER = 516,
    e.GEQUAL = 518,
    e.NOTEQUAL = 517,
    e.KEEP = 7680,
    e.REPLACE = 7681,
    e.INCR = 7682,
    e.DECR = 7683,
    e.INVERT = 5386,
    e.INCR_WRAP = 34055,
    e.DECR_WRAP = 34056,
    e.TEXTURE_CLAMP_ADDRESSMODE = 0,
    e.TEXTURE_WRAP_ADDRESSMODE = 1,
    e.TEXTURE_MIRROR_ADDRESSMODE = 2,
    e.TEXTUREFORMAT_ALPHA = 0,
    e.TEXTUREFORMAT_LUMINANCE = 1,
    e.TEXTUREFORMAT_LUMINANCE_ALPHA = 2,
    e.TEXTUREFORMAT_RGB = 4,
    e.TEXTUREFORMAT_RGBA = 5,
    e.TEXTUREFORMAT_RED = 6,
    e.TEXTUREFORMAT_R = 6,
    e.TEXTUREFORMAT_RG = 7,
    e.TEXTUREFORMAT_RED_INTEGER = 8,
    e.TEXTUREFORMAT_R_INTEGER = 8,
    e.TEXTUREFORMAT_RG_INTEGER = 9,
    e.TEXTUREFORMAT_RGB_INTEGER = 10,
    e.TEXTUREFORMAT_RGBA_INTEGER = 11,
    e.TEXTURETYPE_UNSIGNED_BYTE = 0,
    e.TEXTURETYPE_UNSIGNED_INT = 0,
    e.TEXTURETYPE_FLOAT = 1,
    e.TEXTURETYPE_HALF_FLOAT = 2,
    e.TEXTURETYPE_BYTE = 3,
    e.TEXTURETYPE_SHORT = 4,
    e.TEXTURETYPE_UNSIGNED_SHORT = 5,
    e.TEXTURETYPE_INT = 6,
    e.TEXTURETYPE_UNSIGNED_INTEGER = 7,
    e.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8,
    e.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9,
    e.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10,
    e.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11,
    e.TEXTURETYPE_UNSIGNED_INT_24_8 = 12,
    e.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13,
    e.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14,
    e.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15,
    e.TEXTURE_NEAREST_SAMPLINGMODE = 1,
    e.TEXTURE_BILINEAR_SAMPLINGMODE = 2,
    e.TEXTURE_TRILINEAR_SAMPLINGMODE = 3,
    e.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 8,
    e.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 11,
    e.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3,
    e.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4,
    e.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5,
    e.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6,
    e.TEXTURE_NEAREST_LINEAR = 7,
    e.TEXTURE_NEAREST_NEAREST = 1,
    e.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9,
    e.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10,
    e.TEXTURE_LINEAR_LINEAR = 2,
    e.TEXTURE_LINEAR_NEAREST = 12,
    e.TEXTURE_EXPLICIT_MODE = 0,
    e.TEXTURE_SPHERICAL_MODE = 1,
    e.TEXTURE_PLANAR_MODE = 2,
    e.TEXTURE_CUBIC_MODE = 3,
    e.TEXTURE_PROJECTION_MODE = 4,
    e.TEXTURE_SKYBOX_MODE = 5,
    e.TEXTURE_INVCUBIC_MODE = 6,
    e.TEXTURE_EQUIRECTANGULAR_MODE = 7,
    e.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8,
    e.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9,
    e.SCALEMODE_FLOOR = 1,
    e.SCALEMODE_NEAREST = 2,
    e.SCALEMODE_CEILING = 3,
    e._RescalePostProcessFactory = null,
    e._RenderPassIdCounter = 0,
    e
}(ThinEngine), SceneLoaderFlags = function() {
    function i() {}
    return Object.defineProperty(i, "ForceFullSceneLoadingForIncremental", {
        get: function() {
            return i._ForceFullSceneLoadingForIncremental
        },
        set: function(e) {
            i._ForceFullSceneLoadingForIncremental = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i, "ShowLoadingScreen", {
        get: function() {
            return i._ShowLoadingScreen
        },
        set: function(e) {
            i._ShowLoadingScreen = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i, "loggingLevel", {
        get: function() {
            return i._loggingLevel
        },
        set: function(e) {
            i._loggingLevel = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i, "CleanBoneMatrixWeights", {
        get: function() {
            return i._CleanBoneMatrixWeights
        },
        set: function(e) {
            i._CleanBoneMatrixWeights = e
        },
        enumerable: !1,
        configurable: !0
    }),
    i._ForceFullSceneLoadingForIncremental = !1,
    i._ShowLoadingScreen = !0,
    i._CleanBoneMatrixWeights = !1,
    i._loggingLevel = 0,
    i
}(), SceneLoaderAnimationGroupLoadingMode;
(function(i) {
    i[i.Clean = 0] = "Clean",
    i[i.Stop = 1] = "Stop",
    i[i.Sync = 2] = "Sync",
    i[i.NoSync = 3] = "NoSync"
}
)(SceneLoaderAnimationGroupLoadingMode || (SceneLoaderAnimationGroupLoadingMode = {}));
var SceneLoader = function() {
    function i() {}
    return Object.defineProperty(i, "ForceFullSceneLoadingForIncremental", {
        get: function() {
            return SceneLoaderFlags.ForceFullSceneLoadingForIncremental
        },
        set: function(e) {
            SceneLoaderFlags.ForceFullSceneLoadingForIncremental = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i, "ShowLoadingScreen", {
        get: function() {
            return SceneLoaderFlags.ShowLoadingScreen
        },
        set: function(e) {
            SceneLoaderFlags.ShowLoadingScreen = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i, "loggingLevel", {
        get: function() {
            return SceneLoaderFlags.loggingLevel
        },
        set: function(e) {
            SceneLoaderFlags.loggingLevel = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i, "CleanBoneMatrixWeights", {
        get: function() {
            return SceneLoaderFlags.CleanBoneMatrixWeights
        },
        set: function(e) {
            SceneLoaderFlags.CleanBoneMatrixWeights = e
        },
        enumerable: !1,
        configurable: !0
    }),
    i.GetDefaultPlugin = function() {
        return i._registeredPlugins[".babylon"]
    }
    ,
    i._GetPluginForExtension = function(e) {
        var t = i._registeredPlugins[e];
        return t || (Logger$2.Warn("Unable to find a plugin to load " + e + " files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: https://doc.babylonjs.com/how_to/load_from_any_file_type"),
        i.GetDefaultPlugin())
    }
    ,
    i._GetPluginForDirectLoad = function(e) {
        for (var t in i._registeredPlugins) {
            var r = i._registeredPlugins[t].plugin;
            if (r.canDirectLoad && r.canDirectLoad(e))
                return i._registeredPlugins[t]
        }
        return i.GetDefaultPlugin()
    }
    ,
    i._GetPluginForFilename = function(e) {
        var t = e.indexOf("?");
        t !== -1 && (e = e.substring(0, t));
        var r = e.lastIndexOf(".")
          , n = e.substring(r, e.length).toLowerCase();
        return i._GetPluginForExtension(n)
    }
    ,
    i._GetDirectLoad = function(e) {
        return e.substr(0, 5) === "data:" ? e.substr(5) : null
    }
    ,
    i._FormatErrorMessage = function(e, t, r) {
        var n = "Unable to load from " + e.url;
        return t ? n += ": " + t : r && (n += ": " + r),
        n
    }
    ,
    i._LoadData = function(e, t, r, n, o, a, s) {
        var l = i._GetDirectLoad(e.url), u = s ? i._GetPluginForExtension(s) : l ? i._GetPluginForDirectLoad(e.url) : i._GetPluginForFilename(e.url), c;
        if (u.plugin.createPlugin !== void 0 ? c = u.plugin.createPlugin() : c = u.plugin,
        !c)
            throw "The loader plugin corresponding to the file type you are trying to load has not been found. If using es6, please import the plugin you wish to use before.";
        if (i.OnPluginActivatedObservable.notifyObservers(c),
        l && (c.canDirectLoad && c.canDirectLoad(e.url) || !IsBase64DataUrl(e.url))) {
            if (c.directLoad) {
                var h = c.directLoad(t, l);
                h.then ? h.then(function(P) {
                    r(c, P)
                }).catch(function(P) {
                    o("Error in directLoad of _loadData: " + P, P)
                }) : r(c, h)
            } else
                r(c, l);
            return c
        }
        var f = u.isBinary
          , d = function(P, R) {
            if (t.isDisposed) {
                o("Scene has been disposed");
                return
            }
            r(c, P, R)
        }
          , _ = null
          , g = !1
          , m = c.onDisposeObservable;
        m && m.add(function() {
            g = !0,
            _ && (_.abort(),
            _ = null),
            a()
        });
        var v = function() {
            if (!g) {
                var P = function(M, x) {
                    o(M == null ? void 0 : M.statusText, x)
                }
                  , R = e.file || e.url;
                _ = c.loadFile ? c.loadFile(t, R, d, n, f, P) : t._loadFile(R, d, n, !0, f, P)
            }
        }
          , y = t.getEngine()
          , b = y.enableOfflineSupport;
        if (b) {
            for (var T = !1, C = 0, A = t.disableOfflineSupportExceptionRules; C < A.length; C++) {
                var S = A[C];
                if (S.test(e.url)) {
                    T = !0;
                    break
                }
            }
            b = !T
        }
        return b && Engine.OfflineProviderFactory ? t.offlineProvider = Engine.OfflineProviderFactory(e.url, v, y.disableManifestCheck) : v(),
        c
    }
    ,
    i._GetFileInfo = function(e, t) {
        var r, n, o = null;
        if (!t)
            r = e,
            n = Tools.GetFilename(e),
            e = Tools.GetFolderPath(e);
        else if (t.name) {
            var a = t;
            r = "file:" + a.name,
            n = a.name,
            o = a
        } else if (typeof t == "string" && StartsWith(t, "data:"))
            r = t,
            n = "";
        else {
            var s = t;
            if (s.substr(0, 1) === "/")
                return Tools.Error("Wrong sceneFilename parameter"),
                null;
            r = e + s,
            n = s
        }
        return {
            url: r,
            rootUrl: e,
            name: n,
            file: o
        }
    }
    ,
    i.GetPluginForExtension = function(e) {
        return i._GetPluginForExtension(e).plugin
    }
    ,
    i.IsPluginForExtensionAvailable = function(e) {
        return !!i._registeredPlugins[e]
    }
    ,
    i.RegisterPlugin = function(e) {
        if (typeof e.extensions == "string") {
            var t = e.extensions;
            i._registeredPlugins[t.toLowerCase()] = {
                plugin: e,
                isBinary: !1
            }
        } else {
            var r = e.extensions;
            Object.keys(r).forEach(function(n) {
                i._registeredPlugins[n.toLowerCase()] = {
                    plugin: e,
                    isBinary: r[n].isBinary
                }
            })
        }
    }
    ,
    i.ImportMesh = function(e, t, r, n, o, a, s, l) {
        if (r === void 0 && (r = ""),
        n === void 0 && (n = EngineStore.LastCreatedScene),
        o === void 0 && (o = null),
        a === void 0 && (a = null),
        s === void 0 && (s = null),
        l === void 0 && (l = null),
        !n)
            return Logger$2.Error("No scene available to import mesh to"),
            null;
        var u = i._GetFileInfo(t, r);
        if (!u)
            return null;
        var c = {};
        n._addPendingData(c);
        var h = function() {
            n._removePendingData(c)
        }
          , f = function(g, m) {
            var v = i._FormatErrorMessage(u, g, m);
            s ? s(n, v, new Error(v)) : Logger$2.Error(v),
            h()
        }
          , d = a ? function(g) {
            try {
                a(g)
            } catch (m) {
                f("Error in onProgress callback: " + m, m)
            }
        }
        : void 0
          , _ = function(g, m, v, y, b, T, C) {
            if (n.importedMeshesFiles.push(u.url),
            o)
                try {
                    o(g, m, v, y, b, T, C)
                } catch (A) {
                    f("Error in onSuccess callback: " + A, A)
                }
            n._removePendingData(c)
        };
        return i._LoadData(u, n, function(g, m, v) {
            if (g.rewriteRootURL && (u.rootUrl = g.rewriteRootURL(u.rootUrl, v)),
            g.importMesh) {
                var y = g
                  , b = new Array
                  , T = new Array
                  , C = new Array;
                if (!y.importMesh(e, n, m, u.rootUrl, b, T, C, f))
                    return;
                n.loadingPluginName = g.name,
                _(b, T, C, [], [], [], [])
            } else {
                var A = g;
                A.importMeshAsync(e, n, m, u.rootUrl, d, u.name).then(function(S) {
                    n.loadingPluginName = g.name,
                    _(S.meshes, S.particleSystems, S.skeletons, S.animationGroups, S.transformNodes, S.geometries, S.lights)
                }).catch(function(S) {
                    f(S.message, S)
                })
            }
        }, d, f, h, l)
    }
    ,
    i.ImportMeshAsync = function(e, t, r, n, o, a) {
        return r === void 0 && (r = ""),
        n === void 0 && (n = EngineStore.LastCreatedScene),
        o === void 0 && (o = null),
        a === void 0 && (a = null),
        new Promise(function(s, l) {
            i.ImportMesh(e, t, r, n, function(u, c, h, f, d, _, g) {
                s({
                    meshes: u,
                    particleSystems: c,
                    skeletons: h,
                    animationGroups: f,
                    transformNodes: d,
                    geometries: _,
                    lights: g
                })
            }, o, function(u, c, h) {
                l(h || new Error(c))
            }, a)
        }
        )
    }
    ,
    i.Load = function(e, t, r, n, o, a, s) {
        return t === void 0 && (t = ""),
        r === void 0 && (r = EngineStore.LastCreatedEngine),
        n === void 0 && (n = null),
        o === void 0 && (o = null),
        a === void 0 && (a = null),
        s === void 0 && (s = null),
        r ? i.Append(e, t, new Scene(r), n, o, a, s) : (Tools.Error("No engine available"),
        null)
    }
    ,
    i.LoadAsync = function(e, t, r, n, o) {
        return t === void 0 && (t = ""),
        r === void 0 && (r = EngineStore.LastCreatedEngine),
        n === void 0 && (n = null),
        o === void 0 && (o = null),
        new Promise(function(a, s) {
            i.Load(e, t, r, function(l) {
                a(l)
            }, n, function(l, u, c) {
                s(c || new Error(u))
            }, o)
        }
        )
    }
    ,
    i.Append = function(e, t, r, n, o, a, s) {
        var l = this;
        if (t === void 0 && (t = ""),
        r === void 0 && (r = EngineStore.LastCreatedScene),
        n === void 0 && (n = null),
        o === void 0 && (o = null),
        a === void 0 && (a = null),
        s === void 0 && (s = null),
        !r)
            return Logger$2.Error("No scene available to append to"),
            null;
        var u = i._GetFileInfo(e, t);
        if (!u)
            return null;
        i.ShowLoadingScreen && !this._showingLoadingScreen && (this._showingLoadingScreen = !0,
        r.getEngine().displayLoadingUI(),
        r.executeWhenReady(function() {
            r.getEngine().hideLoadingUI(),
            l._showingLoadingScreen = !1
        }));
        var c = {};
        r._addPendingData(c);
        var h = function() {
            r._removePendingData(c)
        }
          , f = function(g, m) {
            var v = i._FormatErrorMessage(u, g, m);
            a ? a(r, v, new Error(v)) : Logger$2.Error(v),
            h()
        }
          , d = o ? function(g) {
            try {
                o(g)
            } catch (m) {
                f("Error in onProgress callback", m)
            }
        }
        : void 0
          , _ = function() {
            if (n)
                try {
                    n(r)
                } catch (g) {
                    f("Error in onSuccess callback", g)
                }
            r._removePendingData(c)
        };
        return i._LoadData(u, r, function(g, m) {
            if (g.load) {
                var v = g;
                if (!v.load(r, m, u.rootUrl, f))
                    return;
                r.loadingPluginName = g.name,
                _()
            } else {
                var y = g;
                y.loadAsync(r, m, u.rootUrl, d, u.name).then(function() {
                    r.loadingPluginName = g.name,
                    _()
                }).catch(function(b) {
                    f(b.message, b)
                })
            }
        }, d, f, h, s)
    }
    ,
    i.AppendAsync = function(e, t, r, n, o) {
        return t === void 0 && (t = ""),
        r === void 0 && (r = EngineStore.LastCreatedScene),
        n === void 0 && (n = null),
        o === void 0 && (o = null),
        new Promise(function(a, s) {
            i.Append(e, t, r, function(l) {
                a(l)
            }, n, function(l, u, c) {
                s(c || new Error(u))
            }, o)
        }
        )
    }
    ,
    i.LoadAssetContainer = function(e, t, r, n, o, a, s) {
        if (t === void 0 && (t = ""),
        r === void 0 && (r = EngineStore.LastCreatedScene),
        n === void 0 && (n = null),
        o === void 0 && (o = null),
        a === void 0 && (a = null),
        s === void 0 && (s = null),
        !r)
            return Logger$2.Error("No scene available to load asset container to"),
            null;
        var l = i._GetFileInfo(e, t);
        if (!l)
            return null;
        var u = {};
        r._addPendingData(u);
        var c = function() {
            r._removePendingData(u)
        }
          , h = function(_, g) {
            var m = i._FormatErrorMessage(l, _, g);
            a ? a(r, m, new Error(m)) : Logger$2.Error(m),
            c()
        }
          , f = o ? function(_) {
            try {
                o(_)
            } catch (g) {
                h("Error in onProgress callback", g)
            }
        }
        : void 0
          , d = function(_) {
            if (n)
                try {
                    n(_)
                } catch (g) {
                    h("Error in onSuccess callback", g)
                }
            r._removePendingData(u)
        };
        return i._LoadData(l, r, function(_, g) {
            if (_.loadAssetContainer) {
                var m = _
                  , v = m.loadAssetContainer(r, g, l.rootUrl, h);
                if (!v)
                    return;
                r.loadingPluginName = _.name,
                d(v)
            } else if (_.loadAssetContainerAsync) {
                var y = _;
                y.loadAssetContainerAsync(r, g, l.rootUrl, f, l.name).then(function(b) {
                    r.loadingPluginName = _.name,
                    d(b)
                }).catch(function(b) {
                    h(b.message, b)
                })
            } else
                h("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.")
        }, f, h, c, s)
    }
    ,
    i.LoadAssetContainerAsync = function(e, t, r, n, o) {
        return t === void 0 && (t = ""),
        r === void 0 && (r = EngineStore.LastCreatedScene),
        n === void 0 && (n = null),
        o === void 0 && (o = null),
        new Promise(function(a, s) {
            i.LoadAssetContainer(e, t, r, function(l) {
                a(l)
            }, n, function(l, u, c) {
                s(c || new Error(u))
            }, o)
        }
        )
    }
    ,
    i.ImportAnimations = function(e, t, r, n, o, a, s, l, u, c) {
        if (t === void 0 && (t = ""),
        r === void 0 && (r = EngineStore.LastCreatedScene),
        n === void 0 && (n = !0),
        o === void 0 && (o = SceneLoaderAnimationGroupLoadingMode.Clean),
        a === void 0 && (a = null),
        s === void 0 && (s = null),
        l === void 0 && (l = null),
        u === void 0 && (u = null),
        c === void 0 && (c = null),
        !r) {
            Logger$2.Error("No scene available to load animations to");
            return
        }
        if (n) {
            for (var h = 0, f = r.animatables; h < f.length; h++) {
                var d = f[h];
                d.reset()
            }
            r.stopAllAnimations(),
            r.animationGroups.slice().forEach(function(v) {
                v.dispose()
            });
            var _ = r.getNodes();
            _.forEach(function(v) {
                v.animations && (v.animations = [])
            })
        } else
            switch (o) {
            case SceneLoaderAnimationGroupLoadingMode.Clean:
                r.animationGroups.slice().forEach(function(v) {
                    v.dispose()
                });
                break;
            case SceneLoaderAnimationGroupLoadingMode.Stop:
                r.animationGroups.forEach(function(v) {
                    v.stop()
                });
                break;
            case SceneLoaderAnimationGroupLoadingMode.Sync:
                r.animationGroups.forEach(function(v) {
                    v.reset(),
                    v.restart()
                });
                break;
            case SceneLoaderAnimationGroupLoadingMode.NoSync:
                break;
            default:
                Logger$2.Error("Unknown animation group loading mode value '" + o + "'");
                return
            }
        var g = r.animatables.length
          , m = function(v) {
            v.mergeAnimationsTo(r, r.animatables.slice(g), a),
            v.dispose(),
            r.onAnimationFileImportedObservable.notifyObservers(r),
            s && s(r)
        };
        this.LoadAssetContainer(e, t, r, m, l, u, c)
    }
    ,
    i.ImportAnimationsAsync = function(e, t, r, n, o, a, s, l, u, c) {
        return t === void 0 && (t = ""),
        r === void 0 && (r = EngineStore.LastCreatedScene),
        n === void 0 && (n = !0),
        o === void 0 && (o = SceneLoaderAnimationGroupLoadingMode.Clean),
        a === void 0 && (a = null),
        l === void 0 && (l = null),
        c === void 0 && (c = null),
        new Promise(function(h, f) {
            i.ImportAnimations(e, t, r, n, o, a, function(d) {
                h(d)
            }, l, function(d, _, g) {
                f(g || new Error(_))
            }, c)
        }
        )
    }
    ,
    i.NO_LOGGING = 0,
    i.MINIMAL_LOGGING = 1,
    i.SUMMARY_LOGGING = 2,
    i.DETAILED_LOGGING = 3,
    i.OnPluginActivatedObservable = new Observable,
    i._registeredPlugins = {},
    i._showingLoadingScreen = !1,
    i
}(), AnimationKeyInterpolation;
(function(i) {
    i[i.NONE = 0] = "NONE",
    i[i.STEP = 1] = "STEP"
}
)(AnimationKeyInterpolation || (AnimationKeyInterpolation = {}));
var AnimationRange = function() {
    function i(e, t, r) {
        this.name = e,
        this.from = t,
        this.to = r
    }
    return i.prototype.clone = function() {
        return new i(this.name,this.from,this.to)
    }
    ,
    i
}()
  , _InternalNodeDataInfo = function() {
    function i() {
        this._doNotSerialize = !1,
        this._isDisposed = !1,
        this._sceneRootNodesIndex = -1,
        this._isEnabled = !0,
        this._isParentEnabled = !0,
        this._isReady = !0,
        this._onEnabledStateChangedObservable = new Observable,
        this._onClonedObservable = new Observable
    }
    return i
}()
  , Node$2 = function() {
    function i(e, t) {
        t === void 0 && (t = null),
        this._isDirty = !1,
        this._nodeDataStorage = new _InternalNodeDataInfo,
        this.state = "",
        this.metadata = null,
        this.reservedDataStore = null,
        this._parentContainer = null,
        this.animations = new Array,
        this._ranges = {},
        this.onReady = null,
        this._currentRenderId = -1,
        this._parentUpdateId = -1,
        this._childUpdateId = -1,
        this._waitingParentId = null,
        this._cache = {},
        this._parentNode = null,
        this._children = null,
        this._worldMatrix = Matrix.Identity(),
        this._worldMatrixDeterminant = 0,
        this._worldMatrixDeterminantIsDirty = !0,
        this._animationPropertiesOverride = null,
        this._isNode = !0,
        this.onDisposeObservable = new Observable,
        this._onDisposeObserver = null,
        this._behaviors = new Array,
        this.name = e,
        this.id = e,
        this._scene = t || EngineStore.LastCreatedScene,
        this.uniqueId = this._scene.getUniqueId(),
        this._initCache()
    }
    return i.AddNodeConstructor = function(e, t) {
        this._NodeConstructors[e] = t
    }
    ,
    i.Construct = function(e, t, r, n) {
        var o = this._NodeConstructors[e];
        return o ? o(t, r, n) : null
    }
    ,
    Object.defineProperty(i.prototype, "doNotSerialize", {
        get: function() {
            return this._nodeDataStorage._doNotSerialize ? !0 : this._parentNode ? this._parentNode.doNotSerialize : !1
        },
        set: function(e) {
            this._nodeDataStorage._doNotSerialize = e
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.isDisposed = function() {
        return this._nodeDataStorage._isDisposed
    }
    ,
    Object.defineProperty(i.prototype, "parent", {
        get: function() {
            return this._parentNode
        },
        set: function(e) {
            if (this._parentNode !== e) {
                var t = this._parentNode;
                if (this._parentNode && this._parentNode._children !== void 0 && this._parentNode._children !== null) {
                    var r = this._parentNode._children.indexOf(this);
                    r !== -1 && this._parentNode._children.splice(r, 1),
                    !e && !this._nodeDataStorage._isDisposed && this._addToSceneRootNodes()
                }
                this._parentNode = e,
                this._parentNode && ((this._parentNode._children === void 0 || this._parentNode._children === null) && (this._parentNode._children = new Array),
                this._parentNode._children.push(this),
                t || this._removeFromSceneRootNodes()),
                this._syncParentEnabledState()
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype._addToSceneRootNodes = function() {
        this._nodeDataStorage._sceneRootNodesIndex === -1 && (this._nodeDataStorage._sceneRootNodesIndex = this._scene.rootNodes.length,
        this._scene.rootNodes.push(this))
    }
    ,
    i.prototype._removeFromSceneRootNodes = function() {
        if (this._nodeDataStorage._sceneRootNodesIndex !== -1) {
            var e = this._scene.rootNodes
              , t = e.length - 1;
            e[this._nodeDataStorage._sceneRootNodesIndex] = e[t],
            e[this._nodeDataStorage._sceneRootNodesIndex]._nodeDataStorage._sceneRootNodesIndex = this._nodeDataStorage._sceneRootNodesIndex,
            this._scene.rootNodes.pop(),
            this._nodeDataStorage._sceneRootNodesIndex = -1
        }
    }
    ,
    Object.defineProperty(i.prototype, "animationPropertiesOverride", {
        get: function() {
            return this._animationPropertiesOverride ? this._animationPropertiesOverride : this._scene.animationPropertiesOverride
        },
        set: function(e) {
            this._animationPropertiesOverride = e
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.getClassName = function() {
        return "Node"
    }
    ,
    Object.defineProperty(i.prototype, "onDispose", {
        set: function(e) {
            this._onDisposeObserver && this.onDisposeObservable.remove(this._onDisposeObserver),
            this._onDisposeObserver = this.onDisposeObservable.add(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "onEnabledStateChangedObservable", {
        get: function() {
            return this._nodeDataStorage._onEnabledStateChangedObservable
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "onClonedObservable", {
        get: function() {
            return this._nodeDataStorage._onClonedObservable
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.getScene = function() {
        return this._scene
    }
    ,
    i.prototype.getEngine = function() {
        return this._scene.getEngine()
    }
    ,
    i.prototype.addBehavior = function(e, t) {
        var r = this;
        t === void 0 && (t = !1);
        var n = this._behaviors.indexOf(e);
        return n !== -1 ? this : (e.init(),
        this._scene.isLoading && !t ? this._scene.onDataLoadedObservable.addOnce(function() {
            e.attach(r)
        }) : e.attach(this),
        this._behaviors.push(e),
        this)
    }
    ,
    i.prototype.removeBehavior = function(e) {
        var t = this._behaviors.indexOf(e);
        return t === -1 ? this : (this._behaviors[t].detach(),
        this._behaviors.splice(t, 1),
        this)
    }
    ,
    Object.defineProperty(i.prototype, "behaviors", {
        get: function() {
            return this._behaviors
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.getBehaviorByName = function(e) {
        for (var t = 0, r = this._behaviors; t < r.length; t++) {
            var n = r[t];
            if (n.name === e)
                return n
        }
        return null
    }
    ,
    i.prototype.getWorldMatrix = function() {
        return this._currentRenderId !== this._scene.getRenderId() && this.computeWorldMatrix(),
        this._worldMatrix
    }
    ,
    i.prototype._getWorldMatrixDeterminant = function() {
        return this._worldMatrixDeterminantIsDirty && (this._worldMatrixDeterminantIsDirty = !1,
        this._worldMatrixDeterminant = this._worldMatrix.determinant()),
        this._worldMatrixDeterminant
    }
    ,
    Object.defineProperty(i.prototype, "worldMatrixFromCache", {
        get: function() {
            return this._worldMatrix
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype._initCache = function() {
        this._cache = {},
        this._cache.parent = void 0
    }
    ,
    i.prototype.updateCache = function(e) {
        !e && this.isSynchronized() || (this._cache.parent = this.parent,
        this._updateCache())
    }
    ,
    i.prototype._getActionManagerForTrigger = function(e, t) {
        return this.parent ? this.parent._getActionManagerForTrigger(e, !1) : null
    }
    ,
    i.prototype._updateCache = function(e) {}
    ,
    i.prototype._isSynchronized = function() {
        return !0
    }
    ,
    i.prototype._markSyncedWithParent = function() {
        this._parentNode && (this._parentUpdateId = this._parentNode._childUpdateId)
    }
    ,
    i.prototype.isSynchronizedWithParent = function() {
        return this._parentNode ? this._parentUpdateId !== this._parentNode._childUpdateId ? !1 : this._parentNode.isSynchronized() : !0
    }
    ,
    i.prototype.isSynchronized = function() {
        return this._cache.parent != this._parentNode ? (this._cache.parent = this._parentNode,
        !1) : this._parentNode && !this.isSynchronizedWithParent() ? !1 : this._isSynchronized()
    }
    ,
    i.prototype.isReady = function(e) {
        return this._nodeDataStorage._isReady
    }
    ,
    i.prototype.markAsDirty = function(e) {
        return this._currentRenderId = Number.MAX_VALUE,
        this._isDirty = !0,
        this
    }
    ,
    i.prototype.isEnabled = function(e) {
        return e === void 0 && (e = !0),
        e === !1 ? this._nodeDataStorage._isEnabled : this._nodeDataStorage._isEnabled ? this._nodeDataStorage._isParentEnabled : !1
    }
    ,
    i.prototype._syncParentEnabledState = function() {
        this._nodeDataStorage._isParentEnabled = this._parentNode ? this._parentNode.isEnabled() : !0,
        this._children && this._children.forEach(function(e) {
            e._syncParentEnabledState()
        })
    }
    ,
    i.prototype.setEnabled = function(e) {
        this._nodeDataStorage._isEnabled !== e && (this._nodeDataStorage._isEnabled = e,
        this._nodeDataStorage._onEnabledStateChangedObservable.notifyObservers(e),
        this._syncParentEnabledState())
    }
    ,
    i.prototype.isDescendantOf = function(e) {
        return this.parent ? this.parent === e ? !0 : this.parent.isDescendantOf(e) : !1
    }
    ,
    i.prototype._getDescendants = function(e, t, r) {
        if (t === void 0 && (t = !1),
        !!this._children)
            for (var n = 0; n < this._children.length; n++) {
                var o = this._children[n];
                (!r || r(o)) && e.push(o),
                t || o._getDescendants(e, !1, r)
            }
    }
    ,
    i.prototype.getDescendants = function(e, t) {
        var r = new Array;
        return this._getDescendants(r, e, t),
        r
    }
    ,
    i.prototype.getChildMeshes = function(e, t) {
        var r = [];
        return this._getDescendants(r, e, function(n) {
            return (!t || t(n)) && n.cullingStrategy !== void 0
        }),
        r
    }
    ,
    i.prototype.getChildren = function(e, t) {
        return t === void 0 && (t = !0),
        this.getDescendants(t, e)
    }
    ,
    i.prototype._setReady = function(e) {
        if (e !== this._nodeDataStorage._isReady) {
            if (!e) {
                this._nodeDataStorage._isReady = !1;
                return
            }
            this.onReady && this.onReady(this),
            this._nodeDataStorage._isReady = !0
        }
    }
    ,
    i.prototype.getAnimationByName = function(e) {
        for (var t = 0; t < this.animations.length; t++) {
            var r = this.animations[t];
            if (r.name === e)
                return r
        }
        return null
    }
    ,
    i.prototype.createAnimationRange = function(e, t, r) {
        if (!this._ranges[e]) {
            this._ranges[e] = i._AnimationRangeFactory(e, t, r);
            for (var n = 0, o = this.animations.length; n < o; n++)
                this.animations[n] && this.animations[n].createRange(e, t, r)
        }
    }
    ,
    i.prototype.deleteAnimationRange = function(e, t) {
        t === void 0 && (t = !0);
        for (var r = 0, n = this.animations.length; r < n; r++)
            this.animations[r] && this.animations[r].deleteRange(e, t);
        this._ranges[e] = null
    }
    ,
    i.prototype.getAnimationRange = function(e) {
        return this._ranges[e] || null
    }
    ,
    i.prototype.getAnimationRanges = function() {
        var e = [], t;
        for (t in this._ranges)
            e.push(this._ranges[t]);
        return e
    }
    ,
    i.prototype.beginAnimation = function(e, t, r, n) {
        var o = this.getAnimationRange(e);
        return o ? this._scene.beginAnimation(this, o.from, o.to, t, r, n) : null
    }
    ,
    i.prototype.serializeAnimationRanges = function() {
        var e = [];
        for (var t in this._ranges) {
            var r = this._ranges[t];
            if (!!r) {
                var n = {};
                n.name = t,
                n.from = r.from,
                n.to = r.to,
                e.push(n)
            }
        }
        return e
    }
    ,
    i.prototype.computeWorldMatrix = function(e) {
        return this._worldMatrix || (this._worldMatrix = Matrix.Identity()),
        this._worldMatrix
    }
    ,
    i.prototype.dispose = function(e, t) {
        if (t === void 0 && (t = !1),
        this._nodeDataStorage._isDisposed = !0,
        !e)
            for (var r = this.getDescendants(!0), n = 0, o = r; n < o.length; n++) {
                var a = o[n];
                a.dispose(e, t)
            }
        this.parent ? this.parent = null : this._removeFromSceneRootNodes(),
        this.onDisposeObservable.notifyObservers(this),
        this.onDisposeObservable.clear(),
        this.onEnabledStateChangedObservable.clear(),
        this.onClonedObservable.clear();
        for (var s = 0, l = this._behaviors; s < l.length; s++) {
            var u = l[s];
            u.detach()
        }
        this._behaviors = [],
        this.metadata = null
    }
    ,
    i.ParseAnimationRanges = function(e, t, r) {
        if (t.ranges)
            for (var n = 0; n < t.ranges.length; n++) {
                var o = t.ranges[n];
                e.createAnimationRange(o.name, o.from, o.to)
            }
    }
    ,
    i.prototype.getHierarchyBoundingVectors = function(e, t) {
        e === void 0 && (e = !0),
        t === void 0 && (t = null),
        this.getScene().incrementRenderId(),
        this.computeWorldMatrix(!0);
        var r, n, o = this;
        if (o.getBoundingInfo && o.subMeshes) {
            var a = o.getBoundingInfo();
            r = a.boundingBox.minimumWorld.clone(),
            n = a.boundingBox.maximumWorld.clone()
        } else
            r = new Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),
            n = new Vector3(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);
        if (e)
            for (var s = this.getDescendants(!1), l = 0, u = s; l < u.length; l++) {
                var c = u[l]
                  , h = c;
                if (h.computeWorldMatrix(!0),
                !(t && !t(h)) && !(!h.getBoundingInfo || h.getTotalVertices() === 0)) {
                    var f = h.getBoundingInfo()
                      , d = f.boundingBox
                      , _ = d.minimumWorld
                      , g = d.maximumWorld;
                    Vector3.CheckExtends(_, r, n),
                    Vector3.CheckExtends(g, r, n)
                }
            }
        return {
            min: r,
            max: n
        }
    }
    ,
    i._AnimationRangeFactory = function(e, t, r) {
        throw _WarnImport("AnimationRange")
    }
    ,
    i._NodeConstructors = {},
    __decorate([serialize()], i.prototype, "name", void 0),
    __decorate([serialize()], i.prototype, "id", void 0),
    __decorate([serialize()], i.prototype, "uniqueId", void 0),
    __decorate([serialize()], i.prototype, "state", void 0),
    __decorate([serialize()], i.prototype, "metadata", void 0),
    i
}()
  , Size = function() {
    function i(e, t) {
        this.width = e,
        this.height = t
    }
    return i.prototype.toString = function() {
        return "{W: " + this.width + ", H: " + this.height + "}"
    }
    ,
    i.prototype.getClassName = function() {
        return "Size"
    }
    ,
    i.prototype.getHashCode = function() {
        var e = this.width | 0;
        return e = e * 397 ^ (this.height | 0),
        e
    }
    ,
    i.prototype.copyFrom = function(e) {
        this.width = e.width,
        this.height = e.height
    }
    ,
    i.prototype.copyFromFloats = function(e, t) {
        return this.width = e,
        this.height = t,
        this
    }
    ,
    i.prototype.set = function(e, t) {
        return this.copyFromFloats(e, t)
    }
    ,
    i.prototype.multiplyByFloats = function(e, t) {
        return new i(this.width * e,this.height * t)
    }
    ,
    i.prototype.clone = function() {
        return new i(this.width,this.height)
    }
    ,
    i.prototype.equals = function(e) {
        return e ? this.width === e.width && this.height === e.height : !1
    }
    ,
    Object.defineProperty(i.prototype, "surface", {
        get: function() {
            return this.width * this.height
        },
        enumerable: !1,
        configurable: !0
    }),
    i.Zero = function() {
        return new i(0,0)
    }
    ,
    i.prototype.add = function(e) {
        var t = new i(this.width + e.width,this.height + e.height);
        return t
    }
    ,
    i.prototype.subtract = function(e) {
        var t = new i(this.width - e.width,this.height - e.height);
        return t
    }
    ,
    i.Lerp = function(e, t, r) {
        var n = e.width + (t.width - e.width) * r
          , o = e.height + (t.height - e.height) * r;
        return new i(n,o)
    }
    ,
    i
}()
  , Animation = function() {
    function i(e, t, r, n, o, a) {
        this.name = e,
        this.targetProperty = t,
        this.framePerSecond = r,
        this.dataType = n,
        this.loopMode = o,
        this.enableBlending = a,
        this._runtimeAnimations = new Array,
        this._events = new Array,
        this.blendingSpeed = .01,
        this._ranges = {},
        this.targetPropertyPath = t.split("."),
        this.dataType = n,
        this.loopMode = o === void 0 ? i.ANIMATIONLOOPMODE_CYCLE : o,
        this.uniqueId = i._UniqueIdGenerator++
    }
    return i._PrepareAnimation = function(e, t, r, n, o, a, s, l) {
        var u = void 0;
        if (!isNaN(parseFloat(o)) && isFinite(o) ? u = i.ANIMATIONTYPE_FLOAT : o instanceof Quaternion ? u = i.ANIMATIONTYPE_QUATERNION : o instanceof Vector3 ? u = i.ANIMATIONTYPE_VECTOR3 : o instanceof Vector2 ? u = i.ANIMATIONTYPE_VECTOR2 : o instanceof Color3 ? u = i.ANIMATIONTYPE_COLOR3 : o instanceof Color4 ? u = i.ANIMATIONTYPE_COLOR4 : o instanceof Size && (u = i.ANIMATIONTYPE_SIZE),
        u == null)
            return null;
        var c = new i(e,t,r,u,s)
          , h = [{
            frame: 0,
            value: o
        }, {
            frame: n,
            value: a
        }];
        return c.setKeys(h),
        l !== void 0 && c.setEasingFunction(l),
        c
    }
    ,
    i.CreateAnimation = function(e, t, r, n) {
        var o = new i(e + "Animation",e,r,t,i.ANIMATIONLOOPMODE_CONSTANT);
        return o.setEasingFunction(n),
        o
    }
    ,
    i.CreateAndStartAnimation = function(e, t, r, n, o, a, s, l, u, c, h) {
        var f = i._PrepareAnimation(e, r, n, o, a, s, l, u);
        return !f || (t.getScene && (h = t.getScene()),
        !h) ? null : h.beginDirectAnimation(t, [f], 0, o, f.loopMode === 1, 1, c)
    }
    ,
    i.CreateAndStartHierarchyAnimation = function(e, t, r, n, o, a, s, l, u, c, h) {
        var f = i._PrepareAnimation(e, n, o, a, s, l, u, c);
        if (!f)
            return null;
        var d = t.getScene();
        return d.beginDirectHierarchyAnimation(t, r, [f], 0, a, f.loopMode === 1, 1, h)
    }
    ,
    i.CreateMergeAndStartAnimation = function(e, t, r, n, o, a, s, l, u, c) {
        var h = i._PrepareAnimation(e, r, n, o, a, s, l, u);
        return h ? (t.animations.push(h),
        t.getScene().beginAnimation(t, 0, o, h.loopMode === 1, 1, c)) : null
    }
    ,
    i.MakeAnimationAdditive = function(e, t, r, n, o) {
        t === void 0 && (t = 0),
        n === void 0 && (n = !1);
        var a = e;
        if (n && (a = e.clone(),
        a.name = o || a.name),
        !a._keys.length)
            return a;
        t = t >= 0 ? t : 0;
        var s = 0
          , l = a._keys[0]
          , u = a._keys.length - 1
          , c = a._keys[u]
          , h = {
            referenceValue: l.value,
            referencePosition: TmpVectors.Vector3[0],
            referenceQuaternion: TmpVectors.Quaternion[0],
            referenceScaling: TmpVectors.Vector3[1],
            keyPosition: TmpVectors.Vector3[2],
            keyQuaternion: TmpVectors.Quaternion[1],
            keyScaling: TmpVectors.Vector3[3]
        }
          , f = !1
          , d = l.frame
          , _ = c.frame;
        if (r) {
            var g = a.getRange(r);
            g && (d = g.from,
            _ = g.to)
        }
        var m = l.frame === d
          , v = c.frame === _;
        if (a._keys.length === 1) {
            var y = a._getKeyValue(a._keys[0]);
            h.referenceValue = y.clone ? y.clone() : y,
            f = !0
        } else if (t <= l.frame) {
            var y = a._getKeyValue(l.value);
            h.referenceValue = y.clone ? y.clone() : y,
            f = !0
        } else if (t >= c.frame) {
            var y = a._getKeyValue(c.value);
            h.referenceValue = y.clone ? y.clone() : y,
            f = !0
        }
        for (var b = 0; !f || !m || !v && b < a._keys.length - 1; ) {
            var T = a._keys[b]
              , C = a._keys[b + 1];
            if (!f && t >= T.frame && t <= C.frame) {
                var y = void 0;
                if (t === T.frame)
                    y = a._getKeyValue(T.value);
                else if (t === C.frame)
                    y = a._getKeyValue(C.value);
                else {
                    var A = {
                        key: b,
                        repeatCount: 0,
                        loopMode: this.ANIMATIONLOOPMODE_CONSTANT
                    };
                    y = a._interpolate(t, A)
                }
                h.referenceValue = y.clone ? y.clone() : y,
                f = !0
            }
            if (!m && d >= T.frame && d <= C.frame) {
                if (d === T.frame)
                    s = b;
                else if (d === C.frame)
                    s = b + 1;
                else {
                    var A = {
                        key: b,
                        repeatCount: 0,
                        loopMode: this.ANIMATIONLOOPMODE_CONSTANT
                    }
                      , y = a._interpolate(d, A)
                      , S = {
                        frame: d,
                        value: y.clone ? y.clone() : y
                    };
                    a._keys.splice(b + 1, 0, S),
                    s = b + 1
                }
                m = !0
            }
            if (!v && _ >= T.frame && _ <= C.frame) {
                if (_ === T.frame)
                    u = b;
                else if (_ === C.frame)
                    u = b + 1;
                else {
                    var A = {
                        key: b,
                        repeatCount: 0,
                        loopMode: this.ANIMATIONLOOPMODE_CONSTANT
                    }
                      , y = a._interpolate(_, A)
                      , S = {
                        frame: _,
                        value: y.clone ? y.clone() : y
                    };
                    a._keys.splice(b + 1, 0, S),
                    u = b + 1
                }
                v = !0
            }
            b++
        }
        a.dataType === i.ANIMATIONTYPE_QUATERNION ? h.referenceValue.normalize().conjugateInPlace() : a.dataType === i.ANIMATIONTYPE_MATRIX && (h.referenceValue.decompose(h.referenceScaling, h.referenceQuaternion, h.referencePosition),
        h.referenceQuaternion.normalize().conjugateInPlace());
        for (var b = s; b <= u; b++) {
            var S = a._keys[b];
            if (!(b && a.dataType !== i.ANIMATIONTYPE_FLOAT && S.value === l.value))
                switch (a.dataType) {
                case i.ANIMATIONTYPE_MATRIX:
                    S.value.decompose(h.keyScaling, h.keyQuaternion, h.keyPosition),
                    h.keyPosition.subtractInPlace(h.referencePosition),
                    h.keyScaling.divideInPlace(h.referenceScaling),
                    h.referenceQuaternion.multiplyToRef(h.keyQuaternion, h.keyQuaternion),
                    Matrix.ComposeToRef(h.keyScaling, h.keyQuaternion, h.keyPosition, S.value);
                    break;
                case i.ANIMATIONTYPE_QUATERNION:
                    h.referenceValue.multiplyToRef(S.value, S.value);
                    break;
                case i.ANIMATIONTYPE_VECTOR2:
                case i.ANIMATIONTYPE_VECTOR3:
                case i.ANIMATIONTYPE_COLOR3:
                case i.ANIMATIONTYPE_COLOR4:
                    S.value.subtractToRef(h.referenceValue, S.value);
                    break;
                case i.ANIMATIONTYPE_SIZE:
                    S.value.width -= h.referenceValue.width,
                    S.value.height -= h.referenceValue.height;
                    break;
                default:
                    S.value -= h.referenceValue
                }
        }
        return a
    }
    ,
    i.TransitionTo = function(e, t, r, n, o, a, s, l) {
        if (l === void 0 && (l = null),
        s <= 0)
            return r[e] = t,
            l && l(),
            null;
        var u = o * (s / 1e3);
        a.setKeys([{
            frame: 0,
            value: r[e].clone ? r[e].clone() : r[e]
        }, {
            frame: u,
            value: t
        }]),
        r.animations || (r.animations = []),
        r.animations.push(a);
        var c = n.beginAnimation(r, 0, u, !1);
        return c.onAnimationEnd = l,
        c
    }
    ,
    Object.defineProperty(i.prototype, "runtimeAnimations", {
        get: function() {
            return this._runtimeAnimations
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "hasRunningRuntimeAnimations", {
        get: function() {
            for (var e = 0, t = this._runtimeAnimations; e < t.length; e++) {
                var r = t[e];
                if (!r.isStopped())
                    return !0
            }
            return !1
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.toString = function(e) {
        var t = "Name: " + this.name + ", property: " + this.targetProperty;
        if (t += ", datatype: " + ["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"][this.dataType],
        t += ", nKeys: " + (this._keys ? this._keys.length : "none"),
        t += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none"),
        e) {
            t += ", Ranges: {";
            var r = !0;
            for (var n in this._ranges)
                r && (t += ", ",
                r = !1),
                t += n;
            t += "}"
        }
        return t
    }
    ,
    i.prototype.addEvent = function(e) {
        this._events.push(e),
        this._events.sort(function(t, r) {
            return t.frame - r.frame
        })
    }
    ,
    i.prototype.removeEvents = function(e) {
        for (var t = 0; t < this._events.length; t++)
            this._events[t].frame === e && (this._events.splice(t, 1),
            t--)
    }
    ,
    i.prototype.getEvents = function() {
        return this._events
    }
    ,
    i.prototype.createRange = function(e, t, r) {
        this._ranges[e] || (this._ranges[e] = new AnimationRange(e,t,r))
    }
    ,
    i.prototype.deleteRange = function(e, t) {
        t === void 0 && (t = !0);
        var r = this._ranges[e];
        if (!!r) {
            if (t)
                for (var n = r.from, o = r.to, a = this._keys.length - 1; a >= 0; a--)
                    this._keys[a].frame >= n && this._keys[a].frame <= o && this._keys.splice(a, 1);
            this._ranges[e] = null
        }
    }
    ,
    i.prototype.getRange = function(e) {
        return this._ranges[e]
    }
    ,
    i.prototype.getKeys = function() {
        return this._keys
    }
    ,
    i.prototype.getHighestFrame = function() {
        for (var e = 0, t = 0, r = this._keys.length; t < r; t++)
            e < this._keys[t].frame && (e = this._keys[t].frame);
        return e
    }
    ,
    i.prototype.getEasingFunction = function() {
        return this._easingFunction
    }
    ,
    i.prototype.setEasingFunction = function(e) {
        this._easingFunction = e
    }
    ,
    i.prototype.floatInterpolateFunction = function(e, t, r) {
        return Scalar.Lerp(e, t, r)
    }
    ,
    i.prototype.floatInterpolateFunctionWithTangents = function(e, t, r, n, o) {
        return Scalar.Hermite(e, t, r, n, o)
    }
    ,
    i.prototype.quaternionInterpolateFunction = function(e, t, r) {
        return Quaternion.Slerp(e, t, r)
    }
    ,
    i.prototype.quaternionInterpolateFunctionWithTangents = function(e, t, r, n, o) {
        return Quaternion.Hermite(e, t, r, n, o).normalize()
    }
    ,
    i.prototype.vector3InterpolateFunction = function(e, t, r) {
        return Vector3.Lerp(e, t, r)
    }
    ,
    i.prototype.vector3InterpolateFunctionWithTangents = function(e, t, r, n, o) {
        return Vector3.Hermite(e, t, r, n, o)
    }
    ,
    i.prototype.vector2InterpolateFunction = function(e, t, r) {
        return Vector2.Lerp(e, t, r)
    }
    ,
    i.prototype.vector2InterpolateFunctionWithTangents = function(e, t, r, n, o) {
        return Vector2.Hermite(e, t, r, n, o)
    }
    ,
    i.prototype.sizeInterpolateFunction = function(e, t, r) {
        return Size.Lerp(e, t, r)
    }
    ,
    i.prototype.color3InterpolateFunction = function(e, t, r) {
        return Color3.Lerp(e, t, r)
    }
    ,
    i.prototype.color3InterpolateFunctionWithTangents = function(e, t, r, n, o) {
        return Color3.Hermite(e, t, r, n, o)
    }
    ,
    i.prototype.color4InterpolateFunction = function(e, t, r) {
        return Color4.Lerp(e, t, r)
    }
    ,
    i.prototype.color4InterpolateFunctionWithTangents = function(e, t, r, n, o) {
        return Color4.Hermite(e, t, r, n, o)
    }
    ,
    i.prototype._getKeyValue = function(e) {
        return typeof e == "function" ? e() : e
    }
    ,
    i.prototype.evaluate = function(e) {
        return this._interpolate(e, {
            key: 0,
            repeatCount: 0,
            loopMode: i.ANIMATIONLOOPMODE_CONSTANT
        })
    }
    ,
    i.prototype._interpolate = function(e, t) {
        if (t.loopMode === i.ANIMATIONLOOPMODE_CONSTANT && t.repeatCount > 0)
            return t.highLimitValue.clone ? t.highLimitValue.clone() : t.highLimitValue;
        var r = this._keys;
        if (r.length === 1)
            return this._getKeyValue(r[0].value);
        var n = t.key;
        if (r[n].frame >= e)
            for (; n - 1 >= 0 && r[n].frame >= e; )
                n--;
        for (var o = n; o < r.length - 1; o++) {
            var a = r[o + 1];
            if (a.frame >= e) {
                t.key = o;
                var s = r[o]
                  , l = this._getKeyValue(s.value)
                  , u = this._getKeyValue(a.value);
                if (s.interpolation === AnimationKeyInterpolation.STEP)
                    return a.frame > e ? l : u;
                var c = s.outTangent !== void 0 && a.inTangent !== void 0
                  , h = a.frame - s.frame
                  , f = (e - s.frame) / h
                  , d = this.getEasingFunction();
                switch (d != null && (f = d.ease(f)),
                this.dataType) {
                case i.ANIMATIONTYPE_FLOAT:
                    var _ = c ? this.floatInterpolateFunctionWithTangents(l, s.outTangent * h, u, a.inTangent * h, f) : this.floatInterpolateFunction(l, u, f);
                    switch (t.loopMode) {
                    case i.ANIMATIONLOOPMODE_CYCLE:
                    case i.ANIMATIONLOOPMODE_CONSTANT:
                        return _;
                    case i.ANIMATIONLOOPMODE_RELATIVE:
                        return t.offsetValue * t.repeatCount + _
                    }
                    break;
                case i.ANIMATIONTYPE_QUATERNION:
                    var g = c ? this.quaternionInterpolateFunctionWithTangents(l, s.outTangent.scale(h), u, a.inTangent.scale(h), f) : this.quaternionInterpolateFunction(l, u, f);
                    switch (t.loopMode) {
                    case i.ANIMATIONLOOPMODE_CYCLE:
                    case i.ANIMATIONLOOPMODE_CONSTANT:
                        return g;
                    case i.ANIMATIONLOOPMODE_RELATIVE:
                        return g.addInPlace(t.offsetValue.scale(t.repeatCount))
                    }
                    return g;
                case i.ANIMATIONTYPE_VECTOR3:
                    var m = c ? this.vector3InterpolateFunctionWithTangents(l, s.outTangent.scale(h), u, a.inTangent.scale(h), f) : this.vector3InterpolateFunction(l, u, f);
                    switch (t.loopMode) {
                    case i.ANIMATIONLOOPMODE_CYCLE:
                    case i.ANIMATIONLOOPMODE_CONSTANT:
                        return m;
                    case i.ANIMATIONLOOPMODE_RELATIVE:
                        return m.add(t.offsetValue.scale(t.repeatCount))
                    }
                case i.ANIMATIONTYPE_VECTOR2:
                    var v = c ? this.vector2InterpolateFunctionWithTangents(l, s.outTangent.scale(h), u, a.inTangent.scale(h), f) : this.vector2InterpolateFunction(l, u, f);
                    switch (t.loopMode) {
                    case i.ANIMATIONLOOPMODE_CYCLE:
                    case i.ANIMATIONLOOPMODE_CONSTANT:
                        return v;
                    case i.ANIMATIONLOOPMODE_RELATIVE:
                        return v.add(t.offsetValue.scale(t.repeatCount))
                    }
                case i.ANIMATIONTYPE_SIZE:
                    switch (t.loopMode) {
                    case i.ANIMATIONLOOPMODE_CYCLE:
                    case i.ANIMATIONLOOPMODE_CONSTANT:
                        return this.sizeInterpolateFunction(l, u, f);
                    case i.ANIMATIONLOOPMODE_RELATIVE:
                        return this.sizeInterpolateFunction(l, u, f).add(t.offsetValue.scale(t.repeatCount))
                    }
                case i.ANIMATIONTYPE_COLOR3:
                    var y = c ? this.color3InterpolateFunctionWithTangents(l, s.outTangent.scale(h), u, a.inTangent.scale(h), f) : this.color3InterpolateFunction(l, u, f);
                    switch (t.loopMode) {
                    case i.ANIMATIONLOOPMODE_CYCLE:
                    case i.ANIMATIONLOOPMODE_CONSTANT:
                        return y;
                    case i.ANIMATIONLOOPMODE_RELATIVE:
                        return y.add(t.offsetValue.scale(t.repeatCount))
                    }
                case i.ANIMATIONTYPE_COLOR4:
                    var b = c ? this.color4InterpolateFunctionWithTangents(l, s.outTangent.scale(h), u, a.inTangent.scale(h), f) : this.color4InterpolateFunction(l, u, f);
                    switch (t.loopMode) {
                    case i.ANIMATIONLOOPMODE_CYCLE:
                    case i.ANIMATIONLOOPMODE_CONSTANT:
                        return b;
                    case i.ANIMATIONLOOPMODE_RELATIVE:
                        return b.add(t.offsetValue.scale(t.repeatCount))
                    }
                case i.ANIMATIONTYPE_MATRIX:
                    switch (t.loopMode) {
                    case i.ANIMATIONLOOPMODE_CYCLE:
                    case i.ANIMATIONLOOPMODE_CONSTANT:
                        if (i.AllowMatricesInterpolation)
                            return this.matrixInterpolateFunction(l, u, f, t.workValue);
                    case i.ANIMATIONLOOPMODE_RELATIVE:
                        return l
                    }
                }
                break
            }
        }
        return this._getKeyValue(r[r.length - 1].value)
    }
    ,
    i.prototype.matrixInterpolateFunction = function(e, t, r, n) {
        return i.AllowMatrixDecomposeForInterpolation ? n ? (Matrix.DecomposeLerpToRef(e, t, r, n),
        n) : Matrix.DecomposeLerp(e, t, r) : n ? (Matrix.LerpToRef(e, t, r, n),
        n) : Matrix.Lerp(e, t, r)
    }
    ,
    i.prototype.clone = function() {
        var e = new i(this.name,this.targetPropertyPath.join("."),this.framePerSecond,this.dataType,this.loopMode);
        if (e.enableBlending = this.enableBlending,
        e.blendingSpeed = this.blendingSpeed,
        this._keys && e.setKeys(this._keys),
        this._ranges) {
            e._ranges = {};
            for (var t in this._ranges) {
                var r = this._ranges[t];
                !r || (e._ranges[t] = r.clone())
            }
        }
        return e
    }
    ,
    i.prototype.setKeys = function(e) {
        this._keys = e.slice(0)
    }
    ,
    i.prototype.serialize = function() {
        var e = {};
        e.name = this.name,
        e.property = this.targetProperty,
        e.framePerSecond = this.framePerSecond,
        e.dataType = this.dataType,
        e.loopBehavior = this.loopMode,
        e.enableBlending = this.enableBlending,
        e.blendingSpeed = this.blendingSpeed;
        var t = this.dataType;
        e.keys = [];
        for (var r = this.getKeys(), n = 0; n < r.length; n++) {
            var o = r[n]
              , a = {};
            switch (a.frame = o.frame,
            t) {
            case i.ANIMATIONTYPE_FLOAT:
                a.values = [o.value],
                o.inTangent !== void 0 && a.values.push(o.inTangent),
                o.outTangent !== void 0 && (o.inTangent === void 0 && a.values.push(void 0),
                a.values.push(o.outTangent));
                break;
            case i.ANIMATIONTYPE_QUATERNION:
            case i.ANIMATIONTYPE_MATRIX:
            case i.ANIMATIONTYPE_VECTOR3:
            case i.ANIMATIONTYPE_COLOR3:
            case i.ANIMATIONTYPE_COLOR4:
                a.values = o.value.asArray(),
                o.inTangent != null && a.values.push(o.inTangent.asArray()),
                o.outTangent != null && (o.inTangent === void 0 && a.values.push(void 0),
                a.values.push(o.outTangent.asArray()));
                break
            }
            e.keys.push(a)
        }
        e.ranges = [];
        for (var s in this._ranges) {
            var l = this._ranges[s];
            if (!!l) {
                var u = {};
                u.name = s,
                u.from = l.from,
                u.to = l.to,
                e.ranges.push(u)
            }
        }
        return e
    }
    ,
    i._UniversalLerp = function(e, t, r) {
        var n = e.constructor;
        return n.Lerp ? n.Lerp(e, t, r) : n.Slerp ? n.Slerp(e, t, r) : e.toFixed ? e * (1 - r) + r * t : t
    }
    ,
    i.Parse = function(e) {
        var t = new i(e.name,e.property,e.framePerSecond,e.dataType,e.loopBehavior), r = e.dataType, n = [], o, a;
        for (e.enableBlending && (t.enableBlending = e.enableBlending),
        e.blendingSpeed && (t.blendingSpeed = e.blendingSpeed),
        a = 0; a < e.keys.length; a++) {
            var s = e.keys[a]
              , l = void 0
              , u = void 0;
            switch (r) {
            case i.ANIMATIONTYPE_FLOAT:
                o = s.values[0],
                s.values.length >= 1 && (l = s.values[1]),
                s.values.length >= 2 && (u = s.values[2]);
                break;
            case i.ANIMATIONTYPE_QUATERNION:
                if (o = Quaternion.FromArray(s.values),
                s.values.length >= 8) {
                    var c = Quaternion.FromArray(s.values.slice(4, 8));
                    c.equals(Quaternion.Zero()) || (l = c)
                }
                if (s.values.length >= 12) {
                    var h = Quaternion.FromArray(s.values.slice(8, 12));
                    h.equals(Quaternion.Zero()) || (u = h)
                }
                break;
            case i.ANIMATIONTYPE_MATRIX:
                o = Matrix.FromArray(s.values);
                break;
            case i.ANIMATIONTYPE_COLOR3:
                o = Color3.FromArray(s.values),
                s.values[3] && (l = Color3.FromArray(s.values[3])),
                s.values[4] && (u = Color3.FromArray(s.values[4]));
                break;
            case i.ANIMATIONTYPE_COLOR4:
                o = Color4.FromArray(s.values),
                s.values[4] && (l = Color4.FromArray(s.values[4])),
                s.values[5] && (u = Color4.FromArray(s.values[5]));
                break;
            case i.ANIMATIONTYPE_VECTOR3:
            default:
                o = Vector3.FromArray(s.values),
                s.values[3] && (l = Vector3.FromArray(s.values[3])),
                s.values[4] && (u = Vector3.FromArray(s.values[4]));
                break
            }
            var f = {};
            f.frame = s.frame,
            f.value = o,
            l != null && (f.inTangent = l),
            u != null && (f.outTangent = u),
            n.push(f)
        }
        if (t.setKeys(n),
        e.ranges)
            for (a = 0; a < e.ranges.length; a++)
                o = e.ranges[a],
                t.createRange(o.name, o.from, o.to);
        return t
    }
    ,
    i.AppendSerializedAnimations = function(e, t) {
        SerializationHelper.AppendSerializedAnimations(e, t)
    }
    ,
    i.ParseFromFileAsync = function(e, t) {
        var r = this;
        return new Promise(function(n, o) {
            var a = new WebRequest;
            a.addEventListener("readystatechange", function() {
                if (a.readyState == 4)
                    if (a.status == 200) {
                        var s = JSON.parse(a.responseText);
                        if (s.length) {
                            for (var l = new Array, u = 0, c = s; u < c.length; u++) {
                                var h = c[u];
                                l.push(r.Parse(h))
                            }
                            n(l)
                        } else {
                            var l = r.Parse(s);
                            e && (l.name = e),
                            n(l)
                        }
                    } else
                        o("Unable to load the animation")
            }),
            a.open("GET", t),
            a.send()
        }
        )
    }
    ,
    i.CreateFromSnippetAsync = function(e) {
        var t = this;
        return new Promise(function(r, n) {
            var o = new WebRequest;
            o.addEventListener("readystatechange", function() {
                if (o.readyState == 4)
                    if (o.status == 200) {
                        var a = JSON.parse(JSON.parse(o.responseText).jsonPayload);
                        if (a.animations) {
                            for (var s = JSON.parse(a.animations), l = new Array, u = 0, c = s.animations; u < c.length; u++) {
                                var h = c[u]
                                  , f = t.Parse(h);
                                f.snippetId = e,
                                l.push(f)
                            }
                            r(l)
                        } else {
                            var s = JSON.parse(a.animation)
                              , f = t.Parse(s);
                            f.snippetId = e,
                            r(f)
                        }
                    } else
                        n("Unable to load the snippet " + e)
            }),
            o.open("GET", t.SnippetUrl + "/" + e.replace(/#/g, "/")),
            o.send()
        }
        )
    }
    ,
    i._UniqueIdGenerator = 0,
    i.AllowMatricesInterpolation = !1,
    i.AllowMatrixDecomposeForInterpolation = !0,
    i.SnippetUrl = "https://snippet.babylonjs.com",
    i.ANIMATIONTYPE_FLOAT = 0,
    i.ANIMATIONTYPE_VECTOR3 = 1,
    i.ANIMATIONTYPE_QUATERNION = 2,
    i.ANIMATIONTYPE_MATRIX = 3,
    i.ANIMATIONTYPE_COLOR3 = 4,
    i.ANIMATIONTYPE_COLOR4 = 7,
    i.ANIMATIONTYPE_VECTOR2 = 5,
    i.ANIMATIONTYPE_SIZE = 6,
    i.ANIMATIONLOOPMODE_RELATIVE = 0,
    i.ANIMATIONLOOPMODE_CYCLE = 1,
    i.ANIMATIONLOOPMODE_CONSTANT = 2,
    i
}();
RegisterClass("BABYLON.Animation", Animation);
Node$2._AnimationRangeFactory = function(i, e, t) {
    return new AnimationRange(i,e,t)
}
;
var _staticOffsetValueQuaternion = Object.freeze(new Quaternion(0,0,0,0)), _staticOffsetValueVector3 = Object.freeze(Vector3.Zero()), _staticOffsetValueVector2 = Object.freeze(Vector2.Zero()), _staticOffsetValueSize = Object.freeze(Size.Zero()), _staticOffsetValueColor3 = Object.freeze(Color3.Black()), RuntimeAnimation = function() {
    function i(e, t, r, n) {
        var o = this;
        if (this._events = new Array,
        this._currentFrame = 0,
        this._originalValue = new Array,
        this._originalBlendValue = null,
        this._offsetsCache = {},
        this._highLimitsCache = {},
        this._stopped = !1,
        this._blendingFactor = 0,
        this._currentValue = null,
        this._currentActiveTarget = null,
        this._directTarget = null,
        this._targetPath = "",
        this._weight = 1,
        this._ratioOffset = 0,
        this._previousDelay = 0,
        this._previousRatio = 0,
        this._targetIsArray = !1,
        this._animation = t,
        this._target = e,
        this._scene = r,
        this._host = n,
        this._activeTargets = [],
        t._runtimeAnimations.push(this),
        this._animationState = {
            key: 0,
            repeatCount: 0,
            loopMode: this._getCorrectLoopMode()
        },
        this._animation.dataType === Animation.ANIMATIONTYPE_MATRIX && (this._animationState.workValue = Matrix.Zero()),
        this._keys = this._animation.getKeys(),
        this._minFrame = this._keys[0].frame,
        this._maxFrame = this._keys[this._keys.length - 1].frame,
        this._minValue = this._keys[0].value,
        this._maxValue = this._keys[this._keys.length - 1].value,
        this._minFrame !== 0) {
            var a = {
                frame: 0,
                value: this._minValue
            };
            this._keys.splice(0, 0, a)
        }
        if (this._target instanceof Array) {
            for (var s = 0, l = 0, u = this._target; l < u.length; l++) {
                var c = u[l];
                this._preparePath(c, s),
                this._getOriginalValues(s),
                s++
            }
            this._targetIsArray = !0
        } else
            this._preparePath(this._target),
            this._getOriginalValues(),
            this._targetIsArray = !1,
            this._directTarget = this._activeTargets[0];
        var h = t.getEvents();
        h && h.length > 0 && h.forEach(function(f) {
            o._events.push(f._clone())
        }),
        this._enableBlending = e && e.animationPropertiesOverride ? e.animationPropertiesOverride.enableBlending : this._animation.enableBlending
    }
    return Object.defineProperty(i.prototype, "currentFrame", {
        get: function() {
            return this._currentFrame
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "weight", {
        get: function() {
            return this._weight
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "currentValue", {
        get: function() {
            return this._currentValue
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "targetPath", {
        get: function() {
            return this._targetPath
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "target", {
        get: function() {
            return this._currentActiveTarget
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "isAdditive", {
        get: function() {
            return this._host && this._host.isAdditive
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype._preparePath = function(e, t) {
        t === void 0 && (t = 0);
        var r = this._animation.targetPropertyPath;
        if (r.length > 1) {
            for (var n = e[r[0]], o = 1; o < r.length - 1; o++)
                n = n[r[o]];
            this._targetPath = r[r.length - 1],
            this._activeTargets[t] = n
        } else
            this._targetPath = r[0],
            this._activeTargets[t] = e
    }
    ,
    Object.defineProperty(i.prototype, "animation", {
        get: function() {
            return this._animation
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.reset = function(e) {
        if (e === void 0 && (e = !1),
        e)
            if (this._target instanceof Array)
                for (var t = 0, r = 0, n = this._target; r < n.length; r++) {
                    var o = n[r];
                    this._originalValue[t] !== void 0 && this._setValue(o, this._activeTargets[t], this._originalValue[t], -1, t),
                    t++
                }
            else
                this._originalValue[0] !== void 0 && this._setValue(this._target, this._directTarget, this._originalValue[0], -1, 0);
        this._offsetsCache = {},
        this._highLimitsCache = {},
        this._currentFrame = 0,
        this._blendingFactor = 0;
        for (var t = 0; t < this._events.length; t++)
            this._events[t].isDone = !1
    }
    ,
    i.prototype.isStopped = function() {
        return this._stopped
    }
    ,
    i.prototype.dispose = function() {
        var e = this._animation.runtimeAnimations.indexOf(this);
        e > -1 && this._animation.runtimeAnimations.splice(e, 1)
    }
    ,
    i.prototype.setValue = function(e, t) {
        if (this._targetIsArray) {
            for (var r = 0; r < this._target.length; r++) {
                var n = this._target[r];
                this._setValue(n, this._activeTargets[r], e, t, r)
            }
            return
        }
        this._setValue(this._target, this._directTarget, e, t, 0)
    }
    ,
    i.prototype._getOriginalValues = function(e) {
        e === void 0 && (e = 0);
        var t, r = this._activeTargets[e];
        r.getRestPose && this._targetPath === "_matrix" ? t = r.getRestPose() : t = r[this._targetPath],
        t && t.clone ? this._originalValue[e] = t.clone() : this._originalValue[e] = t
    }
    ,
    i.prototype._setValue = function(e, t, r, n, o) {
        if (this._currentActiveTarget = t,
        this._weight = n,
        this._enableBlending && this._blendingFactor <= 1) {
            if (!this._originalBlendValue) {
                var a = t[this._targetPath];
                a.clone ? this._originalBlendValue = a.clone() : this._originalBlendValue = a
            }
            this._originalBlendValue.m ? Animation.AllowMatrixDecomposeForInterpolation ? this._currentValue ? Matrix.DecomposeLerpToRef(this._originalBlendValue, r, this._blendingFactor, this._currentValue) : this._currentValue = Matrix.DecomposeLerp(this._originalBlendValue, r, this._blendingFactor) : this._currentValue ? Matrix.LerpToRef(this._originalBlendValue, r, this._blendingFactor, this._currentValue) : this._currentValue = Matrix.Lerp(this._originalBlendValue, r, this._blendingFactor) : this._currentValue = Animation._UniversalLerp(this._originalBlendValue, r, this._blendingFactor);
            var s = e && e.animationPropertiesOverride ? e.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
            this._blendingFactor += s
        } else
            this._currentValue ? this._currentValue.copyFrom ? this._currentValue.copyFrom(r) : this._currentValue = r : r != null && r.clone ? this._currentValue = r.clone() : this._currentValue = r;
        n !== -1 ? this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[o]) : t[this._targetPath] = this._currentValue,
        e.markAsDirty && e.markAsDirty(this._animation.targetProperty)
    }
    ,
    i.prototype._getCorrectLoopMode = function() {
        return this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.loopMode : this._animation.loopMode
    }
    ,
    i.prototype.goToFrame = function(e) {
        var t = this._animation.getKeys();
        e < t[0].frame ? e = t[0].frame : e > t[t.length - 1].frame && (e = t[t.length - 1].frame);
        var r = this._events;
        if (r.length)
            for (var n = 0; n < r.length; n++)
                r[n].onlyOnce || (r[n].isDone = r[n].frame < e);
        this._currentFrame = e;
        var o = this._animation._interpolate(e, this._animationState);
        this.setValue(o, -1)
    }
    ,
    i.prototype._prepareForSpeedRatioChange = function(e) {
        var t = this._previousDelay * (this._animation.framePerSecond * e) / 1e3;
        this._ratioOffset = this._previousRatio - t
    }
    ,
    i.prototype.animate = function(e, t, r, n, o, a) {
        a === void 0 && (a = -1);
        var s = this._animation
          , l = s.targetPropertyPath;
        if (!l || l.length < 1)
            return this._stopped = !0,
            !1;
        var u = !0;
        (t < this._minFrame || t > this._maxFrame) && (t = this._minFrame),
        (r < this._minFrame || r > this._maxFrame) && (r = this._maxFrame);
        var c = r - t, h, f = e * (s.framePerSecond * o) / 1e3 + this._ratioOffset, d = 0;
        if (this._previousDelay = e,
        this._previousRatio = f,
        !n && r >= t && f >= c)
            u = !1,
            d = s._getKeyValue(this._maxValue);
        else if (!n && t >= r && f <= c)
            u = !1,
            d = s._getKeyValue(this._minValue);
        else if (this._animationState.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
            var _ = r.toString() + t.toString();
            if (!this._offsetsCache[_]) {
                this._animationState.repeatCount = 0,
                this._animationState.loopMode = Animation.ANIMATIONLOOPMODE_CYCLE;
                var g = s._interpolate(t, this._animationState)
                  , m = s._interpolate(r, this._animationState);
                switch (this._animationState.loopMode = this._getCorrectLoopMode(),
                s.dataType) {
                case Animation.ANIMATIONTYPE_FLOAT:
                    this._offsetsCache[_] = m - g;
                    break;
                case Animation.ANIMATIONTYPE_QUATERNION:
                    this._offsetsCache[_] = m.subtract(g);
                    break;
                case Animation.ANIMATIONTYPE_VECTOR3:
                    this._offsetsCache[_] = m.subtract(g);
                    break;
                case Animation.ANIMATIONTYPE_VECTOR2:
                    this._offsetsCache[_] = m.subtract(g);
                    break;
                case Animation.ANIMATIONTYPE_SIZE:
                    this._offsetsCache[_] = m.subtract(g);
                    break;
                case Animation.ANIMATIONTYPE_COLOR3:
                    this._offsetsCache[_] = m.subtract(g);
                    break
                }
                this._highLimitsCache[_] = m
            }
            d = this._highLimitsCache[_],
            h = this._offsetsCache[_]
        }
        if (h === void 0)
            switch (s.dataType) {
            case Animation.ANIMATIONTYPE_FLOAT:
                h = 0;
                break;
            case Animation.ANIMATIONTYPE_QUATERNION:
                h = _staticOffsetValueQuaternion;
                break;
            case Animation.ANIMATIONTYPE_VECTOR3:
                h = _staticOffsetValueVector3;
                break;
            case Animation.ANIMATIONTYPE_VECTOR2:
                h = _staticOffsetValueVector2;
                break;
            case Animation.ANIMATIONTYPE_SIZE:
                h = _staticOffsetValueSize;
                break;
            case Animation.ANIMATIONTYPE_COLOR3:
                h = _staticOffsetValueColor3
            }
        var v;
        if (this._host && this._host.syncRoot) {
            var y = this._host.syncRoot
              , b = (y.masterFrame - y.fromFrame) / (y.toFrame - y.fromFrame);
            v = t + (r - t) * b
        } else
            f > 0 && t > r || f < 0 && t < r ? v = u && c !== 0 ? r + f % c : t : v = u && c !== 0 ? t + f % c : r;
        var T = this._events;
        if ((o > 0 && this.currentFrame > v || o < 0 && this.currentFrame < v) && (this._onLoop(),
        T.length))
            for (var C = 0; C < T.length; C++)
                T[C].onlyOnce || (T[C].isDone = !1);
        this._currentFrame = v,
        this._animationState.repeatCount = c === 0 ? 0 : f / c >> 0,
        this._animationState.highLimitValue = d,
        this._animationState.offsetValue = h;
        var A = s._interpolate(v, this._animationState);
        if (this.setValue(A, a),
        T.length) {
            for (var C = 0; C < T.length; C++)
                if (c > 0 && v >= T[C].frame && T[C].frame >= t || c < 0 && v <= T[C].frame && T[C].frame <= t) {
                    var S = T[C];
                    S.isDone || (S.onlyOnce && (T.splice(C, 1),
                    C--),
                    S.isDone = !0,
                    S.action(v))
                }
        }
        return u || (this._stopped = !0),
        u
    }
    ,
    i
}(), Space;
(function(i) {
    i[i.LOCAL = 0] = "LOCAL",
    i[i.WORLD = 1] = "WORLD",
    i[i.BONE = 2] = "BONE"
}
)(Space || (Space = {}));
var Axis = function() {
    function i() {}
    return i.X = new Vector3(1,0,0),
    i.Y = new Vector3(0,1,0),
    i.Z = new Vector3(0,0,1),
    i
}(), Coordinate;
(function(i) {
    i[i.X = 0] = "X",
    i[i.Y = 1] = "Y",
    i[i.Z = 2] = "Z"
}
)(Coordinate || (Coordinate = {}));
var Bone = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a, s, l) {
        n === void 0 && (n = null),
        o === void 0 && (o = null),
        a === void 0 && (a = null),
        s === void 0 && (s = null),
        l === void 0 && (l = null);
        var u = i.call(this, t, r.getScene()) || this;
        return u.name = t,
        u.children = new Array,
        u.animations = new Array,
        u._index = null,
        u._absoluteTransform = new Matrix,
        u._invertedAbsoluteTransform = new Matrix,
        u._scalingDeterminant = 1,
        u._worldTransform = new Matrix,
        u._needToDecompose = !0,
        u._needToCompose = !1,
        u._linkedTransformNode = null,
        u._waitingTransformNodeId = null,
        u._skeleton = r,
        u._localMatrix = o ? o.clone() : Matrix.Identity(),
        u._restPose = a || u._localMatrix.clone(),
        u._baseMatrix = s || u._localMatrix.clone(),
        u._index = l,
        r.bones.push(u),
        u.setParent(n, !1),
        (s || o) && u._updateDifferenceMatrix(),
        u
    }
    return Object.defineProperty(e.prototype, "_matrix", {
        get: function() {
            return this._compose(),
            this._localMatrix
        },
        set: function(t) {
            this._needToCompose = !1,
            t.updateFlag !== this._localMatrix.updateFlag && (this._localMatrix.copyFrom(t),
            this._markAsDirtyAndDecompose())
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getClassName = function() {
        return "Bone"
    }
    ,
    e.prototype.getSkeleton = function() {
        return this._skeleton
    }
    ,
    e.prototype.getParent = function() {
        return this._parent
    }
    ,
    e.prototype.getChildren = function() {
        return this.children
    }
    ,
    e.prototype.getIndex = function() {
        return this._index === null ? this.getSkeleton().bones.indexOf(this) : this._index
    }
    ,
    e.prototype.setParent = function(t, r) {
        if (r === void 0 && (r = !0),
        this._parent !== t) {
            if (this._parent) {
                var n = this._parent.children.indexOf(this);
                n !== -1 && this._parent.children.splice(n, 1)
            }
            this._parent = t,
            this._parent && this._parent.children.push(this),
            r && this._updateDifferenceMatrix(),
            this.markAsDirty()
        }
    }
    ,
    e.prototype.getLocalMatrix = function() {
        return this._compose(),
        this._localMatrix
    }
    ,
    e.prototype.getBaseMatrix = function() {
        return this._baseMatrix
    }
    ,
    e.prototype.getRestPose = function() {
        return this._restPose
    }
    ,
    e.prototype.setRestPose = function(t) {
        this._restPose.copyFrom(t)
    }
    ,
    e.prototype.getBindPose = function() {
        return this._baseMatrix
    }
    ,
    e.prototype.setBindPose = function(t) {
        this.updateMatrix(t)
    }
    ,
    e.prototype.getWorldMatrix = function() {
        return this._worldTransform
    }
    ,
    e.prototype.returnToRest = function() {
        var t;
        if (this._linkedTransformNode) {
            var r = TmpVectors.Vector3[0]
              , n = TmpVectors.Quaternion[0]
              , o = TmpVectors.Vector3[1];
            this.getRestPose().decompose(r, n, o),
            this._linkedTransformNode.position.copyFrom(o),
            this._linkedTransformNode.rotationQuaternion = (t = this._linkedTransformNode.rotationQuaternion) !== null && t !== void 0 ? t : Quaternion.Identity(),
            this._linkedTransformNode.rotationQuaternion.copyFrom(n),
            this._linkedTransformNode.scaling.copyFrom(r)
        } else
            this._matrix = this._restPose
    }
    ,
    e.prototype.getInvertedAbsoluteTransform = function() {
        return this._invertedAbsoluteTransform
    }
    ,
    e.prototype.getAbsoluteTransform = function() {
        return this._absoluteTransform
    }
    ,
    e.prototype.linkTransformNode = function(t) {
        this._linkedTransformNode && this._skeleton._numBonesWithLinkedTransformNode--,
        this._linkedTransformNode = t,
        this._linkedTransformNode && this._skeleton._numBonesWithLinkedTransformNode++
    }
    ,
    e.prototype.getTransformNode = function() {
        return this._linkedTransformNode
    }
    ,
    Object.defineProperty(e.prototype, "position", {
        get: function() {
            return this._decompose(),
            this._localPosition
        },
        set: function(t) {
            this._decompose(),
            this._localPosition.copyFrom(t),
            this._markAsDirtyAndCompose()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "rotation", {
        get: function() {
            return this.getRotation()
        },
        set: function(t) {
            this.setRotation(t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "rotationQuaternion", {
        get: function() {
            return this._decompose(),
            this._localRotation
        },
        set: function(t) {
            this.setRotationQuaternion(t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "scaling", {
        get: function() {
            return this.getScale()
        },
        set: function(t) {
            this.setScale(t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "animationPropertiesOverride", {
        get: function() {
            return this._skeleton.animationPropertiesOverride
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._decompose = function() {
        !this._needToDecompose || (this._needToDecompose = !1,
        this._localScaling || (this._localScaling = Vector3.Zero(),
        this._localRotation = Quaternion.Zero(),
        this._localPosition = Vector3.Zero()),
        this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition))
    }
    ,
    e.prototype._compose = function() {
        if (!!this._needToCompose) {
            if (!this._localScaling) {
                this._needToCompose = !1;
                return
            }
            this._needToCompose = !1,
            Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix)
        }
    }
    ,
    e.prototype.updateMatrix = function(t, r, n) {
        r === void 0 && (r = !0),
        n === void 0 && (n = !0),
        this._baseMatrix.copyFrom(t),
        r && this._updateDifferenceMatrix(),
        n ? this._matrix = t : this.markAsDirty()
    }
    ,
    e.prototype._updateDifferenceMatrix = function(t, r) {
        if (r === void 0 && (r = !0),
        t || (t = this._baseMatrix),
        this._parent ? t.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform) : this._absoluteTransform.copyFrom(t),
        this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform),
        r)
            for (var n = 0; n < this.children.length; n++)
                this.children[n]._updateDifferenceMatrix();
        this._scalingDeterminant = this._absoluteTransform.determinant() < 0 ? -1 : 1
    }
    ,
    e.prototype.markAsDirty = function(t) {
        return this._currentRenderId++,
        this._childUpdateId++,
        this._skeleton._markAsDirty(),
        this
    }
    ,
    e.prototype._markAsDirtyAndCompose = function() {
        this.markAsDirty(),
        this._needToCompose = !0
    }
    ,
    e.prototype._markAsDirtyAndDecompose = function() {
        this.markAsDirty(),
        this._needToDecompose = !0
    }
    ,
    e.prototype.translate = function(t, r, n) {
        r === void 0 && (r = Space.LOCAL);
        var o = this.getLocalMatrix();
        if (r == Space.LOCAL)
            o.addAtIndex(12, t.x),
            o.addAtIndex(13, t.y),
            o.addAtIndex(14, t.z);
        else {
            var a = null;
            n && (a = n.getWorldMatrix()),
            this._skeleton.computeAbsoluteTransforms();
            var s = e._tmpMats[0]
              , l = e._tmpVecs[0];
            this._parent ? n && a ? (s.copyFrom(this._parent.getAbsoluteTransform()),
            s.multiplyToRef(a, s)) : s.copyFrom(this._parent.getAbsoluteTransform()) : Matrix.IdentityToRef(s),
            s.setTranslationFromFloats(0, 0, 0),
            s.invert(),
            Vector3.TransformCoordinatesToRef(t, s, l),
            o.addAtIndex(12, l.x),
            o.addAtIndex(13, l.y),
            o.addAtIndex(14, l.z)
        }
        this._markAsDirtyAndDecompose()
    }
    ,
    e.prototype.setPosition = function(t, r, n) {
        r === void 0 && (r = Space.LOCAL);
        var o = this.getLocalMatrix();
        if (r == Space.LOCAL)
            o.setTranslationFromFloats(t.x, t.y, t.z);
        else {
            var a = null;
            n && (a = n.getWorldMatrix()),
            this._skeleton.computeAbsoluteTransforms();
            var s = e._tmpMats[0]
              , l = e._tmpVecs[0];
            this._parent ? (n && a ? (s.copyFrom(this._parent.getAbsoluteTransform()),
            s.multiplyToRef(a, s)) : s.copyFrom(this._parent.getAbsoluteTransform()),
            s.invert()) : Matrix.IdentityToRef(s),
            Vector3.TransformCoordinatesToRef(t, s, l),
            o.setTranslationFromFloats(l.x, l.y, l.z)
        }
        this._markAsDirtyAndDecompose()
    }
    ,
    e.prototype.setAbsolutePosition = function(t, r) {
        this.setPosition(t, Space.WORLD, r)
    }
    ,
    e.prototype.scale = function(t, r, n, o) {
        o === void 0 && (o = !1);
        var a = this.getLocalMatrix()
          , s = e._tmpMats[0];
        Matrix.ScalingToRef(t, r, n, s),
        s.multiplyToRef(a, a),
        s.invert();
        for (var l = 0, u = this.children; l < u.length; l++) {
            var c = u[l]
              , h = c.getLocalMatrix();
            h.multiplyToRef(s, h),
            h.multiplyAtIndex(12, t),
            h.multiplyAtIndex(13, r),
            h.multiplyAtIndex(14, n),
            c._markAsDirtyAndDecompose()
        }
        if (this._markAsDirtyAndDecompose(),
        o)
            for (var f = 0, d = this.children; f < d.length; f++) {
                var c = d[f];
                c.scale(t, r, n, o)
            }
    }
    ,
    e.prototype.setScale = function(t) {
        this._decompose(),
        this._localScaling.copyFrom(t),
        this._markAsDirtyAndCompose()
    }
    ,
    e.prototype.getScale = function() {
        return this._decompose(),
        this._localScaling
    }
    ,
    e.prototype.getScaleToRef = function(t) {
        this._decompose(),
        t.copyFrom(this._localScaling)
    }
    ,
    e.prototype.setYawPitchRoll = function(t, r, n, o, a) {
        if (o === void 0 && (o = Space.LOCAL),
        o === Space.LOCAL) {
            var s = e._tmpQuat;
            Quaternion.RotationYawPitchRollToRef(t, r, n, s),
            this.setRotationQuaternion(s, o, a);
            return
        }
        var l = e._tmpMats[0];
        if (!!this._getNegativeRotationToRef(l, a)) {
            var u = e._tmpMats[1];
            Matrix.RotationYawPitchRollToRef(t, r, n, u),
            l.multiplyToRef(u, u),
            this._rotateWithMatrix(u, o, a)
        }
    }
    ,
    e.prototype.rotate = function(t, r, n, o) {
        n === void 0 && (n = Space.LOCAL);
        var a = e._tmpMats[0];
        a.setTranslationFromFloats(0, 0, 0),
        Matrix.RotationAxisToRef(t, r, a),
        this._rotateWithMatrix(a, n, o)
    }
    ,
    e.prototype.setAxisAngle = function(t, r, n, o) {
        if (n === void 0 && (n = Space.LOCAL),
        n === Space.LOCAL) {
            var a = e._tmpQuat;
            Quaternion.RotationAxisToRef(t, r, a),
            this.setRotationQuaternion(a, n, o);
            return
        }
        var s = e._tmpMats[0];
        if (!!this._getNegativeRotationToRef(s, o)) {
            var l = e._tmpMats[1];
            Matrix.RotationAxisToRef(t, r, l),
            s.multiplyToRef(l, l),
            this._rotateWithMatrix(l, n, o)
        }
    }
    ,
    e.prototype.setRotation = function(t, r, n) {
        r === void 0 && (r = Space.LOCAL),
        this.setYawPitchRoll(t.y, t.x, t.z, r, n)
    }
    ,
    e.prototype.setRotationQuaternion = function(t, r, n) {
        if (r === void 0 && (r = Space.LOCAL),
        r === Space.LOCAL) {
            this._decompose(),
            this._localRotation.copyFrom(t),
            this._markAsDirtyAndCompose();
            return
        }
        var o = e._tmpMats[0];
        if (!!this._getNegativeRotationToRef(o, n)) {
            var a = e._tmpMats[1];
            Matrix.FromQuaternionToRef(t, a),
            o.multiplyToRef(a, a),
            this._rotateWithMatrix(a, r, n)
        }
    }
    ,
    e.prototype.setRotationMatrix = function(t, r, n) {
        if (r === void 0 && (r = Space.LOCAL),
        r === Space.LOCAL) {
            var o = e._tmpQuat;
            Quaternion.FromRotationMatrixToRef(t, o),
            this.setRotationQuaternion(o, r, n);
            return
        }
        var a = e._tmpMats[0];
        if (!!this._getNegativeRotationToRef(a, n)) {
            var s = e._tmpMats[1];
            s.copyFrom(t),
            a.multiplyToRef(t, s),
            this._rotateWithMatrix(s, r, n)
        }
    }
    ,
    e.prototype._rotateWithMatrix = function(t, r, n) {
        r === void 0 && (r = Space.LOCAL);
        var o = this.getLocalMatrix()
          , a = o.m[12]
          , s = o.m[13]
          , l = o.m[14]
          , u = this.getParent()
          , c = e._tmpMats[3]
          , h = e._tmpMats[4];
        u && r == Space.WORLD ? (n ? (c.copyFrom(n.getWorldMatrix()),
        u.getAbsoluteTransform().multiplyToRef(c, c)) : c.copyFrom(u.getAbsoluteTransform()),
        h.copyFrom(c),
        h.invert(),
        o.multiplyToRef(c, o),
        o.multiplyToRef(t, o),
        o.multiplyToRef(h, o)) : r == Space.WORLD && n ? (c.copyFrom(n.getWorldMatrix()),
        h.copyFrom(c),
        h.invert(),
        o.multiplyToRef(c, o),
        o.multiplyToRef(t, o),
        o.multiplyToRef(h, o)) : o.multiplyToRef(t, o),
        o.setTranslationFromFloats(a, s, l),
        this.computeAbsoluteTransforms(),
        this._markAsDirtyAndDecompose()
    }
    ,
    e.prototype._getNegativeRotationToRef = function(t, r) {
        var n = e._tmpMats[2];
        return t.copyFrom(this.getAbsoluteTransform()),
        r && (t.multiplyToRef(r.getWorldMatrix(), t),
        Matrix.ScalingToRef(r.scaling.x, r.scaling.y, r.scaling.z, n)),
        t.invert(),
        isNaN(t.m[0]) ? !1 : (n.multiplyAtIndex(0, this._scalingDeterminant),
        t.multiplyToRef(n, t),
        !0)
    }
    ,
    e.prototype.getPosition = function(t, r) {
        t === void 0 && (t = Space.LOCAL),
        r === void 0 && (r = null);
        var n = Vector3.Zero();
        return this.getPositionToRef(t, r, n),
        n
    }
    ,
    e.prototype.getPositionToRef = function(t, r, n) {
        if (t === void 0 && (t = Space.LOCAL),
        t == Space.LOCAL) {
            var o = this.getLocalMatrix();
            n.x = o.m[12],
            n.y = o.m[13],
            n.z = o.m[14]
        } else {
            var a = null;
            r && (a = r.getWorldMatrix()),
            this._skeleton.computeAbsoluteTransforms();
            var s = e._tmpMats[0];
            r && a ? (s.copyFrom(this.getAbsoluteTransform()),
            s.multiplyToRef(a, s)) : s = this.getAbsoluteTransform(),
            n.x = s.m[12],
            n.y = s.m[13],
            n.z = s.m[14]
        }
    }
    ,
    e.prototype.getAbsolutePosition = function(t) {
        t === void 0 && (t = null);
        var r = Vector3.Zero();
        return this.getPositionToRef(Space.WORLD, t, r),
        r
    }
    ,
    e.prototype.getAbsolutePositionToRef = function(t, r) {
        this.getPositionToRef(Space.WORLD, t, r)
    }
    ,
    e.prototype.computeAbsoluteTransforms = function() {
        if (this._compose(),
        this._parent)
            this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
        else {
            this._absoluteTransform.copyFrom(this._localMatrix);
            var t = this._skeleton.getPoseMatrix();
            t && this._absoluteTransform.multiplyToRef(t, this._absoluteTransform)
        }
        for (var r = this.children, n = r.length, o = 0; o < n; o++)
            r[o].computeAbsoluteTransforms()
    }
    ,
    e.prototype.getDirection = function(t, r) {
        r === void 0 && (r = null);
        var n = Vector3.Zero();
        return this.getDirectionToRef(t, r, n),
        n
    }
    ,
    e.prototype.getDirectionToRef = function(t, r, n) {
        r === void 0 && (r = null);
        var o = null;
        r && (o = r.getWorldMatrix()),
        this._skeleton.computeAbsoluteTransforms();
        var a = e._tmpMats[0];
        a.copyFrom(this.getAbsoluteTransform()),
        r && o && a.multiplyToRef(o, a),
        Vector3.TransformNormalToRef(t, a, n),
        n.normalize()
    }
    ,
    e.prototype.getRotation = function(t, r) {
        t === void 0 && (t = Space.LOCAL),
        r === void 0 && (r = null);
        var n = Vector3.Zero();
        return this.getRotationToRef(t, r, n),
        n
    }
    ,
    e.prototype.getRotationToRef = function(t, r, n) {
        t === void 0 && (t = Space.LOCAL),
        r === void 0 && (r = null);
        var o = e._tmpQuat;
        this.getRotationQuaternionToRef(t, r, o),
        o.toEulerAnglesToRef(n)
    }
    ,
    e.prototype.getRotationQuaternion = function(t, r) {
        t === void 0 && (t = Space.LOCAL),
        r === void 0 && (r = null);
        var n = Quaternion.Identity();
        return this.getRotationQuaternionToRef(t, r, n),
        n
    }
    ,
    e.prototype.getRotationQuaternionToRef = function(t, r, n) {
        if (t === void 0 && (t = Space.LOCAL),
        r === void 0 && (r = null),
        t == Space.LOCAL)
            this._decompose(),
            n.copyFrom(this._localRotation);
        else {
            var o = e._tmpMats[0]
              , a = this.getAbsoluteTransform();
            r ? a.multiplyToRef(r.getWorldMatrix(), o) : o.copyFrom(a),
            o.multiplyAtIndex(0, this._scalingDeterminant),
            o.multiplyAtIndex(1, this._scalingDeterminant),
            o.multiplyAtIndex(2, this._scalingDeterminant),
            o.decompose(void 0, n, void 0)
        }
    }
    ,
    e.prototype.getRotationMatrix = function(t, r) {
        t === void 0 && (t = Space.LOCAL);
        var n = Matrix.Identity();
        return this.getRotationMatrixToRef(t, r, n),
        n
    }
    ,
    e.prototype.getRotationMatrixToRef = function(t, r, n) {
        if (t === void 0 && (t = Space.LOCAL),
        t == Space.LOCAL)
            this.getLocalMatrix().getRotationMatrixToRef(n);
        else {
            var o = e._tmpMats[0]
              , a = this.getAbsoluteTransform();
            r ? a.multiplyToRef(r.getWorldMatrix(), o) : o.copyFrom(a),
            o.multiplyAtIndex(0, this._scalingDeterminant),
            o.multiplyAtIndex(1, this._scalingDeterminant),
            o.multiplyAtIndex(2, this._scalingDeterminant),
            o.getRotationMatrixToRef(n)
        }
    }
    ,
    e.prototype.getAbsolutePositionFromLocal = function(t, r) {
        r === void 0 && (r = null);
        var n = Vector3.Zero();
        return this.getAbsolutePositionFromLocalToRef(t, r, n),
        n
    }
    ,
    e.prototype.getAbsolutePositionFromLocalToRef = function(t, r, n) {
        r === void 0 && (r = null);
        var o = null;
        r && (o = r.getWorldMatrix()),
        this._skeleton.computeAbsoluteTransforms();
        var a = e._tmpMats[0];
        r && o ? (a.copyFrom(this.getAbsoluteTransform()),
        a.multiplyToRef(o, a)) : a = this.getAbsoluteTransform(),
        Vector3.TransformCoordinatesToRef(t, a, n)
    }
    ,
    e.prototype.getLocalPositionFromAbsolute = function(t, r) {
        r === void 0 && (r = null);
        var n = Vector3.Zero();
        return this.getLocalPositionFromAbsoluteToRef(t, r, n),
        n
    }
    ,
    e.prototype.getLocalPositionFromAbsoluteToRef = function(t, r, n) {
        r === void 0 && (r = null);
        var o = null;
        r && (o = r.getWorldMatrix()),
        this._skeleton.computeAbsoluteTransforms();
        var a = e._tmpMats[0];
        a.copyFrom(this.getAbsoluteTransform()),
        r && o && a.multiplyToRef(o, a),
        a.invert(),
        Vector3.TransformCoordinatesToRef(t, a, n)
    }
    ,
    e.prototype.setCurrentPoseAsRest = function() {
        this.setRestPose(this.getLocalMatrix())
    }
    ,
    e._tmpVecs = ArrayTools.BuildArray(2, Vector3.Zero),
    e._tmpQuat = Quaternion.Identity(),
    e._tmpMats = ArrayTools.BuildArray(5, Matrix.Identity),
    e
}(Node$2)
  , Animatable = function() {
    function i(e, t, r, n, o, a, s, l, u, c) {
        r === void 0 && (r = 0),
        n === void 0 && (n = 100),
        o === void 0 && (o = !1),
        a === void 0 && (a = 1),
        c === void 0 && (c = !1),
        this.target = t,
        this.fromFrame = r,
        this.toFrame = n,
        this.loopAnimation = o,
        this.onAnimationEnd = s,
        this.onAnimationLoop = u,
        this.isAdditive = c,
        this._localDelayOffset = null,
        this._pausedDelay = null,
        this._manualJumpDelay = null,
        this._runtimeAnimations = new Array,
        this._paused = !1,
        this._speedRatio = 1,
        this._weight = -1,
        this._syncRoot = null,
        this._frameToSyncFromJump = 0,
        this.disposeOnEnd = !0,
        this.animationStarted = !1,
        this.onAnimationEndObservable = new Observable,
        this.onAnimationLoopObservable = new Observable,
        this._scene = e,
        l && this.appendAnimations(t, l),
        this._speedRatio = a,
        e._activeAnimatables.push(this)
    }
    return Object.defineProperty(i.prototype, "syncRoot", {
        get: function() {
            return this._syncRoot
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "masterFrame", {
        get: function() {
            return this._runtimeAnimations.length === 0 ? 0 : this._runtimeAnimations[0].currentFrame
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "weight", {
        get: function() {
            return this._weight
        },
        set: function(e) {
            if (e === -1) {
                this._weight = -1;
                return
            }
            this._weight = Math.min(Math.max(e, 0), 1)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "speedRatio", {
        get: function() {
            return this._speedRatio
        },
        set: function(e) {
            for (var t = 0; t < this._runtimeAnimations.length; t++) {
                var r = this._runtimeAnimations[t];
                r._prepareForSpeedRatioChange(e)
            }
            this._speedRatio = e
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.syncWith = function(e) {
        if (this._syncRoot = e,
        e) {
            var t = this._scene._activeAnimatables.indexOf(this);
            t > -1 && (this._scene._activeAnimatables.splice(t, 1),
            this._scene._activeAnimatables.push(this))
        }
        return this
    }
    ,
    i.prototype.getAnimations = function() {
        return this._runtimeAnimations
    }
    ,
    i.prototype.appendAnimations = function(e, t) {
        for (var r = this, n = 0; n < t.length; n++) {
            var o = t[n]
              , a = new RuntimeAnimation(e,o,this._scene,this);
            a._onLoop = function() {
                r.onAnimationLoopObservable.notifyObservers(r),
                r.onAnimationLoop && r.onAnimationLoop()
            }
            ,
            this._runtimeAnimations.push(a)
        }
    }
    ,
    i.prototype.getAnimationByTargetProperty = function(e) {
        for (var t = this._runtimeAnimations, r = 0; r < t.length; r++)
            if (t[r].animation.targetProperty === e)
                return t[r].animation;
        return null
    }
    ,
    i.prototype.getRuntimeAnimationByTargetProperty = function(e) {
        for (var t = this._runtimeAnimations, r = 0; r < t.length; r++)
            if (t[r].animation.targetProperty === e)
                return t[r];
        return null
    }
    ,
    i.prototype.reset = function() {
        for (var e = this._runtimeAnimations, t = 0; t < e.length; t++)
            e[t].reset(!0);
        this._localDelayOffset = null,
        this._pausedDelay = null
    }
    ,
    i.prototype.enableBlending = function(e) {
        for (var t = this._runtimeAnimations, r = 0; r < t.length; r++)
            t[r].animation.enableBlending = !0,
            t[r].animation.blendingSpeed = e
    }
    ,
    i.prototype.disableBlending = function() {
        for (var e = this._runtimeAnimations, t = 0; t < e.length; t++)
            e[t].animation.enableBlending = !1
    }
    ,
    i.prototype.goToFrame = function(e) {
        var t, r = this._runtimeAnimations;
        if (r[0]) {
            var n = r[0].animation.framePerSecond;
            this._frameToSyncFromJump = (t = this._frameToSyncFromJump) !== null && t !== void 0 ? t : r[0].currentFrame;
            var o = this.speedRatio === 0 ? 0 : (e - this._frameToSyncFromJump) / n * 1e3 / this.speedRatio;
            this._manualJumpDelay = -o
        }
        for (var a = 0; a < r.length; a++)
            r[a].goToFrame(e)
    }
    ,
    i.prototype.pause = function() {
        this._paused || (this._paused = !0)
    }
    ,
    i.prototype.restart = function() {
        this._paused = !1
    }
    ,
    i.prototype._raiseOnAnimationEnd = function() {
        this.onAnimationEnd && this.onAnimationEnd(),
        this.onAnimationEndObservable.notifyObservers(this)
    }
    ,
    i.prototype.stop = function(e, t) {
        if (e || t) {
            var r = this._scene._activeAnimatables.indexOf(this);
            if (r > -1) {
                for (var n = this._runtimeAnimations, o = n.length - 1; o >= 0; o--) {
                    var a = n[o];
                    e && a.animation.name != e || t && !t(a.target) || (a.dispose(),
                    n.splice(o, 1))
                }
                n.length == 0 && (this._scene._activeAnimatables.splice(r, 1),
                this._raiseOnAnimationEnd())
            }
        } else {
            var o = this._scene._activeAnimatables.indexOf(this);
            if (o > -1) {
                this._scene._activeAnimatables.splice(o, 1);
                for (var n = this._runtimeAnimations, o = 0; o < n.length; o++)
                    n[o].dispose();
                this._raiseOnAnimationEnd()
            }
        }
    }
    ,
    i.prototype.waitAsync = function() {
        var e = this;
        return new Promise(function(t, r) {
            e.onAnimationEndObservable.add(function() {
                t(e)
            }, void 0, void 0, e, !0)
        }
        )
    }
    ,
    i.prototype._animate = function(e) {
        if (this._paused)
            return this.animationStarted = !1,
            this._pausedDelay === null && (this._pausedDelay = e),
            !0;
        if (this._localDelayOffset === null ? (this._localDelayOffset = e,
        this._pausedDelay = null) : this._pausedDelay !== null && (this._localDelayOffset += e - this._pausedDelay,
        this._pausedDelay = null),
        this._manualJumpDelay !== null && (this._localDelayOffset += this._manualJumpDelay,
        this._manualJumpDelay = null,
        this._frameToSyncFromJump = null),
        this._weight === 0)
            return !0;
        var t = !1, r = this._runtimeAnimations, n;
        for (n = 0; n < r.length; n++) {
            var o = r[n]
              , a = o.animate(e - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
            t = t || a
        }
        if (this.animationStarted = t,
        !t) {
            if (this.disposeOnEnd)
                for (n = this._scene._activeAnimatables.indexOf(this),
                this._scene._activeAnimatables.splice(n, 1),
                n = 0; n < r.length; n++)
                    r[n].dispose();
            this._raiseOnAnimationEnd(),
            this.disposeOnEnd && (this.onAnimationEnd = null,
            this.onAnimationLoop = null,
            this.onAnimationLoopObservable.clear(),
            this.onAnimationEndObservable.clear())
        }
        return t
    }
    ,
    i
}();
Scene.prototype._animate = function() {
    if (!!this.animationsEnabled) {
        var i = PrecisionDate.Now;
        if (!this._animationTimeLast) {
            if (this._pendingData.length > 0)
                return;
            this._animationTimeLast = i
        }
        this.deltaTime = this.useConstantAnimationDeltaTime ? 16 : (i - this._animationTimeLast) * this.animationTimeScale,
        this._animationTimeLast = i;
        var e = this._activeAnimatables;
        if (e.length !== 0) {
            this._animationTime += this.deltaTime;
            for (var t = this._animationTime, r = 0; r < e.length; r++) {
                var n = e[r];
                !n._animate(t) && n.disposeOnEnd && r--
            }
            this._processLateAnimationBindings()
        }
    }
}
;
Scene.prototype.beginWeightedAnimation = function(i, e, t, r, n, o, a, s, l, u, c) {
    r === void 0 && (r = 1),
    o === void 0 && (o = 1),
    c === void 0 && (c = !1);
    var h = this.beginAnimation(i, e, t, n, o, a, s, !1, l, u, c);
    return h.weight = r,
    h
}
;
Scene.prototype.beginAnimation = function(i, e, t, r, n, o, a, s, l, u, c) {
    n === void 0 && (n = 1),
    s === void 0 && (s = !0),
    c === void 0 && (c = !1),
    e > t && n > 0 && (n *= -1),
    s && this.stopAnimation(i, void 0, l),
    a || (a = new Animatable(this,i,e,t,r,n,o,void 0,u,c));
    var h = l ? l(i) : !0;
    if (i.animations && h && a.appendAnimations(i, i.animations),
    i.getAnimatables)
        for (var f = i.getAnimatables(), d = 0; d < f.length; d++)
            this.beginAnimation(f[d], e, t, r, n, o, a, s, l, u);
    return a.reset(),
    a
}
;
Scene.prototype.beginHierarchyAnimation = function(i, e, t, r, n, o, a, s, l, u, c, h) {
    o === void 0 && (o = 1),
    l === void 0 && (l = !0),
    h === void 0 && (h = !1);
    var f = i.getDescendants(e)
      , d = [];
    d.push(this.beginAnimation(i, t, r, n, o, a, s, l, u, void 0, h));
    for (var _ = 0, g = f; _ < g.length; _++) {
        var m = g[_];
        d.push(this.beginAnimation(m, t, r, n, o, a, s, l, u, void 0, h))
    }
    return d
}
;
Scene.prototype.beginDirectAnimation = function(i, e, t, r, n, o, a, s, l) {
    if (l === void 0 && (l = !1),
    o === void 0 && (o = 1),
    t > r && o > 0)
        o *= -1;
    else if (r > t && o < 0) {
        var u = r;
        r = t,
        t = u
    }
    var c = new Animatable(this,i,t,r,n,o,a,e,s,l);
    return c
}
;
Scene.prototype.beginDirectHierarchyAnimation = function(i, e, t, r, n, o, a, s, l, u) {
    u === void 0 && (u = !1);
    var c = i.getDescendants(e)
      , h = [];
    h.push(this.beginDirectAnimation(i, t, r, n, o, a, s, l, u));
    for (var f = 0, d = c; f < d.length; f++) {
        var _ = d[f];
        h.push(this.beginDirectAnimation(_, t, r, n, o, a, s, l, u))
    }
    return h
}
;
Scene.prototype.getAnimatableByTarget = function(i) {
    for (var e = 0; e < this._activeAnimatables.length; e++)
        if (this._activeAnimatables[e].target === i)
            return this._activeAnimatables[e];
    return null
}
;
Scene.prototype.getAllAnimatablesByTarget = function(i) {
    for (var e = [], t = 0; t < this._activeAnimatables.length; t++)
        this._activeAnimatables[t].target === i && e.push(this._activeAnimatables[t]);
    return e
}
;
Scene.prototype.stopAnimation = function(i, e, t) {
    for (var r = this.getAllAnimatablesByTarget(i), n = 0, o = r; n < o.length; n++) {
        var a = o[n];
        a.stop(e, t)
    }
}
;
Scene.prototype.stopAllAnimations = function() {
    if (this._activeAnimatables) {
        for (var i = 0; i < this._activeAnimatables.length; i++)
            this._activeAnimatables[i].stop();
        this._activeAnimatables = []
    }
    for (var e = 0, t = this.animationGroups; e < t.length; e++) {
        var r = t[e];
        r.stop()
    }
}
;
Scene.prototype._registerTargetForLateAnimationBinding = function(i, e) {
    var t = i.target;
    this._registeredForLateAnimationBindings.pushNoDuplicate(t),
    t._lateAnimationHolders || (t._lateAnimationHolders = {}),
    t._lateAnimationHolders[i.targetPath] || (t._lateAnimationHolders[i.targetPath] = {
        totalWeight: 0,
        totalAdditiveWeight: 0,
        animations: [],
        additiveAnimations: [],
        originalValue: e
    }),
    i.isAdditive ? (t._lateAnimationHolders[i.targetPath].additiveAnimations.push(i),
    t._lateAnimationHolders[i.targetPath].totalAdditiveWeight += i.weight) : (t._lateAnimationHolders[i.targetPath].animations.push(i),
    t._lateAnimationHolders[i.targetPath].totalWeight += i.weight)
}
;
Scene.prototype._processLateAnimationBindingsForMatrices = function(i) {
    if (i.totalWeight === 0 && i.totalAdditiveWeight === 0)
        return i.originalValue;
    var e = 1
      , t = TmpVectors.Vector3[0]
      , r = TmpVectors.Vector3[1]
      , n = TmpVectors.Quaternion[0]
      , o = 0
      , a = i.animations[0]
      , s = i.originalValue
      , l = 1
      , u = !1;
    if (i.totalWeight < 1)
        l = 1 - i.totalWeight,
        s.decompose(r, n, t);
    else {
        if (o = 1,
        e = i.totalWeight,
        l = a.weight / e,
        l == 1)
            if (i.totalAdditiveWeight)
                u = !0;
            else
                return a.currentValue;
        a.currentValue.decompose(r, n, t)
    }
    if (!u) {
        r.scaleInPlace(l),
        t.scaleInPlace(l),
        n.scaleInPlace(l);
        for (var c = o; c < i.animations.length; c++) {
            var h = i.animations[c];
            if (h.weight !== 0) {
                var l = h.weight / e
                  , f = TmpVectors.Vector3[2]
                  , d = TmpVectors.Vector3[3]
                  , _ = TmpVectors.Quaternion[1];
                h.currentValue.decompose(d, _, f),
                d.scaleAndAddToRef(l, r),
                _.scaleAndAddToRef(l, n),
                f.scaleAndAddToRef(l, t)
            }
        }
    }
    for (var g = 0; g < i.additiveAnimations.length; g++) {
        var h = i.additiveAnimations[g];
        if (h.weight !== 0) {
            var f = TmpVectors.Vector3[2]
              , d = TmpVectors.Vector3[3]
              , _ = TmpVectors.Quaternion[1];
            h.currentValue.decompose(d, _, f),
            d.multiplyToRef(r, d),
            Vector3.LerpToRef(r, d, h.weight, r),
            n.multiplyToRef(_, _),
            Quaternion.SlerpToRef(n, _, h.weight, n),
            f.scaleAndAddToRef(h.weight, t)
        }
    }
    var m = a ? a._animationState.workValue : TmpVectors.Matrix[0].clone();
    return Matrix.ComposeToRef(r, n, t, m),
    m
}
;
Scene.prototype._processLateAnimationBindingsForQuaternions = function(i, e) {
    if (i.totalWeight === 0 && i.totalAdditiveWeight === 0)
        return e;
    var t = i.animations[0]
      , r = i.originalValue
      , n = e;
    if (i.totalWeight === 0 && i.totalAdditiveWeight > 0)
        n.copyFrom(r);
    else if (i.animations.length === 1) {
        if (Quaternion.SlerpToRef(r, t.currentValue, Math.min(1, i.totalWeight), n),
        i.totalAdditiveWeight === 0)
            return n
    } else if (i.animations.length > 1) {
        var o = 1
          , a = void 0
          , s = void 0;
        if (i.totalWeight < 1) {
            var l = 1 - i.totalWeight;
            a = [],
            s = [],
            a.push(r),
            s.push(l)
        } else {
            if (i.animations.length === 2 && (Quaternion.SlerpToRef(i.animations[0].currentValue, i.animations[1].currentValue, i.animations[1].weight / i.totalWeight, e),
            i.totalAdditiveWeight === 0))
                return e;
            a = [],
            s = [],
            o = i.totalWeight
        }
        for (var u = 0; u < i.animations.length; u++) {
            var c = i.animations[u];
            a.push(c.currentValue),
            s.push(c.weight / o)
        }
        for (var h = 0, f = 0; f < a.length; ) {
            if (!f) {
                Quaternion.SlerpToRef(a[f], a[f + 1], s[f + 1] / (s[f] + s[f + 1]), e),
                n = e,
                h = s[f] + s[f + 1],
                f += 2;
                continue
            }
            h += s[f],
            Quaternion.SlerpToRef(n, a[f], s[f] / h, n),
            f++
        }
    }
    for (var d = 0; d < i.additiveAnimations.length; d++) {
        var c = i.additiveAnimations[d];
        c.weight !== 0 && (n.multiplyToRef(c.currentValue, TmpVectors.Quaternion[0]),
        Quaternion.SlerpToRef(n, TmpVectors.Quaternion[0], c.weight, n))
    }
    return n
}
;
Scene.prototype._processLateAnimationBindings = function() {
    if (!!this._registeredForLateAnimationBindings.length) {
        for (var i = 0; i < this._registeredForLateAnimationBindings.length; i++) {
            var e = this._registeredForLateAnimationBindings.data[i];
            for (var t in e._lateAnimationHolders) {
                var r = e._lateAnimationHolders[t]
                  , n = r.animations[0]
                  , o = r.originalValue
                  , a = Animation.AllowMatrixDecomposeForInterpolation && o.m
                  , s = e[t];
                if (a)
                    s = this._processLateAnimationBindingsForMatrices(r);
                else {
                    var l = o.w !== void 0;
                    if (l)
                        s = this._processLateAnimationBindingsForQuaternions(r, s || Quaternion.Identity());
                    else {
                        var u = 0
                          , c = 1;
                        if (r.totalWeight < 1)
                            n && o.scale ? s = o.scale(1 - r.totalWeight) : n ? s = o * (1 - r.totalWeight) : o.clone ? s = o.clone() : s = o;
                        else if (n) {
                            c = r.totalWeight;
                            var h = n.weight / c;
                            h !== 1 ? n.currentValue.scale ? s = n.currentValue.scale(h) : s = n.currentValue * h : s = n.currentValue,
                            u = 1
                        }
                        for (var f = u; f < r.animations.length; f++) {
                            var d = r.animations[f]
                              , _ = d.weight / c;
                            if (_)
                                d.currentValue.scaleAndAddToRef ? d.currentValue.scaleAndAddToRef(_, s) : s += d.currentValue * _;
                            else
                                continue
                        }
                        for (var g = 0; g < r.additiveAnimations.length; g++) {
                            var d = r.additiveAnimations[g]
                              , _ = d.weight;
                            if (_)
                                d.currentValue.scaleAndAddToRef ? d.currentValue.scaleAndAddToRef(_, s) : s += d.currentValue * _;
                            else
                                continue
                        }
                    }
                }
                e[t] = s
            }
            e._lateAnimationHolders = {}
        }
        this._registeredForLateAnimationBindings.reset()
    }
}
;
Bone.prototype.copyAnimationRange = function(i, e, t, r, n) {
    r === void 0 && (r = !1),
    n === void 0 && (n = null),
    this.animations.length === 0 && (this.animations.push(new Animation(this.name,"_matrix",i.animations[0].framePerSecond,Animation.ANIMATIONTYPE_MATRIX,0)),
    this.animations[0].setKeys([]));
    var o = i.animations[0].getRange(e);
    if (!o)
        return !1;
    for (var a = o.from, s = o.to, l = i.animations[0].getKeys(), u = i.length, c = i.getParent(), h = this.getParent(), f = r && c && u && this.length && u !== this.length, d = f && h && c ? h.length / c.length : 1, _ = r && !h && n && (n.x !== 1 || n.y !== 1 || n.z !== 1), g = this.animations[0].getKeys(), m, v, y, b = 0, T = l.length; b < T; b++)
        m = l[b],
        m.frame >= a && m.frame <= s && (r ? (y = m.value.clone(),
        f ? (v = y.getTranslation(),
        y.setTranslation(v.scaleInPlace(d))) : _ && n ? (v = y.getTranslation(),
        y.setTranslation(v.multiplyInPlace(n))) : y = m.value) : y = m.value,
        g.push({
            frame: m.frame + t,
            value: y
        }));
    return this.animations[0].createRange(e, a + t, s + t),
    !0
}
;
var TargetedAnimation = function() {
    function i() {}
    return i.prototype.getClassName = function() {
        return "TargetedAnimation"
    }
    ,
    i.prototype.serialize = function() {
        var e = {};
        return e.animation = this.animation.serialize(),
        e.targetId = this.target.id,
        e
    }
    ,
    i
}()
  , AnimationGroup = function() {
    function i(e, t) {
        t === void 0 && (t = null),
        this.name = e,
        this._targetedAnimations = new Array,
        this._animatables = new Array,
        this._from = Number.MAX_VALUE,
        this._to = -Number.MAX_VALUE,
        this._speedRatio = 1,
        this._loopAnimation = !1,
        this._isAdditive = !1,
        this._parentContainer = null,
        this.onAnimationEndObservable = new Observable,
        this.onAnimationLoopObservable = new Observable,
        this.onAnimationGroupLoopObservable = new Observable,
        this.onAnimationGroupEndObservable = new Observable,
        this.onAnimationGroupPauseObservable = new Observable,
        this.onAnimationGroupPlayObservable = new Observable,
        this.metadata = null,
        this._scene = t || EngineStore.LastCreatedScene,
        this.uniqueId = this._scene.getUniqueId(),
        this._scene.addAnimationGroup(this)
    }
    return Object.defineProperty(i.prototype, "from", {
        get: function() {
            return this._from
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "to", {
        get: function() {
            return this._to
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "isStarted", {
        get: function() {
            return this._isStarted
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "isPlaying", {
        get: function() {
            return this._isStarted && !this._isPaused
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "speedRatio", {
        get: function() {
            return this._speedRatio
        },
        set: function(e) {
            if (this._speedRatio !== e) {
                this._speedRatio = e;
                for (var t = 0; t < this._animatables.length; t++) {
                    var r = this._animatables[t];
                    r.speedRatio = this._speedRatio
                }
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "loopAnimation", {
        get: function() {
            return this._loopAnimation
        },
        set: function(e) {
            if (this._loopAnimation !== e) {
                this._loopAnimation = e;
                for (var t = 0; t < this._animatables.length; t++) {
                    var r = this._animatables[t];
                    r.loopAnimation = this._loopAnimation
                }
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "isAdditive", {
        get: function() {
            return this._isAdditive
        },
        set: function(e) {
            if (this._isAdditive !== e) {
                this._isAdditive = e;
                for (var t = 0; t < this._animatables.length; t++) {
                    var r = this._animatables[t];
                    r.isAdditive = this._isAdditive
                }
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "targetedAnimations", {
        get: function() {
            return this._targetedAnimations
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "animatables", {
        get: function() {
            return this._animatables
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "children", {
        get: function() {
            return this._targetedAnimations
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.addTargetedAnimation = function(e, t) {
        var r = new TargetedAnimation;
        r.animation = e,
        r.target = t;
        var n = e.getKeys();
        return this._from > n[0].frame && (this._from = n[0].frame),
        this._to < n[n.length - 1].frame && (this._to = n[n.length - 1].frame),
        this._targetedAnimations.push(r),
        r
    }
    ,
    i.prototype.normalize = function(e, t) {
        e === void 0 && (e = null),
        t === void 0 && (t = null),
        e == null && (e = this._from),
        t == null && (t = this._to);
        for (var r = 0; r < this._targetedAnimations.length; r++) {
            var n = this._targetedAnimations[r]
              , o = n.animation.getKeys()
              , a = o[0]
              , s = o[o.length - 1];
            if (a.frame > e) {
                var l = {
                    frame: e,
                    value: a.value,
                    inTangent: a.inTangent,
                    outTangent: a.outTangent,
                    interpolation: a.interpolation
                };
                o.splice(0, 0, l)
            }
            if (s.frame < t) {
                var l = {
                    frame: t,
                    value: s.value,
                    inTangent: s.inTangent,
                    outTangent: s.outTangent,
                    interpolation: s.interpolation
                };
                o.push(l)
            }
        }
        return this._from = e,
        this._to = t,
        this
    }
    ,
    i.prototype._processLoop = function(e, t, r) {
        var n = this;
        e.onAnimationLoop = function() {
            n.onAnimationLoopObservable.notifyObservers(t),
            !n._animationLoopFlags[r] && (n._animationLoopFlags[r] = !0,
            n._animationLoopCount++,
            n._animationLoopCount === n._targetedAnimations.length && (n.onAnimationGroupLoopObservable.notifyObservers(n),
            n._animationLoopCount = 0,
            n._animationLoopFlags = []))
        }
    }
    ,
    i.prototype.start = function(e, t, r, n, o) {
        var a = this;
        if (e === void 0 && (e = !1),
        t === void 0 && (t = 1),
        this._isStarted || this._targetedAnimations.length === 0)
            return this;
        this._loopAnimation = e,
        this._animationLoopCount = 0,
        this._animationLoopFlags = [];
        for (var s = function() {
            var c = l._targetedAnimations[u]
              , h = l._scene.beginDirectAnimation(c.target, [c.animation], r !== void 0 ? r : l._from, n !== void 0 ? n : l._to, e, t, void 0, void 0, o !== void 0 ? o : l._isAdditive);
            h.onAnimationEnd = function() {
                a.onAnimationEndObservable.notifyObservers(c),
                a._checkAnimationGroupEnded(h)
            }
            ,
            l._processLoop(h, c, u),
            l._animatables.push(h)
        }, l = this, u = 0; u < this._targetedAnimations.length; u++)
            s();
        return this._speedRatio = t,
        this._isStarted = !0,
        this._isPaused = !1,
        this.onAnimationGroupPlayObservable.notifyObservers(this),
        this
    }
    ,
    i.prototype.pause = function() {
        if (!this._isStarted)
            return this;
        this._isPaused = !0;
        for (var e = 0; e < this._animatables.length; e++) {
            var t = this._animatables[e];
            t.pause()
        }
        return this.onAnimationGroupPauseObservable.notifyObservers(this),
        this
    }
    ,
    i.prototype.play = function(e) {
        return this.isStarted && this._animatables.length === this._targetedAnimations.length ? (e !== void 0 && (this.loopAnimation = e),
        this.restart()) : (this.stop(),
        this.start(e, this._speedRatio)),
        this._isPaused = !1,
        this
    }
    ,
    i.prototype.reset = function() {
        if (!this._isStarted)
            return this.play(),
            this.goToFrame(0),
            this.stop(),
            this;
        for (var e = 0; e < this._animatables.length; e++) {
            var t = this._animatables[e];
            t.reset()
        }
        return this
    }
    ,
    i.prototype.restart = function() {
        if (!this._isStarted)
            return this;
        for (var e = 0; e < this._animatables.length; e++) {
            var t = this._animatables[e];
            t.restart()
        }
        return this.onAnimationGroupPlayObservable.notifyObservers(this),
        this
    }
    ,
    i.prototype.stop = function() {
        if (!this._isStarted)
            return this;
        for (var e = this._animatables.slice(), t = 0; t < e.length; t++)
            e[t].stop();
        return this._isStarted = !1,
        this
    }
    ,
    i.prototype.setWeightForAllAnimatables = function(e) {
        for (var t = 0; t < this._animatables.length; t++) {
            var r = this._animatables[t];
            r.weight = e
        }
        return this
    }
    ,
    i.prototype.syncAllAnimationsWith = function(e) {
        for (var t = 0; t < this._animatables.length; t++) {
            var r = this._animatables[t];
            r.syncWith(e)
        }
        return this
    }
    ,
    i.prototype.goToFrame = function(e) {
        if (!this._isStarted)
            return this;
        for (var t = 0; t < this._animatables.length; t++) {
            var r = this._animatables[t];
            r.goToFrame(e)
        }
        return this
    }
    ,
    i.prototype.dispose = function() {
        this._targetedAnimations = [],
        this._animatables = [];
        var e = this._scene.animationGroups.indexOf(this);
        if (e > -1 && this._scene.animationGroups.splice(e, 1),
        this._parentContainer) {
            var t = this._parentContainer.animationGroups.indexOf(this);
            t > -1 && this._parentContainer.animationGroups.splice(t, 1),
            this._parentContainer = null
        }
        this.onAnimationEndObservable.clear(),
        this.onAnimationGroupEndObservable.clear(),
        this.onAnimationGroupPauseObservable.clear(),
        this.onAnimationGroupPlayObservable.clear(),
        this.onAnimationLoopObservable.clear(),
        this.onAnimationGroupLoopObservable.clear()
    }
    ,
    i.prototype._checkAnimationGroupEnded = function(e) {
        var t = this._animatables.indexOf(e);
        t > -1 && this._animatables.splice(t, 1),
        this._animatables.length === 0 && (this._isStarted = !1,
        this.onAnimationGroupEndObservable.notifyObservers(this))
    }
    ,
    i.prototype.clone = function(e, t, r) {
        r === void 0 && (r = !1);
        for (var n = new i(e || this.name,this._scene), o = 0, a = this._targetedAnimations; o < a.length; o++) {
            var s = a[o];
            n.addTargetedAnimation(r ? s.animation.clone() : s.animation, t ? t(s.target) : s.target)
        }
        return n
    }
    ,
    i.prototype.serialize = function() {
        var e = {};
        e.name = this.name,
        e.from = this.from,
        e.to = this.to,
        e.targetedAnimations = [];
        for (var t = 0; t < this.targetedAnimations.length; t++) {
            var r = this.targetedAnimations[t];
            e.targetedAnimations[t] = r.serialize()
        }
        return Tags && Tags.HasTags(this) && (e.tags = Tags.GetTags(this)),
        this.metadata && (e.metadata = this.metadata),
        e
    }
    ,
    i.Parse = function(e, t) {
        for (var r = new i(e.name,t), n = 0; n < e.targetedAnimations.length; n++) {
            var o = e.targetedAnimations[n]
              , a = Animation.Parse(o.animation)
              , s = o.targetId;
            if (o.animation.property === "influence") {
                var l = t.getMorphTargetById(s);
                l && r.addTargetedAnimation(a, l)
            } else {
                var u = t.getNodeById(s);
                u != null && r.addTargetedAnimation(a, u)
            }
        }
        return e.from !== null && e.to !== null && r.normalize(e.from, e.to),
        Tags && Tags.AddTagsTo(r, e.tags),
        e.metadata !== void 0 && (r.metadata = e.metadata),
        r
    }
    ,
    i.MakeAnimationAdditive = function(e, t, r, n, o) {
        t === void 0 && (t = 0),
        n === void 0 && (n = !1);
        var a = e;
        n && (a = e.clone(o || a.name));
        for (var s = a.targetedAnimations, l = 0; l < s.length; l++) {
            var u = s[l];
            Animation.MakeAnimationAdditive(u.animation, t, r)
        }
        return a.isAdditive = !0,
        a
    }
    ,
    i.prototype.getClassName = function() {
        return "AnimationGroup"
    }
    ,
    i.prototype.toString = function(e) {
        var t = "Name: " + this.name;
        return t += ", type: " + this.getClassName(),
        e && (t += ", from: " + this._from,
        t += ", to: " + this._to,
        t += ", isStarted: " + this._isStarted,
        t += ", speedRatio: " + this._speedRatio,
        t += ", targetedAnimations length: " + this._targetedAnimations.length,
        t += ", animatables length: " + this._animatables),
        t
    }
    ,
    i
}()
  , ThinTexture = function() {
    function i(e) {
        this._wrapU = 1,
        this._wrapV = 1,
        this.wrapR = 1,
        this.anisotropicFilteringLevel = 4,
        this.delayLoadState = 0,
        this._texture = null,
        this._engine = null,
        this._cachedSize = Size.Zero(),
        this._cachedBaseSize = Size.Zero(),
        this._initialSamplingMode = 2,
        this._texture = e,
        this._texture && (this._engine = this._texture.getEngine())
    }
    return Object.defineProperty(i.prototype, "wrapU", {
        get: function() {
            return this._wrapU
        },
        set: function(e) {
            this._wrapU = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "wrapV", {
        get: function() {
            return this._wrapV
        },
        set: function(e) {
            this._wrapV = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "coordinatesMode", {
        get: function() {
            return 0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "isCube", {
        get: function() {
            return this._texture ? this._texture.isCube : !1
        },
        set: function(e) {
            !this._texture || (this._texture.isCube = e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "is3D", {
        get: function() {
            return this._texture ? this._texture.is3D : !1
        },
        set: function(e) {
            !this._texture || (this._texture.is3D = e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "is2DArray", {
        get: function() {
            return this._texture ? this._texture.is2DArray : !1
        },
        set: function(e) {
            !this._texture || (this._texture.is2DArray = e)
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.getClassName = function() {
        return "ThinTexture"
    }
    ,
    i.prototype.isReady = function() {
        return this.delayLoadState === 4 ? (this.delayLoad(),
        !1) : this._texture ? this._texture.isReady : !1
    }
    ,
    i.prototype.delayLoad = function() {}
    ,
    i.prototype.getInternalTexture = function() {
        return this._texture
    }
    ,
    i.prototype.getSize = function() {
        if (this._texture) {
            if (this._texture.width)
                return this._cachedSize.width = this._texture.width,
                this._cachedSize.height = this._texture.height,
                this._cachedSize;
            if (this._texture._size)
                return this._cachedSize.width = this._texture._size,
                this._cachedSize.height = this._texture._size,
                this._cachedSize
        }
        return this._cachedSize
    }
    ,
    i.prototype.getBaseSize = function() {
        return !this.isReady() || !this._texture ? (this._cachedBaseSize.width = 0,
        this._cachedBaseSize.height = 0,
        this._cachedBaseSize) : this._texture._size ? (this._cachedBaseSize.width = this._texture._size,
        this._cachedBaseSize.height = this._texture._size,
        this._cachedBaseSize) : (this._cachedBaseSize.width = this._texture.baseWidth,
        this._cachedBaseSize.height = this._texture.baseHeight,
        this._cachedBaseSize)
    }
    ,
    Object.defineProperty(i.prototype, "samplingMode", {
        get: function() {
            return this._texture ? this._texture.samplingMode : this._initialSamplingMode
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.updateSamplingMode = function(e) {
        this._texture && this._engine && this._engine.updateTextureSamplingMode(e, this._texture)
    }
    ,
    i.prototype.releaseInternalTexture = function() {
        this._texture && (this._texture.dispose(),
        this._texture = null)
    }
    ,
    i.prototype.dispose = function() {
        this._texture && (this.releaseInternalTexture(),
        this._engine = null)
    }
    ,
    i
}()
  , BaseTexture = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, null) || this;
        return r.metadata = null,
        r.reservedDataStore = null,
        r._hasAlpha = !1,
        r.getAlphaFromRGB = !1,
        r.level = 1,
        r.coordinatesIndex = 0,
        r._coordinatesMode = 0,
        r.wrapR = 1,
        r.anisotropicFilteringLevel = e.DEFAULT_ANISOTROPIC_FILTERING_LEVEL,
        r._isCube = !1,
        r._gammaSpace = !0,
        r.invertZ = !1,
        r.lodLevelInAlpha = !1,
        r.isRenderTarget = !1,
        r._prefiltered = !1,
        r._forceSerialize = !1,
        r.animations = new Array,
        r.onDisposeObservable = new Observable,
        r._onDisposeObserver = null,
        r._scene = null,
        r._uid = null,
        r._parentContainer = null,
        r._loadingError = !1,
        t ? e._isScene(t) ? r._scene = t : r._engine = t : r._scene = EngineStore.LastCreatedScene,
        r._scene && (r.uniqueId = r._scene.getUniqueId(),
        r._scene.addTexture(r),
        r._engine = r._scene.getEngine()),
        r._uid = null,
        r
    }
    return Object.defineProperty(e.prototype, "hasAlpha", {
        get: function() {
            return this._hasAlpha
        },
        set: function(t) {
            this._hasAlpha !== t && (this._hasAlpha = t,
            this._scene && this._scene.markAllMaterialsAsDirty(17))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "coordinatesMode", {
        get: function() {
            return this._coordinatesMode
        },
        set: function(t) {
            this._coordinatesMode !== t && (this._coordinatesMode = t,
            this._scene && this._scene.markAllMaterialsAsDirty(1))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "wrapU", {
        get: function() {
            return this._wrapU
        },
        set: function(t) {
            this._wrapU = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "wrapV", {
        get: function() {
            return this._wrapV
        },
        set: function(t) {
            this._wrapV = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "isCube", {
        get: function() {
            return this._texture ? this._texture.isCube : this._isCube
        },
        set: function(t) {
            this._texture ? this._texture.isCube = t : this._isCube = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "is3D", {
        get: function() {
            return this._texture ? this._texture.is3D : !1
        },
        set: function(t) {
            !this._texture || (this._texture.is3D = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "is2DArray", {
        get: function() {
            return this._texture ? this._texture.is2DArray : !1
        },
        set: function(t) {
            !this._texture || (this._texture.is2DArray = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "gammaSpace", {
        get: function() {
            if (this._texture)
                this._texture._gammaSpace === null && (this._texture._gammaSpace = this._gammaSpace);
            else
                return this._gammaSpace;
            return this._texture._gammaSpace && !this._texture._useSRGBBuffer
        },
        set: function(t) {
            if (this._texture) {
                if (this._texture._gammaSpace === t)
                    return;
                this._texture._gammaSpace = t
            } else {
                if (this._gammaSpace === t)
                    return;
                this._gammaSpace = t
            }
            this._markAllSubMeshesAsTexturesDirty()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "isRGBD", {
        get: function() {
            return this._texture != null && this._texture._isRGBD
        },
        set: function(t) {
            this._texture && (this._texture._isRGBD = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "noMipmap", {
        get: function() {
            return !1
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "lodGenerationOffset", {
        get: function() {
            return this._texture ? this._texture._lodGenerationOffset : 0
        },
        set: function(t) {
            this._texture && (this._texture._lodGenerationOffset = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "lodGenerationScale", {
        get: function() {
            return this._texture ? this._texture._lodGenerationScale : 0
        },
        set: function(t) {
            this._texture && (this._texture._lodGenerationScale = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "linearSpecularLOD", {
        get: function() {
            return this._texture ? this._texture._linearSpecularLOD : !1
        },
        set: function(t) {
            this._texture && (this._texture._linearSpecularLOD = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "irradianceTexture", {
        get: function() {
            return this._texture ? this._texture._irradianceTexture : null
        },
        set: function(t) {
            this._texture && (this._texture._irradianceTexture = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "uid", {
        get: function() {
            return this._uid || (this._uid = RandomGUID()),
            this._uid
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.toString = function() {
        return this.name
    }
    ,
    e.prototype.getClassName = function() {
        return "BaseTexture"
    }
    ,
    Object.defineProperty(e.prototype, "onDispose", {
        set: function(t) {
            this._onDisposeObserver && this.onDisposeObservable.remove(this._onDisposeObserver),
            this._onDisposeObserver = this.onDisposeObservable.add(t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "isBlocking", {
        get: function() {
            return !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "loadingError", {
        get: function() {
            return this._loadingError
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "errorObject", {
        get: function() {
            return this._errorObject
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getScene = function() {
        return this._scene
    }
    ,
    e.prototype._getEngine = function() {
        return this._engine
    }
    ,
    e.prototype.checkTransformsAreIdentical = function(t) {
        return t !== null
    }
    ,
    e.prototype.getTextureMatrix = function() {
        return Matrix.IdentityReadOnly
    }
    ,
    e.prototype.getReflectionTextureMatrix = function() {
        return Matrix.IdentityReadOnly
    }
    ,
    e.prototype.isReadyOrNotBlocking = function() {
        return !this.isBlocking || this.isReady() || this.loadingError
    }
    ,
    e.prototype.scale = function(t) {}
    ,
    Object.defineProperty(e.prototype, "canRescale", {
        get: function() {
            return !1
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._getFromCache = function(t, r, n, o, a) {
        var s = this._getEngine();
        if (!s)
            return null;
        for (var l = s._getUseSRGBBuffer(!!a, r), u = s.getLoadedTexturesCache(), c = 0; c < u.length; c++) {
            var h = u[c];
            if ((a === void 0 || l === h._useSRGBBuffer) && (o === void 0 || o === h.invertY) && h.url === t && h.generateMipMaps === !r && (!n || n === h.samplingMode))
                return h.incrementReferences(),
                h
        }
        return null
    }
    ,
    e.prototype._rebuild = function() {}
    ,
    e.prototype.clone = function() {
        return null
    }
    ,
    Object.defineProperty(e.prototype, "textureType", {
        get: function() {
            return this._texture && this._texture.type !== void 0 ? this._texture.type : 0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "textureFormat", {
        get: function() {
            return this._texture && this._texture.format !== void 0 ? this._texture.format : 5
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._markAllSubMeshesAsTexturesDirty = function() {
        var t = this.getScene();
        !t || t.markAllMaterialsAsDirty(1)
    }
    ,
    e.prototype.readPixels = function(t, r, n, o, a) {
        if (t === void 0 && (t = 0),
        r === void 0 && (r = 0),
        n === void 0 && (n = null),
        o === void 0 && (o = !0),
        a === void 0 && (a = !1),
        !this._texture)
            return null;
        var s = this.getSize()
          , l = s.width
          , u = s.height
          , c = this._getEngine();
        if (!c)
            return null;
        r != 0 && (l = l / Math.pow(2, r),
        u = u / Math.pow(2, r),
        l = Math.round(l),
        u = Math.round(u));
        try {
            return this._texture.isCube ? c._readTexturePixels(this._texture, l, u, t, r, n, o, a) : c._readTexturePixels(this._texture, l, u, -1, r, n, o, a)
        } catch {
            return null
        }
    }
    ,
    e.prototype._readPixelsSync = function(t, r, n, o, a) {
        if (t === void 0 && (t = 0),
        r === void 0 && (r = 0),
        n === void 0 && (n = null),
        o === void 0 && (o = !0),
        a === void 0 && (a = !1),
        !this._texture)
            return null;
        var s = this.getSize()
          , l = s.width
          , u = s.height
          , c = this._getEngine();
        if (!c)
            return null;
        r != 0 && (l = l / Math.pow(2, r),
        u = u / Math.pow(2, r),
        l = Math.round(l),
        u = Math.round(u));
        try {
            return this._texture.isCube ? c._readTexturePixelsSync(this._texture, l, u, t, r, n, o, a) : c._readTexturePixelsSync(this._texture, l, u, -1, r, n, o, a)
        } catch {
            return null
        }
    }
    ,
    Object.defineProperty(e.prototype, "_lodTextureHigh", {
        get: function() {
            return this._texture ? this._texture._lodTextureHigh : null
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "_lodTextureMid", {
        get: function() {
            return this._texture ? this._texture._lodTextureMid : null
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "_lodTextureLow", {
        get: function() {
            return this._texture ? this._texture._lodTextureLow : null
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.dispose = function() {
        if (this._scene) {
            this._scene.stopAnimation && this._scene.stopAnimation(this),
            this._scene._removePendingData(this);
            var t = this._scene.textures.indexOf(this);
            if (t >= 0 && this._scene.textures.splice(t, 1),
            this._scene.onTextureRemovedObservable.notifyObservers(this),
            this._scene = null,
            this._parentContainer) {
                var r = this._parentContainer.textures.indexOf(this);
                r > -1 && this._parentContainer.textures.splice(r, 1),
                this._parentContainer = null
            }
        }
        this.onDisposeObservable.notifyObservers(this),
        this.onDisposeObservable.clear(),
        this.metadata = null,
        i.prototype.dispose.call(this)
    }
    ,
    e.prototype.serialize = function() {
        if (!this.name)
            return null;
        var t = SerializationHelper.Serialize(this);
        return SerializationHelper.AppendSerializedAnimations(this, t),
        t
    }
    ,
    e.WhenAllReady = function(t, r) {
        var n = t.length;
        if (n === 0) {
            r();
            return
        }
        for (var o = 0; o < t.length; o++) {
            var a = t[o];
            if (a.isReady())
                --n === 0 && r();
            else {
                var s = a.onLoadObservable;
                s && s.addOnce(function() {
                    --n === 0 && r()
                })
            }
        }
    }
    ,
    e._isScene = function(t) {
        return t.getClassName() === "Scene"
    }
    ,
    e.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4,
    __decorate([serialize()], e.prototype, "uniqueId", void 0),
    __decorate([serialize()], e.prototype, "name", void 0),
    __decorate([serialize()], e.prototype, "metadata", void 0),
    __decorate([serialize("hasAlpha")], e.prototype, "_hasAlpha", void 0),
    __decorate([serialize()], e.prototype, "getAlphaFromRGB", void 0),
    __decorate([serialize()], e.prototype, "level", void 0),
    __decorate([serialize()], e.prototype, "coordinatesIndex", void 0),
    __decorate([serialize("coordinatesMode")], e.prototype, "_coordinatesMode", void 0),
    __decorate([serialize()], e.prototype, "wrapU", null),
    __decorate([serialize()], e.prototype, "wrapV", null),
    __decorate([serialize()], e.prototype, "wrapR", void 0),
    __decorate([serialize()], e.prototype, "anisotropicFilteringLevel", void 0),
    __decorate([serialize()], e.prototype, "isCube", null),
    __decorate([serialize()], e.prototype, "is3D", null),
    __decorate([serialize()], e.prototype, "is2DArray", null),
    __decorate([serialize()], e.prototype, "gammaSpace", null),
    __decorate([serialize()], e.prototype, "invertZ", void 0),
    __decorate([serialize()], e.prototype, "lodLevelInAlpha", void 0),
    __decorate([serialize()], e.prototype, "lodGenerationOffset", null),
    __decorate([serialize()], e.prototype, "lodGenerationScale", null),
    __decorate([serialize()], e.prototype, "linearSpecularLOD", null),
    __decorate([serializeAsTexture()], e.prototype, "irradianceTexture", null),
    __decorate([serialize()], e.prototype, "isRenderTarget", void 0),
    e
}(ThinTexture);
function GenerateBase64StringFromPixelData(i, e, t) {
    t === void 0 && (t = !1);
    var r = e.width
      , n = e.height;
    if (i instanceof Float32Array) {
        for (var o = i.byteLength / i.BYTES_PER_ELEMENT, a = new Uint8Array(o); --o >= 0; ) {
            var s = i[o];
            s < 0 ? s = 0 : s > 1 && (s = 1),
            a[o] = s * 255
        }
        i = a
    }
    var l = document.createElement("canvas");
    l.width = r,
    l.height = n;
    var u = l.getContext("2d");
    if (!u)
        return null;
    var c = u.createImageData(r, n)
      , h = c.data;
    if (h.set(i),
    u.putImageData(c, 0, 0),
    t) {
        var f = document.createElement("canvas");
        f.width = r,
        f.height = n;
        var d = f.getContext("2d");
        return d ? (d.translate(0, n),
        d.scale(1, -1),
        d.drawImage(l, 0, 0),
        f.toDataURL("image/png")) : null
    }
    return l.toDataURL("image/png")
}
function GenerateBase64StringFromTexture(i, e, t) {
    e === void 0 && (e = 0),
    t === void 0 && (t = 0);
    var r = i.getInternalTexture();
    if (!r)
        return null;
    var n = i._readPixelsSync(e, t);
    return n ? GenerateBase64StringFromPixelData(n, i.getSize(), r.invertY) : null
}
function GenerateBase64StringFromTextureAsync(i, e, t) {
    return e === void 0 && (e = 0),
    t === void 0 && (t = 0),
    __awaiter(this, void 0, void 0, function() {
        var r, n;
        return __generator(this, function(o) {
            switch (o.label) {
            case 0:
                return r = i.getInternalTexture(),
                r ? [4, i.readPixels(e, t)] : [2, null];
            case 1:
                return n = o.sent(),
                n ? [2, GenerateBase64StringFromPixelData(n, i.getSize(), r.invertY)] : [2, null]
            }
        })
    })
}
var Texture = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a, s, l, u, c, h, f, d, _) {
        o === void 0 && (o = !0),
        a === void 0 && (a = e.TRILINEAR_SAMPLINGMODE),
        s === void 0 && (s = null),
        l === void 0 && (l = null),
        u === void 0 && (u = null),
        c === void 0 && (c = !1);
        var g, m, v, y, b, T, C, A, S = i.call(this, r) || this;
        S.url = null,
        S.uOffset = 0,
        S.vOffset = 0,
        S.uScale = 1,
        S.vScale = 1,
        S.uAng = 0,
        S.vAng = 0,
        S.wAng = 0,
        S.uRotationCenter = .5,
        S.vRotationCenter = .5,
        S.wRotationCenter = .5,
        S.homogeneousRotationInUVTransform = !1,
        S.inspectableCustomProperties = null,
        S._noMipmap = !1,
        S._invertY = !1,
        S._rowGenerationMatrix = null,
        S._cachedTextureMatrix = null,
        S._projectionModeMatrix = null,
        S._t0 = null,
        S._t1 = null,
        S._t2 = null,
        S._cachedUOffset = -1,
        S._cachedVOffset = -1,
        S._cachedUScale = 0,
        S._cachedVScale = 0,
        S._cachedUAng = -1,
        S._cachedVAng = -1,
        S._cachedWAng = -1,
        S._cachedProjectionMatrixId = -1,
        S._cachedURotationCenter = -1,
        S._cachedVRotationCenter = -1,
        S._cachedWRotationCenter = -1,
        S._cachedHomogeneousRotationInUVTransform = !1,
        S._cachedCoordinatesMode = -1,
        S._buffer = null,
        S._deleteBuffer = !1,
        S._format = null,
        S._delayedOnLoad = null,
        S._delayedOnError = null,
        S.onLoadObservable = new Observable,
        S._isBlocking = !0,
        S.name = t || "",
        S.url = t;
        var P, R = !1;
        typeof n == "object" && n !== null ? (P = (g = n.noMipmap) !== null && g !== void 0 ? g : !1,
        o = (m = n.invertY) !== null && m !== void 0 ? m : !0,
        a = (v = n.samplingMode) !== null && v !== void 0 ? v : e.TRILINEAR_SAMPLINGMODE,
        s = (y = n.onLoad) !== null && y !== void 0 ? y : null,
        l = (b = n.onError) !== null && b !== void 0 ? b : null,
        u = (T = n.buffer) !== null && T !== void 0 ? T : null,
        c = (C = n.deleteBuffer) !== null && C !== void 0 ? C : !1,
        h = n.format,
        f = n.mimeType,
        d = n.loaderOptions,
        _ = n.creationFlags,
        R = (A = n.useSRGBBuffer) !== null && A !== void 0 ? A : !1) : P = !!n,
        S._noMipmap = P,
        S._invertY = o,
        S._initialSamplingMode = a,
        S._buffer = u,
        S._deleteBuffer = c,
        S._mimeType = f,
        S._loaderOptions = d,
        S._creationFlags = _,
        S._useSRGBBuffer = R,
        h && (S._format = h);
        var M = S.getScene()
          , x = S._getEngine();
        if (!x)
            return S;
        x.onBeforeTextureInitObservable.notifyObservers(S);
        var I = function() {
            S._texture && (S._texture._invertVScale && (S.vScale *= -1,
            S.vOffset += 1),
            S._texture._cachedWrapU !== null && (S.wrapU = S._texture._cachedWrapU,
            S._texture._cachedWrapU = null),
            S._texture._cachedWrapV !== null && (S.wrapV = S._texture._cachedWrapV,
            S._texture._cachedWrapV = null),
            S._texture._cachedWrapR !== null && (S.wrapR = S._texture._cachedWrapR,
            S._texture._cachedWrapR = null)),
            S.onLoadObservable.hasObservers() && S.onLoadObservable.notifyObservers(S),
            s && s(),
            !S.isBlocking && M && M.resetCachedMaterial()
        }
          , w = function(D, F) {
            S._loadingError = !0,
            S._errorObject = {
                message: D,
                exception: F
            },
            l && l(D, F),
            e.OnTextureLoadErrorObservable.notifyObservers(S)
        };
        if (!S.url)
            return S._delayedOnLoad = I,
            S._delayedOnError = w,
            S;
        if (S._texture = S._getFromCache(S.url, P, a, o, R),
        S._texture)
            if (S._texture.isReady)
                TimingTools.SetImmediate(function() {
                    return I()
                });
            else {
                var O = S._texture.onLoadedObservable.add(I);
                S._texture.onErrorObservable.add(function(D) {
                    var F;
                    w(D.message, D.exception),
                    (F = S._texture) === null || F === void 0 || F.onLoadedObservable.remove(O)
                })
            }
        else if (!M || !M.useDelayedTextureLoading) {
            try {
                S._texture = x.createTexture(S.url, P, o, M, a, I, w, S._buffer, void 0, S._format, null, f, d, _, R)
            } catch (D) {
                throw w("error loading", D),
                D
            }
            c && (S._buffer = null)
        } else
            S.delayLoadState = 4,
            S._delayedOnLoad = I,
            S._delayedOnError = w;
        return S
    }
    return Object.defineProperty(e.prototype, "noMipmap", {
        get: function() {
            return this._noMipmap
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "mimeType", {
        get: function() {
            return this._mimeType
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "isBlocking", {
        get: function() {
            return this._isBlocking
        },
        set: function(t) {
            this._isBlocking = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "invertY", {
        get: function() {
            return this._invertY
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.updateURL = function(t, r, n) {
        r === void 0 && (r = null),
        this.url && (this.releaseInternalTexture(),
        this.getScene().markAllMaterialsAsDirty(1)),
        (!this.name || StartsWith(this.name, "data:")) && (this.name = t),
        this.url = t,
        this._buffer = r,
        this.delayLoadState = 4,
        n && (this._delayedOnLoad = n),
        this.delayLoad()
    }
    ,
    e.prototype.delayLoad = function() {
        if (this.delayLoadState === 4) {
            var t = this.getScene();
            !t || (this.delayLoadState = 1,
            this._texture = this._getFromCache(this.url, this._noMipmap, this.samplingMode, this._invertY, this._useSRGBBuffer),
            this._texture ? this._delayedOnLoad && (this._texture.isReady ? TimingTools.SetImmediate(this._delayedOnLoad) : this._texture.onLoadedObservable.add(this._delayedOnLoad)) : (this._texture = t.getEngine().createTexture(this.url, this._noMipmap, this._invertY, t, this.samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format, null, this._mimeType, this._loaderOptions, this._creationFlags, this._useSRGBBuffer),
            this._deleteBuffer && (this._buffer = null)),
            this._delayedOnLoad = null,
            this._delayedOnError = null)
        }
    }
    ,
    e.prototype._prepareRowForTextureGeneration = function(t, r, n, o) {
        t *= this._cachedUScale,
        r *= this._cachedVScale,
        t -= this.uRotationCenter * this._cachedUScale,
        r -= this.vRotationCenter * this._cachedVScale,
        n -= this.wRotationCenter,
        Vector3.TransformCoordinatesFromFloatsToRef(t, r, n, this._rowGenerationMatrix, o),
        o.x += this.uRotationCenter * this._cachedUScale + this._cachedUOffset,
        o.y += this.vRotationCenter * this._cachedVScale + this._cachedVOffset,
        o.z += this.wRotationCenter
    }
    ,
    e.prototype.checkTransformsAreIdentical = function(t) {
        return t !== null && this.uOffset === t.uOffset && this.vOffset === t.vOffset && this.uScale === t.uScale && this.vScale === t.vScale && this.uAng === t.uAng && this.vAng === t.vAng && this.wAng === t.wAng
    }
    ,
    e.prototype.getTextureMatrix = function(t) {
        var r = this;
        if (t === void 0 && (t = 1),
        this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale * t === this._cachedUScale && this.vScale === this._cachedVScale && this.uAng === this._cachedUAng && this.vAng === this._cachedVAng && this.wAng === this._cachedWAng && this.uRotationCenter === this._cachedURotationCenter && this.vRotationCenter === this._cachedVRotationCenter && this.wRotationCenter === this._cachedWRotationCenter && this.homogeneousRotationInUVTransform === this._cachedHomogeneousRotationInUVTransform)
            return this._cachedTextureMatrix;
        this._cachedUOffset = this.uOffset,
        this._cachedVOffset = this.vOffset,
        this._cachedUScale = this.uScale * t,
        this._cachedVScale = this.vScale,
        this._cachedUAng = this.uAng,
        this._cachedVAng = this.vAng,
        this._cachedWAng = this.wAng,
        this._cachedURotationCenter = this.uRotationCenter,
        this._cachedVRotationCenter = this.vRotationCenter,
        this._cachedWRotationCenter = this.wRotationCenter,
        this._cachedHomogeneousRotationInUVTransform = this.homogeneousRotationInUVTransform,
        (!this._cachedTextureMatrix || !this._rowGenerationMatrix) && (this._cachedTextureMatrix = Matrix.Zero(),
        this._rowGenerationMatrix = new Matrix,
        this._t0 = Vector3.Zero(),
        this._t1 = Vector3.Zero(),
        this._t2 = Vector3.Zero()),
        Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix),
        this.homogeneousRotationInUVTransform ? (Matrix.TranslationToRef(-this._cachedURotationCenter, -this._cachedVRotationCenter, -this._cachedWRotationCenter, TmpVectors.Matrix[0]),
        Matrix.TranslationToRef(this._cachedURotationCenter, this._cachedVRotationCenter, this._cachedWRotationCenter, TmpVectors.Matrix[1]),
        Matrix.ScalingToRef(this._cachedUScale, this._cachedVScale, 0, TmpVectors.Matrix[2]),
        Matrix.TranslationToRef(this._cachedUOffset, this._cachedVOffset, 0, TmpVectors.Matrix[3]),
        TmpVectors.Matrix[0].multiplyToRef(this._rowGenerationMatrix, this._cachedTextureMatrix),
        this._cachedTextureMatrix.multiplyToRef(TmpVectors.Matrix[1], this._cachedTextureMatrix),
        this._cachedTextureMatrix.multiplyToRef(TmpVectors.Matrix[2], this._cachedTextureMatrix),
        this._cachedTextureMatrix.multiplyToRef(TmpVectors.Matrix[3], this._cachedTextureMatrix),
        this._cachedTextureMatrix.setRowFromFloats(2, this._cachedTextureMatrix.m[12], this._cachedTextureMatrix.m[13], this._cachedTextureMatrix.m[14], 1)) : (this._prepareRowForTextureGeneration(0, 0, 0, this._t0),
        this._prepareRowForTextureGeneration(1, 0, 0, this._t1),
        this._prepareRowForTextureGeneration(0, 1, 0, this._t2),
        this._t1.subtractInPlace(this._t0),
        this._t2.subtractInPlace(this._t0),
        Matrix.FromValuesToRef(this._t1.x, this._t1.y, this._t1.z, 0, this._t2.x, this._t2.y, this._t2.z, 0, this._t0.x, this._t0.y, this._t0.z, 0, 0, 0, 0, 1, this._cachedTextureMatrix));
        var n = this.getScene();
        return n ? (n.markAllMaterialsAsDirty(1, function(o) {
            return o.hasTexture(r)
        }),
        this._cachedTextureMatrix) : this._cachedTextureMatrix
    }
    ,
    e.prototype.getReflectionTextureMatrix = function() {
        var t = this
          , r = this.getScene();
        if (!r)
            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 === e.PROJECTION_MODE) {
                if (this._cachedProjectionMatrixId === r.getProjectionMatrix().updateFlag)
                    return this._cachedTextureMatrix
            } else
                return this._cachedTextureMatrix;
        this._cachedTextureMatrix || (this._cachedTextureMatrix = Matrix.Zero()),
        this._projectionModeMatrix || (this._projectionModeMatrix = Matrix.Zero());
        var n = this._cachedCoordinatesMode !== this.coordinatesMode;
        switch (this._cachedUOffset = this.uOffset,
        this._cachedVOffset = this.vOffset,
        this._cachedUScale = this.uScale,
        this._cachedVScale = this.vScale,
        this._cachedCoordinatesMode = this.coordinatesMode,
        this.coordinatesMode) {
        case e.PLANAR_MODE:
            Matrix.IdentityToRef(this._cachedTextureMatrix),
            this._cachedTextureMatrix[0] = this.uScale,
            this._cachedTextureMatrix[5] = this.vScale,
            this._cachedTextureMatrix[12] = this.uOffset,
            this._cachedTextureMatrix[13] = this.vOffset;
            break;
        case e.PROJECTION_MODE:
            Matrix.FromValuesToRef(.5, 0, 0, 0, 0, -.5, 0, 0, 0, 0, 0, 0, .5, .5, 1, 1, this._projectionModeMatrix);
            var o = r.getProjectionMatrix();
            this._cachedProjectionMatrixId = o.updateFlag,
            o.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
            break;
        default:
            Matrix.IdentityToRef(this._cachedTextureMatrix);
            break
        }
        return n && r.markAllMaterialsAsDirty(1, function(a) {
            return a.getActiveTextures().indexOf(t) !== -1
        }),
        this._cachedTextureMatrix
    }
    ,
    e.prototype.clone = function() {
        var t = this
          , r = {
            noMipmap: this._noMipmap,
            invertY: this._invertY,
            samplingMode: this.samplingMode,
            onLoad: void 0,
            onError: void 0,
            buffer: this._texture ? this._texture._buffer : void 0,
            deleteBuffer: this._deleteBuffer,
            format: this.textureFormat,
            mimeType: this.mimeType,
            loaderOptions: this._loaderOptions,
            creationFlags: this._creationFlags,
            useSRGBBuffer: this._useSRGBBuffer
        };
        return SerializationHelper.Clone(function() {
            return new e(t._texture ? t._texture.url : null,t.getScene(),r)
        }, this)
    }
    ,
    e.prototype.serialize = function() {
        var t = this.name;
        e.SerializeBuffers || StartsWith(this.name, "data:") && (this.name = ""),
        StartsWith(this.name, "data:") && this.url === this.name && (this.url = "");
        var r = i.prototype.serialize.call(this);
        return r ? ((e.SerializeBuffers || e.ForceSerializeBuffers) && (typeof this._buffer == "string" && this._buffer.substr(0, 5) === "data:" ? (r.base64String = this._buffer,
        r.name = r.name.replace("data:", "")) : this.url && StartsWith(this.url, "data:") && this._buffer instanceof Uint8Array ? r.base64String = "data:image/png;base64," + EncodeArrayBufferToBase64(this._buffer) : (e.ForceSerializeBuffers || this.url && StartsWith(this.url, "blob:") || this._forceSerialize) && (r.base64String = !this._engine || this._engine._features.supportSyncTextureRead ? GenerateBase64StringFromTexture(this) : GenerateBase64StringFromTextureAsync(this))),
        r.invertY = this._invertY,
        r.samplingMode = this.samplingMode,
        r._creationFlags = this._creationFlags,
        r._useSRGBBuffer = this._useSRGBBuffer,
        this.name = t,
        r) : null
    }
    ,
    e.prototype.getClassName = function() {
        return "Texture"
    }
    ,
    e.prototype.dispose = function() {
        i.prototype.dispose.call(this),
        this.onLoadObservable.clear(),
        this._delayedOnLoad = null,
        this._delayedOnError = null
    }
    ,
    e.Parse = function(t, r, n) {
        if (t.customType) {
            var o = InstantiationTools.Instantiate(t.customType)
              , a = o.Parse(t, r, n);
            return t.samplingMode && a.updateSamplingMode && a._samplingMode && a._samplingMode !== t.samplingMode && a.updateSamplingMode(t.samplingMode),
            a
        }
        if (t.isCube && !t.isRenderTarget)
            return e._CubeTextureParser(t, r, n);
        if (!t.name && !t.isRenderTarget)
            return null;
        var s = function() {
            if (l && l._texture && (l._texture._cachedWrapU = null,
            l._texture._cachedWrapV = null,
            l._texture._cachedWrapR = null),
            t.samplingMode) {
                var u = t.samplingMode;
                l && l.samplingMode !== u && l.updateSamplingMode(u)
            }
            if (l && t.animations)
                for (var c = 0; c < t.animations.length; c++) {
                    var h = t.animations[c]
                      , f = GetClass("BABYLON.Animation");
                    f && l.animations.push(f.Parse(h))
                }
        }
          , l = SerializationHelper.Parse(function() {
            var u, c, h, f = !0;
            if (t.noMipmap && (f = !1),
            t.mirrorPlane) {
                var d = e._CreateMirror(t.name, t.renderTargetSize, r, f);
                return d._waitingRenderList = t.renderList,
                d.mirrorPlane = Plane.FromArray(t.mirrorPlane),
                s(),
                d
            } else if (t.isRenderTarget) {
                var _ = null;
                if (t.isCube) {
                    if (r.reflectionProbes)
                        for (var g = 0; g < r.reflectionProbes.length; g++) {
                            var m = r.reflectionProbes[g];
                            if (m.name === t.name)
                                return m.cubeTexture
                        }
                } else
                    _ = e._CreateRenderTargetTexture(t.name, t.renderTargetSize, r, f, (u = t._creationFlags) !== null && u !== void 0 ? u : 0),
                    _._waitingRenderList = t.renderList;
                return s(),
                _
            } else {
                var v;
                if (t.base64String)
                    v = e.CreateFromBase64String(t.base64String, t.name, r, !f, t.invertY, t.samplingMode, s, (c = t._creationFlags) !== null && c !== void 0 ? c : 0, (h = t._useSRGBBuffer) !== null && h !== void 0 ? h : !1);
                else {
                    var y = void 0;
                    t.name && t.name.indexOf("://") > 0 ? y = t.name : y = n + t.name,
                    (StartsWith(t.url, "data:") || e.UseSerializedUrlIfAny && t.url) && (y = t.url),
                    v = new e(y,r,!f,t.invertY,t.samplingMode,s)
                }
                return v
            }
        }, t, r);
        return l
    }
    ,
    e.CreateFromBase64String = function(t, r, n, o, a, s, l, u, c, h) {
        return s === void 0 && (s = e.TRILINEAR_SAMPLINGMODE),
        l === void 0 && (l = null),
        u === void 0 && (u = null),
        c === void 0 && (c = 5),
        new e("data:" + r,n,o,a,s,l,u,t,!1,c,void 0,void 0,h)
    }
    ,
    e.LoadFromDataString = function(t, r, n, o, a, s, l, u, c, h, f) {
        return o === void 0 && (o = !1),
        s === void 0 && (s = !0),
        l === void 0 && (l = e.TRILINEAR_SAMPLINGMODE),
        u === void 0 && (u = null),
        c === void 0 && (c = null),
        h === void 0 && (h = 5),
        t.substr(0, 5) !== "data:" && (t = "data:" + t),
        new e(t,n,a,s,l,u,c,r,o,h,void 0,void 0,f)
    }
    ,
    e.SerializeBuffers = !0,
    e.ForceSerializeBuffers = !1,
    e.OnTextureLoadErrorObservable = new Observable,
    e._CubeTextureParser = function(t, r, n) {
        throw _WarnImport("CubeTexture")
    }
    ,
    e._CreateMirror = function(t, r, n, o) {
        throw _WarnImport("MirrorTexture")
    }
    ,
    e._CreateRenderTargetTexture = function(t, r, n, o, a) {
        throw _WarnImport("RenderTargetTexture")
    }
    ,
    e.NEAREST_SAMPLINGMODE = 1,
    e.NEAREST_NEAREST_MIPLINEAR = 8,
    e.BILINEAR_SAMPLINGMODE = 2,
    e.LINEAR_LINEAR_MIPNEAREST = 11,
    e.TRILINEAR_SAMPLINGMODE = 3,
    e.LINEAR_LINEAR_MIPLINEAR = 3,
    e.NEAREST_NEAREST_MIPNEAREST = 4,
    e.NEAREST_LINEAR_MIPNEAREST = 5,
    e.NEAREST_LINEAR_MIPLINEAR = 6,
    e.NEAREST_LINEAR = 7,
    e.NEAREST_NEAREST = 1,
    e.LINEAR_NEAREST_MIPNEAREST = 9,
    e.LINEAR_NEAREST_MIPLINEAR = 10,
    e.LINEAR_LINEAR = 2,
    e.LINEAR_NEAREST = 12,
    e.EXPLICIT_MODE = 0,
    e.SPHERICAL_MODE = 1,
    e.PLANAR_MODE = 2,
    e.CUBIC_MODE = 3,
    e.PROJECTION_MODE = 4,
    e.SKYBOX_MODE = 5,
    e.INVCUBIC_MODE = 6,
    e.EQUIRECTANGULAR_MODE = 7,
    e.FIXED_EQUIRECTANGULAR_MODE = 8,
    e.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9,
    e.CLAMP_ADDRESSMODE = 0,
    e.WRAP_ADDRESSMODE = 1,
    e.MIRROR_ADDRESSMODE = 2,
    e.UseSerializedUrlIfAny = !1,
    __decorate([serialize()], e.prototype, "url", void 0),
    __decorate([serialize()], e.prototype, "uOffset", void 0),
    __decorate([serialize()], e.prototype, "vOffset", void 0),
    __decorate([serialize()], e.prototype, "uScale", void 0),
    __decorate([serialize()], e.prototype, "vScale", void 0),
    __decorate([serialize()], e.prototype, "uAng", void 0),
    __decorate([serialize()], e.prototype, "vAng", void 0),
    __decorate([serialize()], e.prototype, "wAng", void 0),
    __decorate([serialize()], e.prototype, "uRotationCenter", void 0),
    __decorate([serialize()], e.prototype, "vRotationCenter", void 0),
    __decorate([serialize()], e.prototype, "wRotationCenter", void 0),
    __decorate([serialize()], e.prototype, "homogeneousRotationInUVTransform", void 0),
    __decorate([serialize()], e.prototype, "isBlocking", null),
    e
}(BaseTexture);
RegisterClass("BABYLON.Texture", Texture);
SerializationHelper._TextureParser = Texture.Parse;
ThinEngine.prototype.updateRawTexture = function(i, e, t, r, n, o) {
    if (n === void 0 && (n = null),
    o === void 0 && (o = 0),
    !!i) {
        var a = this._getRGBABufferInternalSizedFormat(o, t)
          , s = this._getInternalFormat(t)
          , l = this._getWebGLTextureType(o);
        this._bindTextureDirectly(this._gl.TEXTURE_2D, i, !0),
        this._unpackFlipY(r === void 0 ? !0 : !!r),
        this._doNotHandleContextLost || (i._bufferView = e,
        i.format = t,
        i.type = o,
        i.invertY = r,
        i._compression = n),
        i.width % 4 !== 0 && this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1),
        n && e ? this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[n], i.width, i.height, 0, e) : this._gl.texImage2D(this._gl.TEXTURE_2D, 0, a, i.width, i.height, 0, s, l, e),
        i.generateMipMaps && this._gl.generateMipmap(this._gl.TEXTURE_2D),
        this._bindTextureDirectly(this._gl.TEXTURE_2D, null),
        i.isReady = !0
    }
}
;
ThinEngine.prototype.createRawTexture = function(i, e, t, r, n, o, a, s, l, u) {
    s === void 0 && (s = null),
    l === void 0 && (l = 0);
    var c = new InternalTexture(this,InternalTextureSource.Raw);
    c.baseWidth = e,
    c.baseHeight = t,
    c.width = e,
    c.height = t,
    c.format = r,
    c.generateMipMaps = n,
    c.samplingMode = a,
    c.invertY = o,
    c._compression = s,
    c.type = l,
    this._doNotHandleContextLost || (c._bufferView = i),
    this.updateRawTexture(c, i, r, o, s, l),
    this._bindTextureDirectly(this._gl.TEXTURE_2D, c, !0);
    var h = this._getSamplingParameters(a, n);
    return this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, h.mag),
    this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, h.min),
    n && this._gl.generateMipmap(this._gl.TEXTURE_2D),
    this._bindTextureDirectly(this._gl.TEXTURE_2D, null),
    this._internalTexturesCache.push(c),
    c
}
;
ThinEngine.prototype.createRawCubeTexture = function(i, e, t, r, n, o, a, s) {
    s === void 0 && (s = null);
    var l = this._gl
      , u = new InternalTexture(this,InternalTextureSource.CubeRaw);
    u.isCube = !0,
    u.format = t,
    u.type = r,
    this._doNotHandleContextLost || (u._bufferViewArray = i);
    var c = this._getWebGLTextureType(r)
      , h = this._getInternalFormat(t);
    h === l.RGB && (h = l.RGBA),
    c === l.FLOAT && !this._caps.textureFloatLinearFiltering ? (n = !1,
    a = 1,
    Logger$2.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")) : c === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering ? (n = !1,
    a = 1,
    Logger$2.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")) : c === l.FLOAT && !this._caps.textureFloatRender ? (n = !1,
    Logger$2.Warn("Render to float textures is not supported. Mipmap generation forced to false.")) : c === l.HALF_FLOAT && !this._caps.colorBufferFloat && (n = !1,
    Logger$2.Warn("Render to half float textures is not supported. Mipmap generation forced to false."));
    var f = e
      , d = f;
    u.width = f,
    u.height = d;
    var _ = !this.needPOTTextures || Tools.IsExponentOfTwo(u.width) && Tools.IsExponentOfTwo(u.height);
    _ || (n = !1),
    i && this.updateRawCubeTexture(u, i, t, r, o, s),
    this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, u, !0),
    i && n && this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
    var g = this._getSamplingParameters(a, n);
    return l.texParameteri(l.TEXTURE_CUBE_MAP, l.TEXTURE_MAG_FILTER, g.mag),
    l.texParameteri(l.TEXTURE_CUBE_MAP, l.TEXTURE_MIN_FILTER, g.min),
    l.texParameteri(l.TEXTURE_CUBE_MAP, l.TEXTURE_WRAP_S, l.CLAMP_TO_EDGE),
    l.texParameteri(l.TEXTURE_CUBE_MAP, l.TEXTURE_WRAP_T, l.CLAMP_TO_EDGE),
    this._bindTextureDirectly(l.TEXTURE_CUBE_MAP, null),
    u.generateMipMaps = n,
    u.samplingMode = a,
    u
}
;
ThinEngine.prototype.updateRawCubeTexture = function(i, e, t, r, n, o, a) {
    o === void 0 && (o = null),
    a === void 0 && (a = 0),
    i._bufferViewArray = e,
    i.format = t,
    i.type = r,
    i.invertY = n,
    i._compression = o;
    var s = this._gl
      , l = this._getWebGLTextureType(r)
      , u = this._getInternalFormat(t)
      , c = this._getRGBABufferInternalSizedFormat(r)
      , h = !1;
    u === s.RGB && (u = s.RGBA,
    h = !0),
    this._bindTextureDirectly(s.TEXTURE_CUBE_MAP, i, !0),
    this._unpackFlipY(n === void 0 ? !0 : !!n),
    i.width % 4 !== 0 && s.pixelStorei(s.UNPACK_ALIGNMENT, 1);
    for (var f = 0; f < 6; f++) {
        var d = e[f];
        o ? s.compressedTexImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X + f, a, this.getCaps().s3tc[o], i.width, i.height, 0, d) : (h && (d = _convertRGBtoRGBATextureData$1(d, i.width, i.height, r)),
        s.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X + f, a, c, i.width, i.height, 0, u, l, d))
    }
    var _ = !this.needPOTTextures || Tools.IsExponentOfTwo(i.width) && Tools.IsExponentOfTwo(i.height);
    _ && i.generateMipMaps && a === 0 && this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP),
    this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null),
    i.isReady = !0
}
;
ThinEngine.prototype.createRawCubeTextureFromUrl = function(i, e, t, r, n, o, a, s, l, u, c, h) {
    var f = this;
    l === void 0 && (l = null),
    u === void 0 && (u = null),
    c === void 0 && (c = 3),
    h === void 0 && (h = !1);
    var d = this._gl
      , _ = this.createRawCubeTexture(null, t, r, n, !o, h, c, null);
    e == null || e._addPendingData(_),
    _.url = i,
    this._internalTexturesCache.push(_);
    var g = function(v, y) {
        e == null || e._removePendingData(_),
        u && v && u(v.status + " " + v.statusText, y)
    }
      , m = function(v) {
        var y = _.width
          , b = a(v);
        if (!!b) {
            if (s) {
                var T = f._getWebGLTextureType(n)
                  , C = f._getInternalFormat(r)
                  , A = f._getRGBABufferInternalSizedFormat(n)
                  , S = !1;
                C === d.RGB && (C = d.RGBA,
                S = !0),
                f._bindTextureDirectly(d.TEXTURE_CUBE_MAP, _, !0),
                f._unpackFlipY(!1);
                for (var P = s(b), R = 0; R < P.length; R++)
                    for (var M = y >> R, x = 0; x < 6; x++) {
                        var I = P[R][x];
                        S && (I = _convertRGBtoRGBATextureData$1(I, M, M, n)),
                        d.texImage2D(x, R, A, M, M, 0, C, T, I)
                    }
                f._bindTextureDirectly(d.TEXTURE_CUBE_MAP, null)
            } else
                f.updateRawCubeTexture(_, b, r, n, h);
            _.isReady = !0,
            e == null || e._removePendingData(_),
            l && l()
        }
    };
    return this._loadFile(i, function(v) {
        m(v)
    }, void 0, e == null ? void 0 : e.offlineProvider, !0, g),
    _
}
;
function _convertRGBtoRGBATextureData$1(i, e, t, r) {
    var n, o = 1;
    r === 1 ? n = new Float32Array(e * t * 4) : r === 2 ? (n = new Uint16Array(e * t * 4),
    o = 15360) : r === 7 ? n = new Uint32Array(e * t * 4) : n = new Uint8Array(e * t * 4);
    for (var a = 0; a < e; a++)
        for (var s = 0; s < t; s++) {
            var l = (s * e + a) * 3
              , u = (s * e + a) * 4;
            n[u + 0] = i[l + 0],
            n[u + 1] = i[l + 1],
            n[u + 2] = i[l + 2],
            n[u + 3] = o
        }
    return n
}
function _makeCreateRawTextureFunction(i) {
    return function(e, t, r, n, o, a, s, l, u, c) {
        u === void 0 && (u = null),
        c === void 0 && (c = 0);
        var h = i ? this._gl.TEXTURE_3D : this._gl.TEXTURE_2D_ARRAY
          , f = i ? InternalTextureSource.Raw3D : InternalTextureSource.Raw2DArray
          , d = new InternalTexture(this,f);
        d.baseWidth = t,
        d.baseHeight = r,
        d.baseDepth = n,
        d.width = t,
        d.height = r,
        d.depth = n,
        d.format = o,
        d.type = c,
        d.generateMipMaps = a,
        d.samplingMode = l,
        i ? d.is3D = !0 : d.is2DArray = !0,
        this._doNotHandleContextLost || (d._bufferView = e),
        i ? this.updateRawTexture3D(d, e, o, s, u, c) : this.updateRawTexture2DArray(d, e, o, s, u, c),
        this._bindTextureDirectly(h, d, !0);
        var _ = this._getSamplingParameters(l, a);
        return this._gl.texParameteri(h, this._gl.TEXTURE_MAG_FILTER, _.mag),
        this._gl.texParameteri(h, this._gl.TEXTURE_MIN_FILTER, _.min),
        a && this._gl.generateMipmap(h),
        this._bindTextureDirectly(h, null),
        this._internalTexturesCache.push(d),
        d
    }
}
ThinEngine.prototype.createRawTexture2DArray = _makeCreateRawTextureFunction(!1);
ThinEngine.prototype.createRawTexture3D = _makeCreateRawTextureFunction(!0);
function _makeUpdateRawTextureFunction(i) {
    return function(e, t, r, n, o, a) {
        o === void 0 && (o = null),
        a === void 0 && (a = 0);
        var s = i ? this._gl.TEXTURE_3D : this._gl.TEXTURE_2D_ARRAY
          , l = this._getWebGLTextureType(a)
          , u = this._getInternalFormat(r)
          , c = this._getRGBABufferInternalSizedFormat(a, r);
        this._bindTextureDirectly(s, e, !0),
        this._unpackFlipY(n === void 0 ? !0 : !!n),
        this._doNotHandleContextLost || (e._bufferView = t,
        e.format = r,
        e.invertY = n,
        e._compression = o),
        e.width % 4 !== 0 && this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1),
        o && t ? this._gl.compressedTexImage3D(s, 0, this.getCaps().s3tc[o], e.width, e.height, e.depth, 0, t) : this._gl.texImage3D(s, 0, c, e.width, e.height, e.depth, 0, u, l, t),
        e.generateMipMaps && this._gl.generateMipmap(s),
        this._bindTextureDirectly(s, null),
        e.isReady = !0
    }
}
ThinEngine.prototype.updateRawTexture2DArray = _makeUpdateRawTextureFunction(!1);
ThinEngine.prototype.updateRawTexture3D = _makeUpdateRawTextureFunction(!0);
var RawTexture = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a, s, l, u, c, h) {
        s === void 0 && (s = !0),
        l === void 0 && (l = !1),
        u === void 0 && (u = 3),
        c === void 0 && (c = 0);
        var f = i.call(this, null, a, !s, l, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, h) || this;
        return f.format = o,
        f._engine && (!f._engine._caps.textureFloatLinearFiltering && c === 1 && (u = 1),
        !f._engine._caps.textureHalfFloatLinearFiltering && c === 2 && (u = 1),
        f._texture = f._engine.createRawTexture(t, r, n, o, s, l, u, null, c, h != null ? h : 0),
        f.wrapU = Texture.CLAMP_ADDRESSMODE,
        f.wrapV = Texture.CLAMP_ADDRESSMODE),
        f
    }
    return e.prototype.update = function(t) {
        this._getEngine().updateRawTexture(this._texture, t, this._texture.format, this._texture.invertY, null, this._texture.type)
    }
    ,
    e.CreateLuminanceTexture = function(t, r, n, o, a, s, l) {
        return a === void 0 && (a = !0),
        s === void 0 && (s = !1),
        l === void 0 && (l = 3),
        new e(t,r,n,1,o,a,s,l)
    }
    ,
    e.CreateLuminanceAlphaTexture = function(t, r, n, o, a, s, l) {
        return a === void 0 && (a = !0),
        s === void 0 && (s = !1),
        l === void 0 && (l = 3),
        new e(t,r,n,2,o,a,s,l)
    }
    ,
    e.CreateAlphaTexture = function(t, r, n, o, a, s, l) {
        return a === void 0 && (a = !0),
        s === void 0 && (s = !1),
        l === void 0 && (l = 3),
        new e(t,r,n,0,o,a,s,l)
    }
    ,
    e.CreateRGBTexture = function(t, r, n, o, a, s, l, u) {
        return a === void 0 && (a = !0),
        s === void 0 && (s = !1),
        l === void 0 && (l = 3),
        u === void 0 && (u = 0),
        new e(t,r,n,4,o,a,s,l,u)
    }
    ,
    e.CreateRGBATexture = function(t, r, n, o, a, s, l, u) {
        return a === void 0 && (a = !0),
        s === void 0 && (s = !1),
        l === void 0 && (l = 3),
        u === void 0 && (u = 0),
        new e(t,r,n,5,o,a,s,l,u)
    }
    ,
    e.CreateRGBAStorageTexture = function(t, r, n, o, a, s, l, u) {
        return a === void 0 && (a = !0),
        s === void 0 && (s = !1),
        l === void 0 && (l = 3),
        u === void 0 && (u = 0),
        new e(t,r,n,5,o,a,s,l,u,1)
    }
    ,
    e.CreateRTexture = function(t, r, n, o, a, s, l, u) {
        return a === void 0 && (a = !0),
        s === void 0 && (s = !1),
        l === void 0 && (l = Texture.TRILINEAR_SAMPLINGMODE),
        u === void 0 && (u = 1),
        new e(t,r,n,6,o,a,s,l,u)
    }
    ,
    e.CreateRStorageTexture = function(t, r, n, o, a, s, l, u) {
        return a === void 0 && (a = !0),
        s === void 0 && (s = !1),
        l === void 0 && (l = Texture.TRILINEAR_SAMPLINGMODE),
        u === void 0 && (u = 1),
        new e(t,r,n,6,o,a,s,l,u,1)
    }
    ,
    e
}(Texture)
  , Skeleton = function() {
    function i(e, t, r) {
        this.name = e,
        this.id = t,
        this.bones = new Array,
        this.needInitialSkinMatrix = !1,
        this.overrideMesh = null,
        this._isDirty = !0,
        this._meshesWithPoseMatrix = new Array,
        this._identity = Matrix.Identity(),
        this._ranges = {},
        this._lastAbsoluteTransformsUpdateId = -1,
        this._canUseTextureForBones = !1,
        this._uniqueId = 0,
        this._numBonesWithLinkedTransformNode = 0,
        this._hasWaitingData = null,
        this._waitingOverrideMeshId = null,
        this._parentContainer = null,
        this.doNotSerialize = !1,
        this._useTextureToStoreBoneMatrices = !0,
        this._animationPropertiesOverride = null,
        this.onBeforeComputeObservable = new Observable,
        this.bones = [],
        this._scene = r || EngineStore.LastCreatedScene,
        this._uniqueId = this._scene.getUniqueId(),
        this._scene.addSkeleton(this),
        this._isDirty = !0;
        var n = this._scene.getEngine().getCaps();
        this._canUseTextureForBones = n.textureFloat && n.maxVertexTextureImageUnits > 0
    }
    return Object.defineProperty(i.prototype, "useTextureToStoreBoneMatrices", {
        get: function() {
            return this._useTextureToStoreBoneMatrices
        },
        set: function(e) {
            this._useTextureToStoreBoneMatrices = e,
            this._markAsDirty()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "animationPropertiesOverride", {
        get: function() {
            return this._animationPropertiesOverride ? this._animationPropertiesOverride : this._scene.animationPropertiesOverride
        },
        set: function(e) {
            this._animationPropertiesOverride = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "isUsingTextureForMatrices", {
        get: function() {
            return this.useTextureToStoreBoneMatrices && this._canUseTextureForBones
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "uniqueId", {
        get: function() {
            return this._uniqueId
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.getClassName = function() {
        return "Skeleton"
    }
    ,
    i.prototype.getChildren = function() {
        return this.bones.filter(function(e) {
            return !e.getParent()
        })
    }
    ,
    i.prototype.getTransformMatrices = function(e) {
        return this.needInitialSkinMatrix && e._bonesTransformMatrices ? e._bonesTransformMatrices : (this._transformMatrices || this.prepare(),
        this._transformMatrices)
    }
    ,
    i.prototype.getTransformMatrixTexture = function(e) {
        return this.needInitialSkinMatrix && e._transformMatrixTexture ? e._transformMatrixTexture : this._transformMatrixTexture
    }
    ,
    i.prototype.getScene = function() {
        return this._scene
    }
    ,
    i.prototype.toString = function(e) {
        var t = "Name: " + this.name + ", nBones: " + this.bones.length;
        if (t += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none"),
        e) {
            t += ", Ranges: {";
            var r = !0;
            for (var n in this._ranges)
                r && (t += ", ",
                r = !1),
                t += n;
            t += "}"
        }
        return t
    }
    ,
    i.prototype.getBoneIndexByName = function(e) {
        for (var t = 0, r = this.bones.length; t < r; t++)
            if (this.bones[t].name === e)
                return t;
        return -1
    }
    ,
    i.prototype.createAnimationRange = function(e, t, r) {
        if (!this._ranges[e]) {
            this._ranges[e] = new AnimationRange(e,t,r);
            for (var n = 0, o = this.bones.length; n < o; n++)
                this.bones[n].animations[0] && this.bones[n].animations[0].createRange(e, t, r)
        }
    }
    ,
    i.prototype.deleteAnimationRange = function(e, t) {
        t === void 0 && (t = !0);
        for (var r = 0, n = this.bones.length; r < n; r++)
            this.bones[r].animations[0] && this.bones[r].animations[0].deleteRange(e, t);
        this._ranges[e] = null
    }
    ,
    i.prototype.getAnimationRange = function(e) {
        return this._ranges[e] || null
    }
    ,
    i.prototype.getAnimationRanges = function() {
        var e = [], t;
        for (t in this._ranges)
            e.push(this._ranges[t]);
        return e
    }
    ,
    i.prototype.copyAnimationRange = function(e, t, r) {
        if (r === void 0 && (r = !1),
        this._ranges[t] || !e.getAnimationRange(t))
            return !1;
        var n = !0, o = this._getHighestAnimationFrame() + 1, a = {}, s = e.bones, l, u;
        for (u = 0,
        l = s.length; u < l; u++)
            a[s[u].name] = s[u];
        this.bones.length !== s.length && (Logger$2.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + s.length),
        n = !1);
        var c = r && this.dimensionsAtRest && e.dimensionsAtRest ? this.dimensionsAtRest.divide(e.dimensionsAtRest) : null;
        for (u = 0,
        l = this.bones.length; u < l; u++) {
            var h = this.bones[u].name
              , f = a[h];
            f ? n = n && this.bones[u].copyAnimationRange(f, t, o, r, c) : (Logger$2.Warn("copyAnimationRange: not same rig, missing source bone " + h),
            n = !1)
        }
        var d = e.getAnimationRange(t);
        return d && (this._ranges[t] = new AnimationRange(t,d.from + o,d.to + o)),
        n
    }
    ,
    i.prototype.returnToRest = function() {
        for (var e = 0, t = this.bones; e < t.length; e++) {
            var r = t[e];
            r._index !== -1 && r.returnToRest()
        }
    }
    ,
    i.prototype._getHighestAnimationFrame = function() {
        for (var e = 0, t = 0, r = this.bones.length; t < r; t++)
            if (this.bones[t].animations[0]) {
                var n = this.bones[t].animations[0].getHighestFrame();
                e < n && (e = n)
            }
        return e
    }
    ,
    i.prototype.beginAnimation = function(e, t, r, n) {
        var o = this.getAnimationRange(e);
        return o ? this._scene.beginAnimation(this, o.from, o.to, t, r, n) : null
    }
    ,
    i.MakeAnimationAdditive = function(e, t, r) {
        t === void 0 && (t = 0);
        var n = e.getAnimationRange(r);
        if (!n)
            return null;
        for (var o = e._scene.getAllAnimatablesByTarget(e), a = null, s = 0; s < o.length; s++) {
            var l = o[s];
            if (l.fromFrame === (n == null ? void 0 : n.from) && l.toFrame === (n == null ? void 0 : n.to)) {
                a = l;
                break
            }
        }
        for (var u = e.getAnimatables(), s = 0; s < u.length; s++) {
            var c = u[s]
              , h = c.animations;
            if (!!h)
                for (var f = 0; f < h.length; f++)
                    Animation.MakeAnimationAdditive(h[f], t, r)
        }
        return a && (a.isAdditive = !0),
        e
    }
    ,
    i.prototype._markAsDirty = function() {
        this._isDirty = !0
    }
    ,
    i.prototype._registerMeshWithPoseMatrix = function(e) {
        this._meshesWithPoseMatrix.push(e)
    }
    ,
    i.prototype._unregisterMeshWithPoseMatrix = function(e) {
        var t = this._meshesWithPoseMatrix.indexOf(e);
        t > -1 && this._meshesWithPoseMatrix.splice(t, 1)
    }
    ,
    i.prototype._computeTransformMatrices = function(e, t) {
        this.onBeforeComputeObservable.notifyObservers(this);
        for (var r = 0; r < this.bones.length; r++) {
            var n = this.bones[r];
            n._childUpdateId++;
            var o = n.getParent();
            if (o ? n.getLocalMatrix().multiplyToRef(o.getWorldMatrix(), n.getWorldMatrix()) : t ? n.getLocalMatrix().multiplyToRef(t, n.getWorldMatrix()) : n.getWorldMatrix().copyFrom(n.getLocalMatrix()),
            n._index !== -1) {
                var a = n._index === null ? r : n._index;
                n.getInvertedAbsoluteTransform().multiplyToArray(n.getWorldMatrix(), e, a * 16)
            }
        }
        this._identity.copyToArray(e, this.bones.length * 16)
    }
    ,
    i.prototype.prepare = function() {
        if (this._numBonesWithLinkedTransformNode > 0)
            for (var e = 0, t = this.bones; e < t.length; e++) {
                var r = t[e];
                r._linkedTransformNode && (r._linkedTransformNode.computeWorldMatrix(),
                r._matrix = r._linkedTransformNode._localMatrix)
            }
        if (!!this._isDirty) {
            if (this.needInitialSkinMatrix)
                for (var n = 0; n < this._meshesWithPoseMatrix.length; n++) {
                    var o = this._meshesWithPoseMatrix[n]
                      , a = o.getPoseMatrix();
                    if ((!o._bonesTransformMatrices || o._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) && (o._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1))),
                    this._synchronizedWithMesh !== o) {
                        this._synchronizedWithMesh = o;
                        for (var s = 0; s < this.bones.length; s++) {
                            var l = this.bones[s];
                            if (!l.getParent()) {
                                var u = l.getBaseMatrix();
                                u.multiplyToRef(a, TmpVectors.Matrix[1]),
                                l._updateDifferenceMatrix(TmpVectors.Matrix[1])
                            }
                        }
                        if (this.isUsingTextureForMatrices) {
                            var c = (this.bones.length + 1) * 4;
                            (!o._transformMatrixTexture || o._transformMatrixTexture.getSize().width !== c) && (o._transformMatrixTexture && o._transformMatrixTexture.dispose(),
                            o._transformMatrixTexture = RawTexture.CreateRGBATexture(o._bonesTransformMatrices, (this.bones.length + 1) * 4, 1, this._scene, !1, !1, 1, 1))
                        }
                    }
                    this._computeTransformMatrices(o._bonesTransformMatrices, a),
                    this.isUsingTextureForMatrices && o._transformMatrixTexture && o._transformMatrixTexture.update(o._bonesTransformMatrices)
                }
            else
                (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) && (this._transformMatrices = new Float32Array(16 * (this.bones.length + 1)),
                this.isUsingTextureForMatrices && (this._transformMatrixTexture && this._transformMatrixTexture.dispose(),
                this._transformMatrixTexture = RawTexture.CreateRGBATexture(this._transformMatrices, (this.bones.length + 1) * 4, 1, this._scene, !1, !1, 1, 1))),
                this._computeTransformMatrices(this._transformMatrices, null),
                this.isUsingTextureForMatrices && this._transformMatrixTexture && this._transformMatrixTexture.update(this._transformMatrices);
            this._isDirty = !1,
            this._scene._activeBones.addCount(this.bones.length, !1)
        }
    }
    ,
    i.prototype.getAnimatables = function() {
        if (!this._animatables || this._animatables.length !== this.bones.length) {
            this._animatables = [];
            for (var e = 0; e < this.bones.length; e++)
                this._animatables.push(this.bones[e])
        }
        return this._animatables
    }
    ,
    i.prototype.clone = function(e, t) {
        var r = new i(e,t || e,this._scene);
        r.needInitialSkinMatrix = this.needInitialSkinMatrix,
        r.overrideMesh = this.overrideMesh;
        for (var n = 0; n < this.bones.length; n++) {
            var o = this.bones[n]
              , a = null
              , s = o.getParent();
            if (s) {
                var l = this.bones.indexOf(s);
                a = r.bones[l]
            }
            var u = new Bone(o.name,r,a,o.getBaseMatrix().clone(),o.getRestPose().clone());
            u._index = o._index,
            o._linkedTransformNode && u.linkTransformNode(o._linkedTransformNode),
            DeepCopier.DeepCopy(o.animations, u.animations)
        }
        if (this._ranges) {
            r._ranges = {};
            for (var c in this._ranges) {
                var h = this._ranges[c];
                h && (r._ranges[c] = h.clone())
            }
        }
        return this._isDirty = !0,
        r
    }
    ,
    i.prototype.enableBlending = function(e) {
        e === void 0 && (e = .01),
        this.bones.forEach(function(t) {
            t.animations.forEach(function(r) {
                r.enableBlending = !0,
                r.blendingSpeed = e
            })
        })
    }
    ,
    i.prototype.dispose = function() {
        if (this._meshesWithPoseMatrix = [],
        this.getScene().stopAnimation(this),
        this.getScene().removeSkeleton(this),
        this._parentContainer) {
            var e = this._parentContainer.skeletons.indexOf(this);
            e > -1 && this._parentContainer.skeletons.splice(e, 1),
            this._parentContainer = null
        }
        this._transformMatrixTexture && (this._transformMatrixTexture.dispose(),
        this._transformMatrixTexture = null)
    }
    ,
    i.prototype.serialize = function() {
        var e, t, r = {};
        r.name = this.name,
        r.id = this.id,
        this.dimensionsAtRest && (r.dimensionsAtRest = this.dimensionsAtRest.asArray()),
        r.bones = [],
        r.needInitialSkinMatrix = this.needInitialSkinMatrix,
        r.overrideMeshId = (e = this.overrideMesh) === null || e === void 0 ? void 0 : e.id;
        for (var n = 0; n < this.bones.length; n++) {
            var o = this.bones[n]
              , a = o.getParent()
              , s = {
                parentBoneIndex: a ? this.bones.indexOf(a) : -1,
                index: o.getIndex(),
                name: o.name,
                id: o.id,
                matrix: o.getBaseMatrix().toArray(),
                rest: o.getRestPose().toArray(),
                linkedTransformNodeId: (t = o.getTransformNode()) === null || t === void 0 ? void 0 : t.id
            };
            r.bones.push(s),
            o.length && (s.length = o.length),
            o.metadata && (s.metadata = o.metadata),
            o.animations && o.animations.length > 0 && (s.animation = o.animations[0].serialize()),
            r.ranges = [];
            for (var l in this._ranges) {
                var u = this._ranges[l];
                if (!!u) {
                    var c = {};
                    c.name = l,
                    c.from = u.from,
                    c.to = u.to,
                    r.ranges.push(c)
                }
            }
        }
        return r
    }
    ,
    i.Parse = function(e, t) {
        var r = new i(e.name,e.id,t);
        e.dimensionsAtRest && (r.dimensionsAtRest = Vector3.FromArray(e.dimensionsAtRest)),
        r.needInitialSkinMatrix = e.needInitialSkinMatrix,
        e.overrideMeshId && (r._hasWaitingData = !0,
        r._waitingOverrideMeshId = e.overrideMeshId);
        var n;
        for (n = 0; n < e.bones.length; n++) {
            var o = e.bones[n]
              , a = e.bones[n].index
              , s = null;
            o.parentBoneIndex > -1 && (s = r.bones[o.parentBoneIndex]);
            var l = o.rest ? Matrix.FromArray(o.rest) : null
              , u = new Bone(o.name,r,s,Matrix.FromArray(o.matrix),l,null,a);
            o.id !== void 0 && o.id !== null && (u.id = o.id),
            o.length && (u.length = o.length),
            o.metadata && (u.metadata = o.metadata),
            o.animation && u.animations.push(Animation.Parse(o.animation)),
            o.linkedTransformNodeId !== void 0 && o.linkedTransformNodeId !== null && (r._hasWaitingData = !0,
            u._waitingTransformNodeId = o.linkedTransformNodeId)
        }
        if (e.ranges)
            for (n = 0; n < e.ranges.length; n++) {
                var c = e.ranges[n];
                r.createAnimationRange(c.name, c.from, c.to)
            }
        return r
    }
    ,
    i.prototype.computeAbsoluteTransforms = function(e) {
        e === void 0 && (e = !1);
        var t = this._scene.getRenderId();
        (this._lastAbsoluteTransformsUpdateId != t || e) && (this.bones[0].computeAbsoluteTransforms(),
        this._lastAbsoluteTransformsUpdateId = t)
    }
    ,
    i.prototype.getPoseMatrix = function() {
        var e = null;
        return this._meshesWithPoseMatrix.length > 0 && (e = this._meshesWithPoseMatrix[0].getPoseMatrix()),
        e
    }
    ,
    i.prototype.sortBones = function() {
        for (var e = new Array, t = new Array(this.bones.length), r = 0; r < this.bones.length; r++)
            this._sortBones(r, e, t);
        this.bones = e
    }
    ,
    i.prototype._sortBones = function(e, t, r) {
        if (!r[e]) {
            r[e] = !0;
            var n = this.bones[e];
            n._index === void 0 && (n._index = e);
            var o = n.getParent();
            o && this._sortBones(this.bones.indexOf(o), t, r),
            t.push(n)
        }
    }
    ,
    i.prototype.setCurrentPoseAsRest = function() {
        this.bones.forEach(function(e) {
            e.setCurrentPoseAsRest()
        })
    }
    ,
    i
}();
function inlineScheduler(i, e, t) {
    try {
        var r = i.next();
        r.done ? e(r) : r.value ? r.value.then(function() {
            r.value = void 0,
            e(r)
        }, t) : e(r)
    } catch (n) {
        t(n)
    }
}
function createYieldingScheduler(i) {
    i === void 0 && (i = 25);
    var e;
    return function(t, r, n) {
        var o = performance.now();
        e === void 0 || o - e > i ? (e = o,
        setTimeout(function() {
            inlineScheduler(t, r, n)
        }, 0)) : inlineScheduler(t, r, n)
    }
}
function runCoroutine(i, e, t, r, n) {
    var o = function() {
        var a, s = function(l) {
            l.done ? t(l.value) : a === void 0 ? a = !0 : o()
        };
        do
            a = void 0,
            !n || !n.aborted ? e(i, s, r) : r(new Error("Aborted")),
            a === void 0 && (a = !1);
        while (a)
    };
    o()
}
function runCoroutineSync(i, e) {
    var t;
    return runCoroutine(i, inlineScheduler, function(r) {
        return t = r
    }, function(r) {
        throw r
    }, e),
    t
}
function runCoroutineAsync(i, e, t) {
    return new Promise(function(r, n) {
        runCoroutine(i, e, r, n, t)
    }
    )
}
function makeSyncFunction(i, e) {
    return function() {
        for (var t = [], r = 0; r < arguments.length; r++)
            t[r] = arguments[r];
        return runCoroutineSync(i.apply(void 0, t), e)
    }
}
var VertexData = function() {
    function i() {
        this._applyTo = makeSyncFunction(this._applyToCoroutine.bind(this))
    }
    return i.prototype.set = function(e, t) {
        switch (e.length || Logger$2.Warn("Setting vertex data kind '" + t + "' with an empty array"),
        t) {
        case VertexBuffer.PositionKind:
            this.positions = e;
            break;
        case VertexBuffer.NormalKind:
            this.normals = e;
            break;
        case VertexBuffer.TangentKind:
            this.tangents = e;
            break;
        case VertexBuffer.UVKind:
            this.uvs = e;
            break;
        case VertexBuffer.UV2Kind:
            this.uvs2 = e;
            break;
        case VertexBuffer.UV3Kind:
            this.uvs3 = e;
            break;
        case VertexBuffer.UV4Kind:
            this.uvs4 = e;
            break;
        case VertexBuffer.UV5Kind:
            this.uvs5 = e;
            break;
        case VertexBuffer.UV6Kind:
            this.uvs6 = e;
            break;
        case VertexBuffer.ColorKind:
            this.colors = e;
            break;
        case VertexBuffer.MatricesIndicesKind:
            this.matricesIndices = e;
            break;
        case VertexBuffer.MatricesWeightsKind:
            this.matricesWeights = e;
            break;
        case VertexBuffer.MatricesIndicesExtraKind:
            this.matricesIndicesExtra = e;
            break;
        case VertexBuffer.MatricesWeightsExtraKind:
            this.matricesWeightsExtra = e;
            break
        }
    }
    ,
    i.prototype.applyToMesh = function(e, t) {
        return this._applyTo(e, t, !1),
        this
    }
    ,
    i.prototype.applyToGeometry = function(e, t) {
        return this._applyTo(e, t, !1),
        this
    }
    ,
    i.prototype.updateMesh = function(e) {
        return this._update(e),
        this
    }
    ,
    i.prototype.updateGeometry = function(e) {
        return this._update(e),
        this
    }
    ,
    i.prototype._applyToCoroutine = function(e, t, r) {
        return t === void 0 && (t = !1),
        __generator(this, function(n) {
            switch (n.label) {
            case 0:
                return this.positions ? (e.setVerticesData(VertexBuffer.PositionKind, this.positions, t),
                r ? [4] : [3, 2]) : [3, 2];
            case 1:
                n.sent(),
                n.label = 2;
            case 2:
                return this.normals ? (e.setVerticesData(VertexBuffer.NormalKind, this.normals, t),
                r ? [4] : [3, 4]) : [3, 4];
            case 3:
                n.sent(),
                n.label = 4;
            case 4:
                return this.tangents ? (e.setVerticesData(VertexBuffer.TangentKind, this.tangents, t),
                r ? [4] : [3, 6]) : [3, 6];
            case 5:
                n.sent(),
                n.label = 6;
            case 6:
                return this.uvs ? (e.setVerticesData(VertexBuffer.UVKind, this.uvs, t),
                r ? [4] : [3, 8]) : [3, 8];
            case 7:
                n.sent(),
                n.label = 8;
            case 8:
                return this.uvs2 ? (e.setVerticesData(VertexBuffer.UV2Kind, this.uvs2, t),
                r ? [4] : [3, 10]) : [3, 10];
            case 9:
                n.sent(),
                n.label = 10;
            case 10:
                return this.uvs3 ? (e.setVerticesData(VertexBuffer.UV3Kind, this.uvs3, t),
                r ? [4] : [3, 12]) : [3, 12];
            case 11:
                n.sent(),
                n.label = 12;
            case 12:
                return this.uvs4 ? (e.setVerticesData(VertexBuffer.UV4Kind, this.uvs4, t),
                r ? [4] : [3, 14]) : [3, 14];
            case 13:
                n.sent(),
                n.label = 14;
            case 14:
                return this.uvs5 ? (e.setVerticesData(VertexBuffer.UV5Kind, this.uvs5, t),
                r ? [4] : [3, 16]) : [3, 16];
            case 15:
                n.sent(),
                n.label = 16;
            case 16:
                return this.uvs6 ? (e.setVerticesData(VertexBuffer.UV6Kind, this.uvs6, t),
                r ? [4] : [3, 18]) : [3, 18];
            case 17:
                n.sent(),
                n.label = 18;
            case 18:
                return this.colors ? (e.setVerticesData(VertexBuffer.ColorKind, this.colors, t),
                r ? [4] : [3, 20]) : [3, 20];
            case 19:
                n.sent(),
                n.label = 20;
            case 20:
                return this.matricesIndices ? (e.setVerticesData(VertexBuffer.MatricesIndicesKind, this.matricesIndices, t),
                r ? [4] : [3, 22]) : [3, 22];
            case 21:
                n.sent(),
                n.label = 22;
            case 22:
                return this.matricesWeights ? (e.setVerticesData(VertexBuffer.MatricesWeightsKind, this.matricesWeights, t),
                r ? [4] : [3, 24]) : [3, 24];
            case 23:
                n.sent(),
                n.label = 24;
            case 24:
                return this.matricesIndicesExtra ? (e.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, t),
                r ? [4] : [3, 26]) : [3, 26];
            case 25:
                n.sent(),
                n.label = 26;
            case 26:
                return this.matricesWeightsExtra ? (e.setVerticesData(VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, t),
                r ? [4] : [3, 28]) : [3, 28];
            case 27:
                n.sent(),
                n.label = 28;
            case 28:
                return this.indices ? (e.setIndices(this.indices, null, t),
                r ? [4] : [3, 30]) : [3, 31];
            case 29:
                n.sent(),
                n.label = 30;
            case 30:
                return [3, 32];
            case 31:
                e.setIndices([], null),
                n.label = 32;
            case 32:
                return [2, this]
            }
        })
    }
    ,
    i.prototype._update = function(e, t, r) {
        return this.positions && e.updateVerticesData(VertexBuffer.PositionKind, this.positions, t, r),
        this.normals && e.updateVerticesData(VertexBuffer.NormalKind, this.normals, t, r),
        this.tangents && e.updateVerticesData(VertexBuffer.TangentKind, this.tangents, t, r),
        this.uvs && e.updateVerticesData(VertexBuffer.UVKind, this.uvs, t, r),
        this.uvs2 && e.updateVerticesData(VertexBuffer.UV2Kind, this.uvs2, t, r),
        this.uvs3 && e.updateVerticesData(VertexBuffer.UV3Kind, this.uvs3, t, r),
        this.uvs4 && e.updateVerticesData(VertexBuffer.UV4Kind, this.uvs4, t, r),
        this.uvs5 && e.updateVerticesData(VertexBuffer.UV5Kind, this.uvs5, t, r),
        this.uvs6 && e.updateVerticesData(VertexBuffer.UV6Kind, this.uvs6, t, r),
        this.colors && e.updateVerticesData(VertexBuffer.ColorKind, this.colors, t, r),
        this.matricesIndices && e.updateVerticesData(VertexBuffer.MatricesIndicesKind, this.matricesIndices, t, r),
        this.matricesWeights && e.updateVerticesData(VertexBuffer.MatricesWeightsKind, this.matricesWeights, t, r),
        this.matricesIndicesExtra && e.updateVerticesData(VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, t, r),
        this.matricesWeightsExtra && e.updateVerticesData(VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, t, r),
        this.indices && e.setIndices(this.indices, null),
        this
    }
    ,
    i._TransformVector3Coordinates = function(e, t) {
        for (var r = TmpVectors.Vector3[0], n = TmpVectors.Vector3[1], o = 0; o < e.length; o += 3)
            Vector3.FromArrayToRef(e, o, r),
            Vector3.TransformCoordinatesToRef(r, t, n),
            e[o] = n.x,
            e[o + 1] = n.y,
            e[o + 2] = n.z
    }
    ,
    i._TransformVector3Normals = function(e, t) {
        for (var r = TmpVectors.Vector3[0], n = TmpVectors.Vector3[1], o = 0; o < e.length; o += 3)
            Vector3.FromArrayToRef(e, o, r),
            Vector3.TransformNormalToRef(r, t, n),
            e[o] = n.x,
            e[o + 1] = n.y,
            e[o + 2] = n.z
    }
    ,
    i._TransformVector4Normals = function(e, t) {
        for (var r = TmpVectors.Vector4[0], n = TmpVectors.Vector4[1], o = 0; o < e.length; o += 4)
            Vector4.FromArrayToRef(e, o, r),
            Vector4.TransformNormalToRef(r, t, n),
            e[o] = n.x,
            e[o + 1] = n.y,
            e[o + 2] = n.z,
            e[o + 3] = n.w
    }
    ,
    i._FlipFaces = function(e) {
        for (var t = 0; t < e.length; t += 3) {
            var r = e[t + 1];
            e[t + 1] = e[t + 2],
            e[t + 2] = r
        }
    }
    ,
    i.prototype.transform = function(e) {
        var t = e.determinant() < 0;
        return this.positions && i._TransformVector3Coordinates(this.positions, e),
        this.normals && i._TransformVector3Normals(this.normals, e),
        this.tangents && i._TransformVector4Normals(this.tangents, e),
        t && this.indices && i._FlipFaces(this.indices),
        this
    }
    ,
    i.prototype.merge = function(e, t) {
        return t === void 0 && (t = !1),
        runCoroutineSync(this._mergeCoroutine(e, t, !1))
    }
    ,
    i.prototype._mergeCoroutine = function(e, t, r) {
        var n, o, f, a, s, l, u, c, h, f, d, _, g, m, v;
        return t === void 0 && (t = !1),
        __generator(this, function(y) {
            switch (y.label) {
            case 0:
                for (this._validate(),
                e = Array.isArray(e) ? e : [e],
                n = 0,
                o = e; n < o.length; n++)
                    if (f = o[n],
                    f._validate(),
                    !this.normals != !f.normals || !this.tangents != !f.tangents || !this.uvs != !f.uvs || !this.uvs2 != !f.uvs2 || !this.uvs3 != !f.uvs3 || !this.uvs4 != !f.uvs4 || !this.uvs5 != !f.uvs5 || !this.uvs6 != !f.uvs6 || !this.colors != !f.colors || !this.matricesIndices != !f.matricesIndices || !this.matricesWeights != !f.matricesWeights || !this.matricesIndicesExtra != !f.matricesIndicesExtra || !this.matricesWeightsExtra != !f.matricesWeightsExtra)
                        throw new Error("Cannot merge vertex data that do not have the same set of attributes");
                if (a = e.reduce(function(b, T) {
                    var C, A;
                    return b + ((A = (C = T.indices) === null || C === void 0 ? void 0 : C.length) !== null && A !== void 0 ? A : 0)
                }, (g = (_ = this.indices) === null || _ === void 0 ? void 0 : _.length) !== null && g !== void 0 ? g : 0),
                !(a > 0))
                    return [3, 4];
                s = (v = (m = this.indices) === null || m === void 0 ? void 0 : m.length) !== null && v !== void 0 ? v : 0,
                this.indices || (this.indices = new Array(a)),
                this.indices.length !== a && (Array.isArray(this.indices) ? this.indices.length = a : (l = t || this.indices instanceof Uint32Array ? new Uint32Array(a) : new Uint16Array(a),
                l.set(this.indices),
                this.indices = l)),
                u = this.positions ? this.positions.length / 3 : 0,
                c = 0,
                h = e,
                y.label = 1;
            case 1:
                if (!(c < h.length))
                    return [3, 4];
                if (f = h[c],
                !f.indices)
                    return [3, 3];
                for (d = 0; d < f.indices.length; d++)
                    this.indices[s + d] = f.indices[d] + u;
                return u += f.positions.length / 3,
                s += f.indices.length,
                r ? [4] : [3, 3];
            case 2:
                y.sent(),
                y.label = 3;
            case 3:
                return c++,
                [3, 1];
            case 4:
                return this.positions = i._mergeElement(this.positions, e.map(function(b) {
                    return b.positions
                })),
                r ? [4] : [3, 6];
            case 5:
                y.sent(),
                y.label = 6;
            case 6:
                return this.normals = i._mergeElement(this.normals, e.map(function(b) {
                    return b.normals
                })),
                r ? [4] : [3, 8];
            case 7:
                y.sent(),
                y.label = 8;
            case 8:
                return this.tangents = i._mergeElement(this.tangents, e.map(function(b) {
                    return b.tangents
                })),
                r ? [4] : [3, 10];
            case 9:
                y.sent(),
                y.label = 10;
            case 10:
                return this.uvs = i._mergeElement(this.uvs, e.map(function(b) {
                    return b.uvs
                })),
                r ? [4] : [3, 12];
            case 11:
                y.sent(),
                y.label = 12;
            case 12:
                return this.uvs2 = i._mergeElement(this.uvs2, e.map(function(b) {
                    return b.uvs2
                })),
                r ? [4] : [3, 14];
            case 13:
                y.sent(),
                y.label = 14;
            case 14:
                return this.uvs3 = i._mergeElement(this.uvs3, e.map(function(b) {
                    return b.uvs3
                })),
                r ? [4] : [3, 16];
            case 15:
                y.sent(),
                y.label = 16;
            case 16:
                return this.uvs4 = i._mergeElement(this.uvs4, e.map(function(b) {
                    return b.uvs4
                })),
                r ? [4] : [3, 18];
            case 17:
                y.sent(),
                y.label = 18;
            case 18:
                return this.uvs5 = i._mergeElement(this.uvs5, e.map(function(b) {
                    return b.uvs5
                })),
                r ? [4] : [3, 20];
            case 19:
                y.sent(),
                y.label = 20;
            case 20:
                return this.uvs6 = i._mergeElement(this.uvs6, e.map(function(b) {
                    return b.uvs6
                })),
                r ? [4] : [3, 22];
            case 21:
                y.sent(),
                y.label = 22;
            case 22:
                return this.colors = i._mergeElement(this.colors, e.map(function(b) {
                    return b.colors
                })),
                r ? [4] : [3, 24];
            case 23:
                y.sent(),
                y.label = 24;
            case 24:
                return this.matricesIndices = i._mergeElement(this.matricesIndices, e.map(function(b) {
                    return b.matricesIndices
                })),
                r ? [4] : [3, 26];
            case 25:
                y.sent(),
                y.label = 26;
            case 26:
                return this.matricesWeights = i._mergeElement(this.matricesWeights, e.map(function(b) {
                    return b.matricesWeights
                })),
                r ? [4] : [3, 28];
            case 27:
                y.sent(),
                y.label = 28;
            case 28:
                return this.matricesIndicesExtra = i._mergeElement(this.matricesIndicesExtra, e.map(function(b) {
                    return b.matricesIndicesExtra
                })),
                r ? [4] : [3, 30];
            case 29:
                y.sent(),
                y.label = 30;
            case 30:
                return this.matricesWeightsExtra = i._mergeElement(this.matricesWeightsExtra, e.map(function(b) {
                    return b.matricesWeightsExtra
                })),
                [2, this]
            }
        })
    }
    ,
    i._mergeElement = function(e, t) {
        var r = t.filter(function(_) {
            return _ != null
        });
        if (r.length === 0)
            return e;
        if (!e)
            return this._mergeElement(r[0], r.slice(1));
        var n = r.reduce(function(_, g) {
            return _ + g.length
        }, e.length);
        if (e instanceof Float32Array) {
            var o = new Float32Array(n);
            o.set(e);
            for (var a = e.length, s = 0, l = r; s < l.length; s++) {
                var u = l[s];
                o.set(u, a),
                a += u.length
            }
            return o
        } else {
            for (var c = new Array(n), h = 0; h < e.length; h++)
                c[h] = e[h];
            for (var a = e.length, f = 0, d = r; f < d.length; f++) {
                for (var u = d[f], h = 0; h < u.length; h++)
                    c[a + h] = u[h];
                a += u.length
            }
            return c
        }
    }
    ,
    i.prototype._validate = function() {
        if (!this.positions)
            throw new Error("Positions are required");
        var e = function(n, o) {
            var a = VertexBuffer.DeduceStride(n);
            if (o.length % a !== 0)
                throw new Error("The " + n + "s array count must be a multiple of " + a);
            return o.length / a
        }
          , t = e(VertexBuffer.PositionKind, this.positions)
          , r = function(n, o) {
            var a = e(n, o);
            if (a !== t)
                throw new Error("The " + n + "s element count (" + a + ") does not match the positions count (" + t + ")")
        };
        this.normals && r(VertexBuffer.NormalKind, this.normals),
        this.tangents && r(VertexBuffer.TangentKind, this.tangents),
        this.uvs && r(VertexBuffer.UVKind, this.uvs),
        this.uvs2 && r(VertexBuffer.UV2Kind, this.uvs2),
        this.uvs3 && r(VertexBuffer.UV3Kind, this.uvs3),
        this.uvs4 && r(VertexBuffer.UV4Kind, this.uvs4),
        this.uvs5 && r(VertexBuffer.UV5Kind, this.uvs5),
        this.uvs6 && r(VertexBuffer.UV6Kind, this.uvs6),
        this.colors && r(VertexBuffer.ColorKind, this.colors),
        this.matricesIndices && r(VertexBuffer.MatricesIndicesKind, this.matricesIndices),
        this.matricesWeights && r(VertexBuffer.MatricesWeightsKind, this.matricesWeights),
        this.matricesIndicesExtra && r(VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra),
        this.matricesWeightsExtra && r(VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra)
    }
    ,
    i.prototype.serialize = function() {
        var e = {};
        return this.positions && (e.positions = this.positions),
        this.normals && (e.normals = this.normals),
        this.tangents && (e.tangents = this.tangents),
        this.uvs && (e.uvs = this.uvs),
        this.uvs2 && (e.uvs2 = this.uvs2),
        this.uvs3 && (e.uvs3 = this.uvs3),
        this.uvs4 && (e.uvs4 = this.uvs4),
        this.uvs5 && (e.uvs5 = this.uvs5),
        this.uvs6 && (e.uvs6 = this.uvs6),
        this.colors && (e.colors = this.colors),
        this.matricesIndices && (e.matricesIndices = this.matricesIndices,
        e.matricesIndices._isExpanded = !0),
        this.matricesWeights && (e.matricesWeights = this.matricesWeights),
        this.matricesIndicesExtra && (e.matricesIndicesExtra = this.matricesIndicesExtra,
        e.matricesIndicesExtra._isExpanded = !0),
        this.matricesWeightsExtra && (e.matricesWeightsExtra = this.matricesWeightsExtra),
        e.indices = this.indices,
        e
    }
    ,
    i.ExtractFromMesh = function(e, t, r) {
        return i._ExtractFrom(e, t, r)
    }
    ,
    i.ExtractFromGeometry = function(e, t, r) {
        return i._ExtractFrom(e, t, r)
    }
    ,
    i._ExtractFrom = function(e, t, r) {
        var n = new i;
        return e.isVerticesDataPresent(VertexBuffer.PositionKind) && (n.positions = e.getVerticesData(VertexBuffer.PositionKind, t, r)),
        e.isVerticesDataPresent(VertexBuffer.NormalKind) && (n.normals = e.getVerticesData(VertexBuffer.NormalKind, t, r)),
        e.isVerticesDataPresent(VertexBuffer.TangentKind) && (n.tangents = e.getVerticesData(VertexBuffer.TangentKind, t, r)),
        e.isVerticesDataPresent(VertexBuffer.UVKind) && (n.uvs = e.getVerticesData(VertexBuffer.UVKind, t, r)),
        e.isVerticesDataPresent(VertexBuffer.UV2Kind) && (n.uvs2 = e.getVerticesData(VertexBuffer.UV2Kind, t, r)),
        e.isVerticesDataPresent(VertexBuffer.UV3Kind) && (n.uvs3 = e.getVerticesData(VertexBuffer.UV3Kind, t, r)),
        e.isVerticesDataPresent(VertexBuffer.UV4Kind) && (n.uvs4 = e.getVerticesData(VertexBuffer.UV4Kind, t, r)),
        e.isVerticesDataPresent(VertexBuffer.UV5Kind) && (n.uvs5 = e.getVerticesData(VertexBuffer.UV5Kind, t, r)),
        e.isVerticesDataPresent(VertexBuffer.UV6Kind) && (n.uvs6 = e.getVerticesData(VertexBuffer.UV6Kind, t, r)),
        e.isVerticesDataPresent(VertexBuffer.ColorKind) && (n.colors = e.getVerticesData(VertexBuffer.ColorKind, t, r)),
        e.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind) && (n.matricesIndices = e.getVerticesData(VertexBuffer.MatricesIndicesKind, t, r)),
        e.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind) && (n.matricesWeights = e.getVerticesData(VertexBuffer.MatricesWeightsKind, t, r)),
        e.isVerticesDataPresent(VertexBuffer.MatricesIndicesExtraKind) && (n.matricesIndicesExtra = e.getVerticesData(VertexBuffer.MatricesIndicesExtraKind, t, r)),
        e.isVerticesDataPresent(VertexBuffer.MatricesWeightsExtraKind) && (n.matricesWeightsExtra = e.getVerticesData(VertexBuffer.MatricesWeightsExtraKind, t, r)),
        n.indices = e.getIndices(t, r),
        n
    }
    ,
    i.CreateRibbon = function(e) {
        throw _WarnImport("ribbonBuilder")
    }
    ,
    i.CreateBox = function(e) {
        throw _WarnImport("boxBuilder")
    }
    ,
    i.CreateTiledBox = function(e) {
        throw _WarnImport("tiledBoxBuilder")
    }
    ,
    i.CreateTiledPlane = function(e) {
        throw _WarnImport("tiledPlaneBuilder")
    }
    ,
    i.CreateSphere = function(e) {
        throw _WarnImport("sphereBuilder")
    }
    ,
    i.CreateCylinder = function(e) {
        throw _WarnImport("cylinderBuilder")
    }
    ,
    i.CreateTorus = function(e) {
        throw _WarnImport("torusBuilder")
    }
    ,
    i.CreateLineSystem = function(e) {
        throw _WarnImport("linesBuilder")
    }
    ,
    i.CreateDashedLines = function(e) {
        throw _WarnImport("linesBuilder")
    }
    ,
    i.CreateGround = function(e) {
        throw _WarnImport("groundBuilder")
    }
    ,
    i.CreateTiledGround = function(e) {
        throw _WarnImport("groundBuilder")
    }
    ,
    i.CreateGroundFromHeightMap = function(e) {
        throw _WarnImport("groundBuilder")
    }
    ,
    i.CreatePlane = function(e) {
        throw _WarnImport("planeBuilder")
    }
    ,
    i.CreateDisc = function(e) {
        throw _WarnImport("discBuilder")
    }
    ,
    i.CreatePolygon = function(e, t, r, n, o, a, s) {
        throw _WarnImport("polygonBuilder")
    }
    ,
    i.CreateIcoSphere = function(e) {
        throw _WarnImport("icoSphereBuilder")
    }
    ,
    i.CreatePolyhedron = function(e) {
        throw _WarnImport("polyhedronBuilder")
    }
    ,
    i.CreateCapsule = function(e) {
        throw e === void 0 && (e = {
            orientation: Vector3.Up(),
            subdivisions: 2,
            tessellation: 16,
            height: 1,
            radius: .25,
            capSubdivisions: 6
        }),
        _WarnImport("capsuleBuilder")
    }
    ,
    i.CreateTorusKnot = function(e) {
        throw _WarnImport("torusKnotBuilder")
    }
    ,
    i.ComputeNormals = function(e, t, r, n) {
        var o = 0
          , a = 0
          , s = 0
          , l = 0
          , u = 0
          , c = 0
          , h = 0
          , f = 0
          , d = 0
          , _ = 0
          , g = 0
          , m = 0
          , v = 0
          , y = 0
          , b = 0
          , T = 0
          , C = 0
          , A = 0
          , S = 0
          , P = 0
          , R = !1
          , M = !1
          , x = !1
          , I = !1
          , w = 1
          , O = 0
          , D = null;
        if (n && (R = !!n.facetNormals,
        M = !!n.facetPositions,
        x = !!n.facetPartitioning,
        w = n.useRightHandedSystem === !0 ? -1 : 1,
        O = n.ratio || 0,
        I = !!n.depthSort,
        D = n.distanceTo,
        I)) {
            D === void 0 && (D = Vector3.Zero());
            var F = n.depthSortedFacets
        }
        var V = 0
          , N = 0
          , L = 0
          , k = 0;
        if (x && n && n.bbSize) {
            var U = 0
              , z = 0
              , H = 0
              , G = 0
              , W = 0
              , j = 0
              , B = 0
              , X = 0
              , $ = 0
              , Y = 0
              , K = 0
              , Z = 0
              , q = 0
              , J = 0
              , Q = 0
              , te = 0
              , re = n.bbSize.x > n.bbSize.y ? n.bbSize.x : n.bbSize.y;
            re = re > n.bbSize.z ? re : n.bbSize.z,
            V = n.subDiv.X * O / n.bbSize.x,
            N = n.subDiv.Y * O / n.bbSize.y,
            L = n.subDiv.Z * O / n.bbSize.z,
            k = n.subDiv.max * n.subDiv.max,
            n.facetPartitioning.length = 0
        }
        for (o = 0; o < e.length; o++)
            r[o] = 0;
        var ie = t.length / 3 | 0;
        for (o = 0; o < ie; o++) {
            if (m = t[o * 3] * 3,
            v = m + 1,
            y = m + 2,
            b = t[o * 3 + 1] * 3,
            T = b + 1,
            C = b + 2,
            A = t[o * 3 + 2] * 3,
            S = A + 1,
            P = A + 2,
            a = e[m] - e[b],
            s = e[v] - e[T],
            l = e[y] - e[C],
            u = e[A] - e[b],
            c = e[S] - e[T],
            h = e[P] - e[C],
            f = w * (s * h - l * c),
            d = w * (l * u - a * h),
            _ = w * (a * c - s * u),
            g = Math.sqrt(f * f + d * d + _ * _),
            g = g === 0 ? 1 : g,
            f /= g,
            d /= g,
            _ /= g,
            R && n && (n.facetNormals[o].x = f,
            n.facetNormals[o].y = d,
            n.facetNormals[o].z = _),
            M && n && (n.facetPositions[o].x = (e[m] + e[b] + e[A]) / 3,
            n.facetPositions[o].y = (e[v] + e[T] + e[S]) / 3,
            n.facetPositions[o].z = (e[y] + e[C] + e[P]) / 3),
            x && n && (U = Math.floor((n.facetPositions[o].x - n.bInfo.minimum.x * O) * V),
            z = Math.floor((n.facetPositions[o].y - n.bInfo.minimum.y * O) * N),
            H = Math.floor((n.facetPositions[o].z - n.bInfo.minimum.z * O) * L),
            G = Math.floor((e[m] - n.bInfo.minimum.x * O) * V),
            W = Math.floor((e[v] - n.bInfo.minimum.y * O) * N),
            j = Math.floor((e[y] - n.bInfo.minimum.z * O) * L),
            B = Math.floor((e[b] - n.bInfo.minimum.x * O) * V),
            X = Math.floor((e[T] - n.bInfo.minimum.y * O) * N),
            $ = Math.floor((e[C] - n.bInfo.minimum.z * O) * L),
            Y = Math.floor((e[A] - n.bInfo.minimum.x * O) * V),
            K = Math.floor((e[S] - n.bInfo.minimum.y * O) * N),
            Z = Math.floor((e[P] - n.bInfo.minimum.z * O) * L),
            J = G + n.subDiv.max * W + k * j,
            Q = B + n.subDiv.max * X + k * $,
            te = Y + n.subDiv.max * K + k * Z,
            q = U + n.subDiv.max * z + k * H,
            n.facetPartitioning[q] = n.facetPartitioning[q] ? n.facetPartitioning[q] : new Array,
            n.facetPartitioning[J] = n.facetPartitioning[J] ? n.facetPartitioning[J] : new Array,
            n.facetPartitioning[Q] = n.facetPartitioning[Q] ? n.facetPartitioning[Q] : new Array,
            n.facetPartitioning[te] = n.facetPartitioning[te] ? n.facetPartitioning[te] : new Array,
            n.facetPartitioning[J].push(o),
            Q != J && n.facetPartitioning[Q].push(o),
            te == Q || te == J || n.facetPartitioning[te].push(o),
            q == J || q == Q || q == te || n.facetPartitioning[q].push(o)),
            I && n && n.facetPositions) {
                var ee = F[o];
                ee.ind = o * 3,
                ee.sqDistance = Vector3.DistanceSquared(n.facetPositions[o], D)
            }
            r[m] += f,
            r[v] += d,
            r[y] += _,
            r[b] += f,
            r[T] += d,
            r[C] += _,
            r[A] += f,
            r[S] += d,
            r[P] += _
        }
        for (o = 0; o < r.length / 3; o++)
            f = r[o * 3],
            d = r[o * 3 + 1],
            _ = r[o * 3 + 2],
            g = Math.sqrt(f * f + d * d + _ * _),
            g = g === 0 ? 1 : g,
            f /= g,
            d /= g,
            _ /= g,
            r[o * 3] = f,
            r[o * 3 + 1] = d,
            r[o * 3 + 2] = _
    }
    ,
    i._ComputeSides = function(e, t, r, n, o, a, s) {
        var l = r.length, u = n.length, c, h;
        switch (e = e || i.DEFAULTSIDE,
        e) {
        case i.FRONTSIDE:
            break;
        case i.BACKSIDE:
            var f;
            for (c = 0; c < l; c += 3)
                f = r[c],
                r[c] = r[c + 2],
                r[c + 2] = f;
            for (h = 0; h < u; h++)
                n[h] = -n[h];
            break;
        case i.DOUBLESIDE:
            for (var d = t.length, _ = d / 3, g = 0; g < d; g++)
                t[d + g] = t[g];
            for (c = 0; c < l; c += 3)
                r[c + l] = r[c + 2] + _,
                r[c + 1 + l] = r[c + 1] + _,
                r[c + 2 + l] = r[c] + _;
            for (h = 0; h < u; h++)
                n[u + h] = -n[h];
            var m = o.length
              , v = 0;
            for (v = 0; v < m; v++)
                o[v + m] = o[v];
            for (a = a || new Vector4(0,0,1,1),
            s = s || new Vector4(0,0,1,1),
            v = 0,
            c = 0; c < m / 2; c++)
                o[v] = a.x + (a.z - a.x) * o[v],
                o[v + 1] = a.y + (a.w - a.y) * o[v + 1],
                o[v + m] = s.x + (s.z - s.x) * o[v + m],
                o[v + m + 1] = s.y + (s.w - s.y) * o[v + m + 1],
                v += 2;
            break
        }
    }
    ,
    i.ImportVertexData = function(e, t) {
        var r = new i
          , n = e.positions;
        n && r.set(n, VertexBuffer.PositionKind);
        var o = e.normals;
        o && r.set(o, VertexBuffer.NormalKind);
        var a = e.tangents;
        a && r.set(a, VertexBuffer.TangentKind);
        var s = e.uvs;
        s && r.set(s, VertexBuffer.UVKind);
        var l = e.uv2s;
        l && r.set(l, VertexBuffer.UV2Kind);
        var u = e.uv3s;
        u && r.set(u, VertexBuffer.UV3Kind);
        var c = e.uv4s;
        c && r.set(c, VertexBuffer.UV4Kind);
        var h = e.uv5s;
        h && r.set(h, VertexBuffer.UV5Kind);
        var f = e.uv6s;
        f && r.set(f, VertexBuffer.UV6Kind);
        var d = e.colors;
        d && r.set(Color4.CheckColors4(d, n.length / 3), VertexBuffer.ColorKind);
        var _ = e.matricesIndices;
        _ && r.set(_, VertexBuffer.MatricesIndicesKind);
        var g = e.matricesWeights;
        g && r.set(g, VertexBuffer.MatricesWeightsKind);
        var m = e.indices;
        m && (r.indices = m),
        t.setAllVerticesData(r, e.updatable)
    }
    ,
    i.FRONTSIDE = 0,
    i.BACKSIDE = 1,
    i.DOUBLESIDE = 2,
    i.DEFAULTSIDE = 0,
    __decorate([nativeOverride.filter(function() {
        for (var e = [], t = 0; t < arguments.length; t++)
            e[t] = arguments[t];
        var r = e[0];
        return !Array.isArray(r)
    })], i, "_TransformVector3Coordinates", null),
    __decorate([nativeOverride.filter(function() {
        for (var e = [], t = 0; t < arguments.length; t++)
            e[t] = arguments[t];
        var r = e[0];
        return !Array.isArray(r)
    })], i, "_TransformVector3Normals", null),
    __decorate([nativeOverride.filter(function() {
        for (var e = [], t = 0; t < arguments.length; t++)
            e[t] = arguments[t];
        var r = e[0];
        return !Array.isArray(r)
    })], i, "_TransformVector4Normals", null),
    __decorate([nativeOverride.filter(function() {
        for (var e = [], t = 0; t < arguments.length; t++)
            e[t] = arguments[t];
        var r = e[0];
        return !Array.isArray(r)
    })], i, "_FlipFaces", null),
    i
}()
  , IntersectionInfo = function() {
    function i(e, t, r) {
        this.bu = e,
        this.bv = t,
        this.distance = r,
        this.faceId = 0,
        this.subMeshId = 0
    }
    return i
}()
  , BoundingBox = function() {
    function i(e, t, r) {
        this.vectors = ArrayTools.BuildArray(8, Vector3.Zero),
        this.center = Vector3.Zero(),
        this.centerWorld = Vector3.Zero(),
        this.extendSize = Vector3.Zero(),
        this.extendSizeWorld = Vector3.Zero(),
        this.directions = ArrayTools.BuildArray(3, Vector3.Zero),
        this.vectorsWorld = ArrayTools.BuildArray(8, Vector3.Zero),
        this.minimumWorld = Vector3.Zero(),
        this.maximumWorld = Vector3.Zero(),
        this.minimum = Vector3.Zero(),
        this.maximum = Vector3.Zero(),
        this._drawWrapperFront = null,
        this._drawWrapperBack = null,
        this.reConstruct(e, t, r)
    }
    return i.prototype.reConstruct = function(e, t, r) {
        var n = e.x
          , o = e.y
          , a = e.z
          , s = t.x
          , l = t.y
          , u = t.z
          , c = this.vectors;
        this.minimum.copyFromFloats(n, o, a),
        this.maximum.copyFromFloats(s, l, u),
        c[0].copyFromFloats(n, o, a),
        c[1].copyFromFloats(s, l, u),
        c[2].copyFromFloats(s, o, a),
        c[3].copyFromFloats(n, l, a),
        c[4].copyFromFloats(n, o, u),
        c[5].copyFromFloats(s, l, a),
        c[6].copyFromFloats(n, l, u),
        c[7].copyFromFloats(s, o, u),
        t.addToRef(e, this.center).scaleInPlace(.5),
        t.subtractToRef(e, this.extendSize).scaleInPlace(.5),
        this._worldMatrix = r || Matrix.IdentityReadOnly,
        this._update(this._worldMatrix)
    }
    ,
    i.prototype.scale = function(e) {
        var t = i.TmpVector3
          , r = this.maximum.subtractToRef(this.minimum, t[0])
          , n = r.length();
        r.normalizeFromLength(n);
        var o = n * e
          , a = r.scaleInPlace(o * .5)
          , s = this.center.subtractToRef(a, t[1])
          , l = this.center.addToRef(a, t[2]);
        return this.reConstruct(s, l, this._worldMatrix),
        this
    }
    ,
    i.prototype.getWorldMatrix = function() {
        return this._worldMatrix
    }
    ,
    i.prototype._update = function(e) {
        var t = this.minimumWorld
          , r = this.maximumWorld
          , n = this.directions
          , o = this.vectorsWorld
          , a = this.vectors;
        if (e.isIdentity()) {
            t.copyFrom(this.minimum),
            r.copyFrom(this.maximum);
            for (var s = 0; s < 8; ++s)
                o[s].copyFrom(a[s]);
            this.extendSizeWorld.copyFrom(this.extendSize),
            this.centerWorld.copyFrom(this.center)
        } else {
            t.setAll(Number.MAX_VALUE),
            r.setAll(-Number.MAX_VALUE);
            for (var s = 0; s < 8; ++s) {
                var l = o[s];
                Vector3.TransformCoordinatesToRef(a[s], e, l),
                t.minimizeInPlace(l),
                r.maximizeInPlace(l)
            }
            r.subtractToRef(t, this.extendSizeWorld).scaleInPlace(.5),
            r.addToRef(t, this.centerWorld).scaleInPlace(.5)
        }
        Vector3.FromArrayToRef(e.m, 0, n[0]),
        Vector3.FromArrayToRef(e.m, 4, n[1]),
        Vector3.FromArrayToRef(e.m, 8, n[2]),
        this._worldMatrix = e
    }
    ,
    i.prototype.isInFrustum = function(e) {
        return i.IsInFrustum(this.vectorsWorld, e)
    }
    ,
    i.prototype.isCompletelyInFrustum = function(e) {
        return i.IsCompletelyInFrustum(this.vectorsWorld, e)
    }
    ,
    i.prototype.intersectsPoint = function(e) {
        var t = this.minimumWorld
          , r = this.maximumWorld
          , n = t.x
          , o = t.y
          , a = t.z
          , s = r.x
          , l = r.y
          , u = r.z
          , c = e.x
          , h = e.y
          , f = e.z
          , d = -Epsilon;
        return !(s - c < d || d > c - n || l - h < d || d > h - o || u - f < d || d > f - a)
    }
    ,
    i.prototype.intersectsSphere = function(e) {
        return i.IntersectsSphere(this.minimumWorld, this.maximumWorld, e.centerWorld, e.radiusWorld)
    }
    ,
    i.prototype.intersectsMinMax = function(e, t) {
        var r = this.minimumWorld
          , n = this.maximumWorld
          , o = r.x
          , a = r.y
          , s = r.z
          , l = n.x
          , u = n.y
          , c = n.z
          , h = e.x
          , f = e.y
          , d = e.z
          , _ = t.x
          , g = t.y
          , m = t.z;
        return !(l < h || o > _ || u < f || a > g || c < d || s > m)
    }
    ,
    i.prototype.dispose = function() {
        var e, t;
        (e = this._drawWrapperFront) === null || e === void 0 || e.dispose(),
        (t = this._drawWrapperBack) === null || t === void 0 || t.dispose()
    }
    ,
    i.Intersects = function(e, t) {
        return e.intersectsMinMax(t.minimumWorld, t.maximumWorld)
    }
    ,
    i.IntersectsSphere = function(e, t, r, n) {
        var o = i.TmpVector3[0];
        Vector3.ClampToRef(r, e, t, o);
        var a = Vector3.DistanceSquared(r, o);
        return a <= n * n
    }
    ,
    i.IsCompletelyInFrustum = function(e, t) {
        for (var r = 0; r < 6; ++r)
            for (var n = t[r], o = 0; o < 8; ++o)
                if (n.dotCoordinate(e[o]) < 0)
                    return !1;
        return !0
    }
    ,
    i.IsInFrustum = function(e, t) {
        for (var r = 0; r < 6; ++r) {
            for (var n = !0, o = t[r], a = 0; a < 8; ++a)
                if (o.dotCoordinate(e[a]) >= 0) {
                    n = !1;
                    break
                }
            if (n)
                return !1
        }
        return !0
    }
    ,
    i.TmpVector3 = ArrayTools.BuildArray(3, Vector3.Zero),
    i
}()
  , BoundingSphere = function() {
    function i(e, t, r) {
        this.center = Vector3.Zero(),
        this.centerWorld = Vector3.Zero(),
        this.minimum = Vector3.Zero(),
        this.maximum = Vector3.Zero(),
        this.reConstruct(e, t, r)
    }
    return i.prototype.reConstruct = function(e, t, r) {
        this.minimum.copyFrom(e),
        this.maximum.copyFrom(t);
        var n = Vector3.Distance(e, t);
        t.addToRef(e, this.center).scaleInPlace(.5),
        this.radius = n * .5,
        this._update(r || Matrix.IdentityReadOnly)
    }
    ,
    i.prototype.scale = function(e) {
        var t = this.radius * e
          , r = i.TmpVector3
          , n = r[0].setAll(t)
          , o = this.center.subtractToRef(n, r[1])
          , a = this.center.addToRef(n, r[2]);
        return this.reConstruct(o, a, this._worldMatrix),
        this
    }
    ,
    i.prototype.getWorldMatrix = function() {
        return this._worldMatrix
    }
    ,
    i.prototype._update = function(e) {
        if (e.isIdentity())
            this.centerWorld.copyFrom(this.center),
            this.radiusWorld = this.radius;
        else {
            Vector3.TransformCoordinatesToRef(this.center, e, this.centerWorld);
            var t = i.TmpVector3[0];
            Vector3.TransformNormalFromFloatsToRef(1, 1, 1, e, t),
            this.radiusWorld = Math.max(Math.abs(t.x), Math.abs(t.y), Math.abs(t.z)) * this.radius
        }
    }
    ,
    i.prototype.isInFrustum = function(e) {
        for (var t = this.centerWorld, r = this.radiusWorld, n = 0; n < 6; n++)
            if (e[n].dotCoordinate(t) <= -r)
                return !1;
        return !0
    }
    ,
    i.prototype.isCenterInFrustum = function(e) {
        for (var t = this.centerWorld, r = 0; r < 6; r++)
            if (e[r].dotCoordinate(t) < 0)
                return !1;
        return !0
    }
    ,
    i.prototype.intersectsPoint = function(e) {
        var t = Vector3.DistanceSquared(this.centerWorld, e);
        return !(this.radiusWorld * this.radiusWorld < t)
    }
    ,
    i.Intersects = function(e, t) {
        var r = Vector3.DistanceSquared(e.centerWorld, t.centerWorld)
          , n = e.radiusWorld + t.radiusWorld;
        return !(n * n < r)
    }
    ,
    i.CreateFromCenterAndRadius = function(e, t, r) {
        this.TmpVector3[0].copyFrom(e),
        this.TmpVector3[1].copyFromFloats(0, 0, t),
        this.TmpVector3[2].copyFrom(e),
        this.TmpVector3[0].addInPlace(this.TmpVector3[1]),
        this.TmpVector3[2].subtractInPlace(this.TmpVector3[1]);
        var n = new i(this.TmpVector3[0],this.TmpVector3[2]);
        return r ? n._worldMatrix = r : n._worldMatrix = Matrix.Identity(),
        n
    }
    ,
    i.TmpVector3 = ArrayTools.BuildArray(3, Vector3.Zero),
    i
}()
  , _result0 = {
    min: 0,
    max: 0
}
  , _result1 = {
    min: 0,
    max: 0
}
  , computeBoxExtents = function(i, e, t) {
    var r = Vector3.Dot(e.centerWorld, i)
      , n = Math.abs(Vector3.Dot(e.directions[0], i)) * e.extendSize.x
      , o = Math.abs(Vector3.Dot(e.directions[1], i)) * e.extendSize.y
      , a = Math.abs(Vector3.Dot(e.directions[2], i)) * e.extendSize.z
      , s = n + o + a;
    t.min = r - s,
    t.max = r + s
}
  , axisOverlap = function(i, e, t) {
    return computeBoxExtents(i, e, _result0),
    computeBoxExtents(i, t, _result1),
    !(_result0.min > _result1.max || _result1.min > _result0.max)
}
  , BoundingInfo = function() {
    function i(e, t, r) {
        this._isLocked = !1,
        this.boundingBox = new BoundingBox(e,t,r),
        this.boundingSphere = new BoundingSphere(e,t,r)
    }
    return i.prototype.reConstruct = function(e, t, r) {
        this.boundingBox.reConstruct(e, t, r),
        this.boundingSphere.reConstruct(e, t, r)
    }
    ,
    Object.defineProperty(i.prototype, "minimum", {
        get: function() {
            return this.boundingBox.minimum
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "maximum", {
        get: function() {
            return this.boundingBox.maximum
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "isLocked", {
        get: function() {
            return this._isLocked
        },
        set: function(e) {
            this._isLocked = e
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.update = function(e) {
        this._isLocked || (this.boundingBox._update(e),
        this.boundingSphere._update(e))
    }
    ,
    i.prototype.centerOn = function(e, t) {
        var r = i.TmpVector3[0].copyFrom(e).subtractInPlace(t)
          , n = i.TmpVector3[1].copyFrom(e).addInPlace(t);
        return this.boundingBox.reConstruct(r, n, this.boundingBox.getWorldMatrix()),
        this.boundingSphere.reConstruct(r, n, this.boundingBox.getWorldMatrix()),
        this
    }
    ,
    i.prototype.encapsulate = function(e) {
        var t = Vector3.Minimize(this.minimum, e)
          , r = Vector3.Maximize(this.maximum, e);
        return this.reConstruct(t, r, this.boundingBox.getWorldMatrix()),
        this
    }
    ,
    i.prototype.encapsulateBoundingInfo = function(e) {
        return this.encapsulate(e.boundingBox.centerWorld.subtract(e.boundingBox.extendSizeWorld)),
        this.encapsulate(e.boundingBox.centerWorld.add(e.boundingBox.extendSizeWorld)),
        this
    }
    ,
    i.prototype.scale = function(e) {
        return this.boundingBox.scale(e),
        this.boundingSphere.scale(e),
        this
    }
    ,
    i.prototype.isInFrustum = function(e, t) {
        t === void 0 && (t = 0);
        var r = t === 2 || t === 3;
        if (r && this.boundingSphere.isCenterInFrustum(e))
            return !0;
        if (!this.boundingSphere.isInFrustum(e))
            return !1;
        var n = t === 1 || t === 3;
        return n ? !0 : this.boundingBox.isInFrustum(e)
    }
    ,
    Object.defineProperty(i.prototype, "diagonalLength", {
        get: function() {
            var e = this.boundingBox
              , t = e.maximumWorld.subtractToRef(e.minimumWorld, i.TmpVector3[0]);
            return t.length()
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.isCompletelyInFrustum = function(e) {
        return this.boundingBox.isCompletelyInFrustum(e)
    }
    ,
    i.prototype._checkCollision = function(e) {
        return e._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld)
    }
    ,
    i.prototype.intersectsPoint = function(e) {
        return !(!this.boundingSphere.centerWorld || !this.boundingSphere.intersectsPoint(e) || !this.boundingBox.intersectsPoint(e))
    }
    ,
    i.prototype.intersects = function(e, t) {
        if (!BoundingSphere.Intersects(this.boundingSphere, e.boundingSphere) || !BoundingBox.Intersects(this.boundingBox, e.boundingBox))
            return !1;
        if (!t)
            return !0;
        var r = this.boundingBox
          , n = e.boundingBox;
        return !(!axisOverlap(r.directions[0], r, n) || !axisOverlap(r.directions[1], r, n) || !axisOverlap(r.directions[2], r, n) || !axisOverlap(n.directions[0], r, n) || !axisOverlap(n.directions[1], r, n) || !axisOverlap(n.directions[2], r, n) || !axisOverlap(Vector3.Cross(r.directions[0], n.directions[0]), r, n) || !axisOverlap(Vector3.Cross(r.directions[0], n.directions[1]), r, n) || !axisOverlap(Vector3.Cross(r.directions[0], n.directions[2]), r, n) || !axisOverlap(Vector3.Cross(r.directions[1], n.directions[0]), r, n) || !axisOverlap(Vector3.Cross(r.directions[1], n.directions[1]), r, n) || !axisOverlap(Vector3.Cross(r.directions[1], n.directions[2]), r, n) || !axisOverlap(Vector3.Cross(r.directions[2], n.directions[0]), r, n) || !axisOverlap(Vector3.Cross(r.directions[2], n.directions[1]), r, n) || !axisOverlap(Vector3.Cross(r.directions[2], n.directions[2]), r, n))
    }
    ,
    i.TmpVector3 = ArrayTools.BuildArray(2, Vector3.Zero),
    i
}()
  , MathHelpers = function() {
    function i() {}
    return i.extractMinAndMaxIndexed = function(e, t, r, n, o, a) {
        for (var s = r; s < r + n; s++) {
            var l = t[s] * 3
              , u = e[l]
              , c = e[l + 1]
              , h = e[l + 2];
            o.minimizeInPlaceFromFloats(u, c, h),
            a.maximizeInPlaceFromFloats(u, c, h)
        }
    }
    ,
    i.extractMinAndMax = function(e, t, r, n, o, a) {
        for (var s = t, l = t * n; s < t + r; s++,
        l += n) {
            var u = e[l]
              , c = e[l + 1]
              , h = e[l + 2];
            o.minimizeInPlaceFromFloats(u, c, h),
            a.maximizeInPlaceFromFloats(u, c, h)
        }
    }
    ,
    __decorate([nativeOverride.filter(function() {
        for (var e = [], t = 0; t < arguments.length; t++)
            e[t] = arguments[t];
        var r = e[0]
          , n = e[1];
        return !Array.isArray(r) && !Array.isArray(n)
    })], i, "extractMinAndMaxIndexed", null),
    __decorate([nativeOverride.filter(function() {
        for (var e = [], t = 0; t < arguments.length; t++)
            e[t] = arguments[t];
        var r = e[0];
        return !Array.isArray(r)
    })], i, "extractMinAndMax", null),
    i
}();
function extractMinAndMaxIndexed(i, e, t, r, n) {
    n === void 0 && (n = null);
    var o = new Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)
      , a = new Vector3(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);
    return MathHelpers.extractMinAndMaxIndexed(i, e, t, r, o, a),
    n && (o.x -= o.x * n.x + n.y,
    o.y -= o.y * n.x + n.y,
    o.z -= o.z * n.x + n.y,
    a.x += a.x * n.x + n.y,
    a.y += a.y * n.x + n.y,
    a.z += a.z * n.x + n.y),
    {
        minimum: o,
        maximum: a
    }
}
function extractMinAndMax(i, e, t, r, n) {
    r === void 0 && (r = null);
    var o = new Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)
      , a = new Vector3(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);
    return n || (n = 3),
    MathHelpers.extractMinAndMax(i, e, t, n, o, a),
    r && (o.x -= o.x * r.x + r.y,
    o.y -= o.y * r.x + r.y,
    o.z -= o.z * r.x + r.y,
    a.x += a.x * r.x + r.y,
    a.y += a.y * r.x + r.y,
    a.z += a.z * r.x + r.y),
    {
        minimum: o,
        maximum: a
    }
}
var SubMesh = function() {
    function i(e, t, r, n, o, a, s, l, u) {
        l === void 0 && (l = !0),
        u === void 0 && (u = !0),
        this.materialIndex = e,
        this.verticesStart = t,
        this.verticesCount = r,
        this.indexStart = n,
        this.indexCount = o,
        this._mainDrawWrapperOverride = null,
        this._linesIndexCount = 0,
        this._linesIndexBuffer = null,
        this._lastColliderWorldVertices = null,
        this._lastColliderTransformMatrix = null,
        this._renderId = 0,
        this._alphaIndex = 0,
        this._distanceToCamera = 0,
        this._currentMaterial = null,
        this._mesh = a,
        this._renderingMesh = s || a,
        u && a.subMeshes.push(this),
        this._engine = this._mesh.getScene().getEngine(),
        this.resetDrawCache(),
        this._trianglePlanes = [],
        this._id = a.subMeshes.length - 1,
        l && (this.refreshBoundingInfo(),
        a.computeWorldMatrix(!0))
    }
    return Object.defineProperty(i.prototype, "materialDefines", {
        get: function() {
            var e;
            return this._mainDrawWrapperOverride ? this._mainDrawWrapperOverride.defines : (e = this._getDrawWrapper()) === null || e === void 0 ? void 0 : e.defines
        },
        set: function(e) {
            var t, r = (t = this._mainDrawWrapperOverride) !== null && t !== void 0 ? t : this._getDrawWrapper(void 0, !0);
            r.defines = e
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype._getDrawWrapper = function(e, t) {
        t === void 0 && (t = !1),
        e = e != null ? e : this._engine.currentRenderPassId;
        var r = this._drawWrappers[e];
        return !r && t && (this._drawWrappers[e] = r = new DrawWrapper(this._mesh.getScene().getEngine())),
        r
    }
    ,
    i.prototype._removeDrawWrapper = function(e, t) {
        var r;
        t === void 0 && (t = !0),
        t && ((r = this._drawWrappers[e]) === null || r === void 0 || r.dispose()),
        this._drawWrappers[e] = void 0
    }
    ,
    Object.defineProperty(i.prototype, "effect", {
        get: function() {
            var e, t;
            return this._mainDrawWrapperOverride ? this._mainDrawWrapperOverride.effect : (t = (e = this._getDrawWrapper()) === null || e === void 0 ? void 0 : e.effect) !== null && t !== void 0 ? t : null
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "_drawWrapper", {
        get: function() {
            var e;
            return (e = this._mainDrawWrapperOverride) !== null && e !== void 0 ? e : this._getDrawWrapper(void 0, !0)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "_drawWrapperOverride", {
        get: function() {
            return this._mainDrawWrapperOverride
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype._setMainDrawWrapperOverride = function(e) {
        this._mainDrawWrapperOverride = e
    }
    ,
    i.prototype.setEffect = function(e, t, r, n) {
        t === void 0 && (t = null),
        n === void 0 && (n = !0);
        var o = this._drawWrapper;
        o.setEffect(e, t, n),
        r !== void 0 && (o.materialContext = r),
        e || (o.defines = null,
        o.materialContext = void 0)
    }
    ,
    i.prototype.resetDrawCache = function() {
        if (this._drawWrappers)
            for (var e = 0, t = this._drawWrappers; e < t.length; e++) {
                var r = t[e];
                r == null || r.dispose()
            }
        this._drawWrappers = []
    }
    ,
    i.AddToMesh = function(e, t, r, n, o, a, s, l) {
        return l === void 0 && (l = !0),
        new i(e,t,r,n,o,a,s,l)
    }
    ,
    Object.defineProperty(i.prototype, "IsGlobal", {
        get: function() {
            return this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices()
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.getBoundingInfo = function() {
        return this.IsGlobal ? this._mesh.getBoundingInfo() : this._boundingInfo
    }
    ,
    i.prototype.setBoundingInfo = function(e) {
        return this._boundingInfo = e,
        this
    }
    ,
    i.prototype.getMesh = function() {
        return this._mesh
    }
    ,
    i.prototype.getRenderingMesh = function() {
        return this._renderingMesh
    }
    ,
    i.prototype.getReplacementMesh = function() {
        return this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh ? this._mesh : null
    }
    ,
    i.prototype.getEffectiveMesh = function() {
        var e = this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh ? this._mesh : null;
        return e || this._renderingMesh
    }
    ,
    i.prototype.getMaterial = function() {
        var e, t = (e = this._renderingMesh.getMaterialForRenderPass(this._engine.currentRenderPassId)) !== null && e !== void 0 ? e : this._renderingMesh.material;
        if (t == null)
            return this._mesh.getScene().defaultMaterial;
        if (this._IsMultiMaterial(t)) {
            var r = t.getSubMaterial(this.materialIndex);
            return this._currentMaterial !== r && (this._currentMaterial = r,
            this.resetDrawCache()),
            r
        }
        return t
    }
    ,
    i.prototype._IsMultiMaterial = function(e) {
        return e.getSubMaterial !== void 0
    }
    ,
    i.prototype.refreshBoundingInfo = function(e) {
        if (e === void 0 && (e = null),
        this._lastColliderWorldVertices = null,
        this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry)
            return this;
        if (e || (e = this._renderingMesh.getVerticesData(VertexBuffer.PositionKind)),
        !e)
            return this._boundingInfo = this._mesh.getBoundingInfo(),
            this;
        var t = this._renderingMesh.getIndices(), r;
        if (this.indexStart === 0 && this.indexCount === t.length) {
            var n = this._renderingMesh.getBoundingInfo();
            r = {
                minimum: n.minimum.clone(),
                maximum: n.maximum.clone()
            }
        } else
            r = extractMinAndMaxIndexed(e, t, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
        return this._boundingInfo ? this._boundingInfo.reConstruct(r.minimum, r.maximum) : this._boundingInfo = new BoundingInfo(r.minimum,r.maximum),
        this
    }
    ,
    i.prototype._checkCollision = function(e) {
        var t = this.getBoundingInfo();
        return t._checkCollision(e)
    }
    ,
    i.prototype.updateBoundingInfo = function(e) {
        var t = this.getBoundingInfo();
        return t || (this.refreshBoundingInfo(),
        t = this.getBoundingInfo()),
        t && t.update(e),
        this
    }
    ,
    i.prototype.isInFrustum = function(e) {
        var t = this.getBoundingInfo();
        return t ? t.isInFrustum(e, this._mesh.cullingStrategy) : !1
    }
    ,
    i.prototype.isCompletelyInFrustum = function(e) {
        var t = this.getBoundingInfo();
        return t ? t.isCompletelyInFrustum(e) : !1
    }
    ,
    i.prototype.render = function(e) {
        return this._renderingMesh.render(this, e, this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh ? this._mesh : void 0),
        this
    }
    ,
    i.prototype._getLinesIndexBuffer = function(e, t) {
        if (!this._linesIndexBuffer) {
            for (var r = [], n = this.indexStart; n < this.indexStart + this.indexCount; n += 3)
                r.push(e[n], e[n + 1], e[n + 1], e[n + 2], e[n + 2], e[n]);
            this._linesIndexBuffer = t.createIndexBuffer(r),
            this._linesIndexCount = r.length
        }
        return this._linesIndexBuffer
    }
    ,
    i.prototype.canIntersects = function(e) {
        var t = this.getBoundingInfo();
        return t ? e.intersectsBox(t.boundingBox) : !1
    }
    ,
    i.prototype.intersects = function(e, t, r, n, o) {
        var a = this.getMaterial();
        if (!a)
            return null;
        var s = 3
          , l = !1;
        switch (a.fillMode) {
        case 3:
        case 4:
        case 5:
        case 6:
        case 8:
            return null;
        case 7:
            s = 1,
            l = !0;
            break
        }
        return this._mesh.getClassName() === "InstancedLinesMesh" || this._mesh.getClassName() === "LinesMesh" ? r.length ? this._intersectLines(e, t, r, this._mesh.intersectionThreshold, n) : this._intersectUnIndexedLines(e, t, r, this._mesh.intersectionThreshold, n) : !r.length && this._mesh._unIndexed ? this._intersectUnIndexedTriangles(e, t, r, n, o) : this._intersectTriangles(e, t, r, s, l, n, o)
    }
    ,
    i.prototype._intersectLines = function(e, t, r, n, o) {
        for (var a = null, s = this.indexStart; s < this.indexStart + this.indexCount; s += 2) {
            var l = t[r[s]]
              , u = t[r[s + 1]]
              , c = e.intersectionSegment(l, u, n);
            if (!(c < 0) && (o || !a || c < a.distance) && (a = new IntersectionInfo(null,null,c),
            a.faceId = s / 2,
            o))
                break
        }
        return a
    }
    ,
    i.prototype._intersectUnIndexedLines = function(e, t, r, n, o) {
        for (var a = null, s = this.verticesStart; s < this.verticesStart + this.verticesCount; s += 2) {
            var l = t[s]
              , u = t[s + 1]
              , c = e.intersectionSegment(l, u, n);
            if (!(c < 0) && (o || !a || c < a.distance) && (a = new IntersectionInfo(null,null,c),
            a.faceId = s / 2,
            o))
                break
        }
        return a
    }
    ,
    i.prototype._intersectTriangles = function(e, t, r, n, o, a, s) {
        for (var l = null, u = -1, c = this.indexStart; c < this.indexStart + this.indexCount - (3 - n); c += n) {
            u++;
            var h = r[c]
              , f = r[c + 1]
              , d = r[c + 2];
            if (o && d === 4294967295) {
                c += 2;
                continue
            }
            var _ = t[h]
              , g = t[f]
              , m = t[d];
            if (!(!_ || !g || !m) && !(s && !s(_, g, m, e))) {
                var v = e.intersectsTriangle(_, g, m);
                if (v) {
                    if (v.distance < 0)
                        continue;
                    if ((a || !l || v.distance < l.distance) && (l = v,
                    l.faceId = u,
                    a))
                        break
                }
            }
        }
        return l
    }
    ,
    i.prototype._intersectUnIndexedTriangles = function(e, t, r, n, o) {
        for (var a = null, s = this.verticesStart; s < this.verticesStart + this.verticesCount; s += 3) {
            var l = t[s]
              , u = t[s + 1]
              , c = t[s + 2];
            if (!(o && !o(l, u, c, e))) {
                var h = e.intersectsTriangle(l, u, c);
                if (h) {
                    if (h.distance < 0)
                        continue;
                    if ((n || !a || h.distance < a.distance) && (a = h,
                    a.faceId = s / 3,
                    n))
                        break
                }
            }
        }
        return a
    }
    ,
    i.prototype._rebuild = function() {
        this._linesIndexBuffer && (this._linesIndexBuffer = null)
    }
    ,
    i.prototype.clone = function(e, t) {
        var r = new i(this.materialIndex,this.verticesStart,this.verticesCount,this.indexStart,this.indexCount,e,t,!1);
        if (!this.IsGlobal) {
            var n = this.getBoundingInfo();
            if (!n)
                return r;
            r._boundingInfo = new BoundingInfo(n.minimum,n.maximum)
        }
        return r
    }
    ,
    i.prototype.dispose = function() {
        this._linesIndexBuffer && (this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer),
        this._linesIndexBuffer = null);
        var e = this._mesh.subMeshes.indexOf(this);
        this._mesh.subMeshes.splice(e, 1),
        this.resetDrawCache()
    }
    ,
    i.prototype.getClassName = function() {
        return "SubMesh"
    }
    ,
    i.CreateFromIndices = function(e, t, r, n, o, a) {
        a === void 0 && (a = !0);
        for (var s = Number.MAX_VALUE, l = -Number.MAX_VALUE, u = o || n, c = u.getIndices(), h = t; h < t + r; h++) {
            var f = c[h];
            f < s && (s = f),
            f > l && (l = f)
        }
        return new i(e,s,l - s + 1,t,r,n,o,a)
    }
    ,
    i
}()
  , Geometry = function() {
    function i(e, t, r, n, o) {
        n === void 0 && (n = !1),
        o === void 0 && (o = null),
        this.delayLoadState = 0,
        this._totalVertices = 0,
        this._isDisposed = !1,
        this._indexBufferIsUpdatable = !1,
        this._positionsCache = [],
        this._parentContainer = null,
        this.useBoundingInfoFromGeometry = !1,
        this.id = e,
        this.uniqueId = t.getUniqueId(),
        this._engine = t.getEngine(),
        this._meshes = [],
        this._scene = t,
        this._vertexBuffers = {},
        this._indices = [],
        this._updatable = n,
        r ? this.setAllVerticesData(r, n) : (this._totalVertices = 0,
        this._indices = []),
        this._engine.getCaps().vertexArrayObject && (this._vertexArrayObjects = {}),
        o && (this.applyToMesh(o),
        o.computeWorldMatrix(!0))
    }
    return Object.defineProperty(i.prototype, "boundingBias", {
        get: function() {
            return this._boundingBias
        },
        set: function(e) {
            this._boundingBias ? this._boundingBias.copyFrom(e) : this._boundingBias = e.clone(),
            this._updateBoundingInfo(!0, null)
        },
        enumerable: !1,
        configurable: !0
    }),
    i.CreateGeometryForMesh = function(e) {
        var t = new i(i.RandomId(),e.getScene());
        return t.applyToMesh(e),
        t
    }
    ,
    Object.defineProperty(i.prototype, "meshes", {
        get: function() {
            return this._meshes
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "extend", {
        get: function() {
            return this._extend
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.getScene = function() {
        return this._scene
    }
    ,
    i.prototype.getEngine = function() {
        return this._engine
    }
    ,
    i.prototype.isReady = function() {
        return this.delayLoadState === 1 || this.delayLoadState === 0
    }
    ,
    Object.defineProperty(i.prototype, "doNotSerialize", {
        get: function() {
            for (var e = 0; e < this._meshes.length; e++)
                if (!this._meshes[e].doNotSerialize)
                    return !1;
            return !0
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype._rebuild = function() {
        this._vertexArrayObjects && (this._vertexArrayObjects = {}),
        this._meshes.length !== 0 && this._indices && (this._indexBuffer = this._engine.createIndexBuffer(this._indices, this._updatable));
        for (var e in this._vertexBuffers) {
            var t = this._vertexBuffers[e];
            t._rebuild()
        }
    }
    ,
    i.prototype.setAllVerticesData = function(e, t) {
        e.applyToGeometry(this, t),
        this.notifyUpdate()
    }
    ,
    i.prototype.setVerticesData = function(e, t, r, n) {
        r === void 0 && (r = !1),
        r && Array.isArray(t) && (t = new Float32Array(t));
        var o = new VertexBuffer(this._engine,t,e,r,this._meshes.length === 0,n);
        this.setVerticesBuffer(o)
    }
    ,
    i.prototype.removeVerticesData = function(e) {
        this._vertexBuffers[e] && (this._vertexBuffers[e].dispose(),
        delete this._vertexBuffers[e]),
        this._vertexArrayObjects && this._disposeVertexArrayObjects()
    }
    ,
    i.prototype.setVerticesBuffer = function(e, t, r) {
        t === void 0 && (t = null),
        r === void 0 && (r = !0);
        var n = e.getKind();
        this._vertexBuffers[n] && r && this._vertexBuffers[n].dispose(),
        e._buffer && e._buffer._increaseReferences(),
        this._vertexBuffers[n] = e;
        var o = this._meshes
          , a = o.length;
        if (n === VertexBuffer.PositionKind) {
            var s = e.getData();
            t != null ? this._totalVertices = t : s != null && (this._totalVertices = s.length / (e.type === VertexBuffer.BYTE ? e.byteStride : e.byteStride / 4)),
            this._updateExtend(s),
            this._resetPointsArrayCache();
            for (var l = 0; l < a; l++) {
                var u = o[l];
                u.buildBoundingInfo(this._extend.minimum, this._extend.maximum),
                u._createGlobalSubMesh(!1),
                u.computeWorldMatrix(!0),
                u.synchronizeInstances()
            }
        }
        this.notifyUpdate(n)
    }
    ,
    i.prototype.updateVerticesDataDirectly = function(e, t, r, n) {
        n === void 0 && (n = !1);
        var o = this.getVertexBuffer(e);
        !o || (o.updateDirectly(t, r, n),
        this.notifyUpdate(e))
    }
    ,
    i.prototype.updateVerticesData = function(e, t, r) {
        r === void 0 && (r = !1);
        var n = this.getVertexBuffer(e);
        !n || (n.update(t),
        e === VertexBuffer.PositionKind && this._updateBoundingInfo(r, t),
        this.notifyUpdate(e))
    }
    ,
    i.prototype._updateBoundingInfo = function(e, t) {
        if (e && this._updateExtend(t),
        this._resetPointsArrayCache(),
        e)
            for (var r = this._meshes, n = 0, o = r; n < o.length; n++) {
                var a = o[n];
                a.hasBoundingInfo ? a.getBoundingInfo().reConstruct(this._extend.minimum, this._extend.maximum) : a.buildBoundingInfo(this._extend.minimum, this._extend.maximum);
                for (var s = a.subMeshes, l = 0, u = s; l < u.length; l++) {
                    var c = u[l];
                    c.refreshBoundingInfo()
                }
            }
    }
    ,
    i.prototype._bind = function(e, t, r, n) {
        if (!!e) {
            t === void 0 && (t = this._indexBuffer);
            var o = this.getVertexBuffers();
            if (!!o) {
                if (t != this._indexBuffer || !this._vertexArrayObjects && !n) {
                    this._engine.bindBuffers(o, t, e, r);
                    return
                }
                var a = n || this._vertexArrayObjects;
                a[e.key] || (a[e.key] = this._engine.recordVertexArrayObject(o, t, e, r)),
                this._engine.bindVertexArrayObject(a[e.key], t)
            }
        }
    }
    ,
    i.prototype.getTotalVertices = function() {
        return this.isReady() ? this._totalVertices : 0
    }
    ,
    i.prototype.getVerticesData = function(e, t, r) {
        var n = this.getVertexBuffer(e);
        return n ? n.getFloatData(this._totalVertices, r || t && this._meshes.length !== 1) : null
    }
    ,
    i.prototype.isVertexBufferUpdatable = function(e) {
        var t = this._vertexBuffers[e];
        return t ? t.isUpdatable() : !1
    }
    ,
    i.prototype.getVertexBuffer = function(e) {
        return this.isReady() ? this._vertexBuffers[e] : null
    }
    ,
    i.prototype.getVertexBuffers = function() {
        return this.isReady() ? this._vertexBuffers : null
    }
    ,
    i.prototype.isVerticesDataPresent = function(e) {
        return this._vertexBuffers ? this._vertexBuffers[e] !== void 0 : this._delayInfo ? this._delayInfo.indexOf(e) !== -1 : !1
    }
    ,
    i.prototype.getVerticesDataKinds = function() {
        var e = [], t;
        if (!this._vertexBuffers && this._delayInfo)
            for (t in this._delayInfo)
                e.push(t);
        else
            for (t in this._vertexBuffers)
                e.push(t);
        return e
    }
    ,
    i.prototype.updateIndices = function(e, t, r) {
        if (r === void 0 && (r = !1),
        !!this._indexBuffer)
            if (!this._indexBufferIsUpdatable)
                this.setIndices(e, null, !0);
            else {
                var n = e.length !== this._indices.length;
                if (r || (this._indices = e.slice()),
                this._engine.updateDynamicIndexBuffer(this._indexBuffer, e, t),
                n)
                    for (var o = 0, a = this._meshes; o < a.length; o++) {
                        var s = a[o];
                        s._createGlobalSubMesh(!0)
                    }
            }
    }
    ,
    i.prototype.setIndices = function(e, t, r) {
        t === void 0 && (t = null),
        r === void 0 && (r = !1),
        this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer),
        this._indices = e,
        this._indexBufferIsUpdatable = r,
        this._meshes.length !== 0 && this._indices && (this._indexBuffer = this._engine.createIndexBuffer(this._indices, r)),
        t != null && (this._totalVertices = t);
        for (var n = 0, o = this._meshes; n < o.length; n++) {
            var a = o[n];
            a._createGlobalSubMesh(!0),
            a.synchronizeInstances()
        }
        this.notifyUpdate()
    }
    ,
    i.prototype.getTotalIndices = function() {
        return this.isReady() ? this._indices.length : 0
    }
    ,
    i.prototype.getIndices = function(e, t) {
        if (!this.isReady())
            return null;
        var r = this._indices;
        return !t && (!e || this._meshes.length === 1) ? r : Tools.Slice(r)
    }
    ,
    i.prototype.getIndexBuffer = function() {
        return this.isReady() ? this._indexBuffer : null
    }
    ,
    i.prototype._releaseVertexArrayObject = function(e) {
        e === void 0 && (e = null),
        !(!e || !this._vertexArrayObjects) && this._vertexArrayObjects[e.key] && (this._engine.releaseVertexArrayObject(this._vertexArrayObjects[e.key]),
        delete this._vertexArrayObjects[e.key])
    }
    ,
    i.prototype.releaseForMesh = function(e, t) {
        var r = this._meshes
          , n = r.indexOf(e);
        n !== -1 && (r.splice(n, 1),
        this._vertexArrayObjects && e._invalidateInstanceVertexArrayObject(),
        e._geometry = null,
        r.length === 0 && t && this.dispose())
    }
    ,
    i.prototype.applyToMesh = function(e) {
        if (e._geometry !== this) {
            var t = e._geometry;
            t && t.releaseForMesh(e),
            this._vertexArrayObjects && e._invalidateInstanceVertexArrayObject();
            var r = this._meshes;
            e._geometry = this,
            e._internalAbstractMeshDataInfo._positions = null,
            this._scene.pushGeometry(this),
            r.push(e),
            this.isReady() ? this._applyToMesh(e) : this._boundingInfo && e.setBoundingInfo(this._boundingInfo)
        }
    }
    ,
    i.prototype._updateExtend = function(e) {
        e === void 0 && (e = null),
        this.useBoundingInfoFromGeometry && this._boundingInfo ? this._extend = {
            minimum: this._boundingInfo.minimum.clone(),
            maximum: this._boundingInfo.maximum.clone()
        } : (e || (e = this.getVerticesData(VertexBuffer.PositionKind)),
        this._extend = extractMinAndMax(e, 0, this._totalVertices, this.boundingBias, 3))
    }
    ,
    i.prototype._applyToMesh = function(e) {
        var t = this._meshes.length;
        for (var r in this._vertexBuffers)
            t === 1 && this._vertexBuffers[r].create(),
            r === VertexBuffer.PositionKind && (this._extend || this._updateExtend(),
            e.buildBoundingInfo(this._extend.minimum, this._extend.maximum),
            e._createGlobalSubMesh(!1),
            e._updateBoundingInfo());
        t === 1 && this._indices && this._indices.length > 0 && (this._indexBuffer = this._engine.createIndexBuffer(this._indices, this._updatable)),
        e._syncGeometryWithMorphTargetManager(),
        e.synchronizeInstances()
    }
    ,
    i.prototype.notifyUpdate = function(e) {
        this.onGeometryUpdated && this.onGeometryUpdated(this, e),
        this._vertexArrayObjects && this._disposeVertexArrayObjects();
        for (var t = 0, r = this._meshes; t < r.length; t++) {
            var n = r[t];
            n._markSubMeshesAsAttributesDirty()
        }
    }
    ,
    i.prototype.load = function(e, t) {
        if (this.delayLoadState !== 2) {
            if (this.isReady()) {
                t && t();
                return
            }
            this.delayLoadState = 2,
            this._queueLoad(e, t)
        }
    }
    ,
    i.prototype._queueLoad = function(e, t) {
        var r = this;
        !this.delayLoadingFile || (e._addPendingData(this),
        e._loadFile(this.delayLoadingFile, function(n) {
            if (!!r._delayLoadingFunction) {
                r._delayLoadingFunction(JSON.parse(n), r),
                r.delayLoadState = 1,
                r._delayInfo = [],
                e._removePendingData(r);
                for (var o = r._meshes, a = o.length, s = 0; s < a; s++)
                    r._applyToMesh(o[s]);
                t && t()
            }
        }, void 0, !0))
    }
    ,
    i.prototype.toLeftHanded = function() {
        var e = this.getIndices(!1);
        if (e != null && e.length > 0) {
            for (var t = 0; t < e.length; t += 3) {
                var r = e[t + 0];
                e[t + 0] = e[t + 2],
                e[t + 2] = r
            }
            this.setIndices(e)
        }
        var n = this.getVerticesData(VertexBuffer.PositionKind, !1);
        if (n != null && n.length > 0) {
            for (var t = 0; t < n.length; t += 3)
                n[t + 2] = -n[t + 2];
            this.setVerticesData(VertexBuffer.PositionKind, n, !1)
        }
        var o = this.getVerticesData(VertexBuffer.NormalKind, !1);
        if (o != null && o.length > 0) {
            for (var t = 0; t < o.length; t += 3)
                o[t + 2] = -o[t + 2];
            this.setVerticesData(VertexBuffer.NormalKind, o, !1)
        }
    }
    ,
    i.prototype._resetPointsArrayCache = function() {
        this._positions = null
    }
    ,
    i.prototype._generatePointsArray = function() {
        if (this._positions)
            return !0;
        var e = this.getVerticesData(VertexBuffer.PositionKind);
        if (!e || e.length === 0)
            return !1;
        for (var t = this._positionsCache.length * 3, r = this._positionsCache.length; t < e.length; t += 3,
        ++r)
            this._positionsCache[r] = Vector3.FromArray(e, t);
        for (var t = 0, r = 0; t < e.length; t += 3,
        ++r)
            this._positionsCache[r].set(e[0 + t], e[1 + t], e[2 + t]);
        return this._positionsCache.length = e.length / 3,
        this._positions = this._positionsCache,
        !0
    }
    ,
    i.prototype.isDisposed = function() {
        return this._isDisposed
    }
    ,
    i.prototype._disposeVertexArrayObjects = function() {
        if (this._vertexArrayObjects) {
            for (var e in this._vertexArrayObjects)
                this._engine.releaseVertexArrayObject(this._vertexArrayObjects[e]);
            this._vertexArrayObjects = {};
            for (var t = this._meshes, r = t.length, n = 0; n < r; n++)
                t[n]._invalidateInstanceVertexArrayObject()
        }
    }
    ,
    i.prototype.dispose = function() {
        var e = this._meshes, t = e.length, r;
        for (r = 0; r < t; r++)
            this.releaseForMesh(e[r]);
        this._meshes = [],
        this._disposeVertexArrayObjects();
        for (var n in this._vertexBuffers)
            this._vertexBuffers[n].dispose();
        if (this._vertexBuffers = {},
        this._totalVertices = 0,
        this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer),
        this._indexBuffer = null,
        this._indices = [],
        this.delayLoadState = 0,
        this.delayLoadingFile = null,
        this._delayLoadingFunction = null,
        this._delayInfo = [],
        this._boundingInfo = null,
        this._scene.removeGeometry(this),
        this._parentContainer) {
            var o = this._parentContainer.geometries.indexOf(this);
            o > -1 && this._parentContainer.geometries.splice(o, 1),
            this._parentContainer = null
        }
        this._isDisposed = !0
    }
    ,
    i.prototype.copy = function(e) {
        var t = new VertexData;
        t.indices = [];
        var r = this.getIndices();
        if (r)
            for (var n = 0; n < r.length; n++)
                t.indices.push(r[n]);
        var o = !1, a = !1, s;
        for (s in this._vertexBuffers) {
            var l = this.getVerticesData(s);
            if (l && (l instanceof Float32Array ? t.set(new Float32Array(l), s) : t.set(l.slice(0), s),
            !a)) {
                var u = this.getVertexBuffer(s);
                u && (o = u.isUpdatable(),
                a = !o)
            }
        }
        var c = new i(e,this._scene,t,o);
        c.delayLoadState = this.delayLoadState,
        c.delayLoadingFile = this.delayLoadingFile,
        c._delayLoadingFunction = this._delayLoadingFunction;
        for (s in this._delayInfo)
            c._delayInfo = c._delayInfo || [],
            c._delayInfo.push(s);
        return c._boundingInfo = new BoundingInfo(this._extend.minimum,this._extend.maximum),
        c
    }
    ,
    i.prototype.serialize = function() {
        var e = {};
        return e.id = this.id,
        e.uniqueId = this.uniqueId,
        e.updatable = this._updatable,
        Tags && Tags.HasTags(this) && (e.tags = Tags.GetTags(this)),
        e
    }
    ,
    i.prototype.toNumberArray = function(e) {
        return Array.isArray(e) ? e : Array.prototype.slice.call(e)
    }
    ,
    i.prototype.clearCachedData = function() {
        this._indices = [],
        this._resetPointsArrayCache();
        for (var e in this._vertexBuffers)
            !this._vertexBuffers.hasOwnProperty(e) || (this._vertexBuffers[e]._buffer._data = null)
    }
    ,
    i.prototype.serializeVerticeData = function() {
        var e = this.serialize();
        return this.isVerticesDataPresent(VertexBuffer.PositionKind) && (e.positions = this.toNumberArray(this.getVerticesData(VertexBuffer.PositionKind)),
        this.isVertexBufferUpdatable(VertexBuffer.PositionKind) && (e.positions._updatable = !0)),
        this.isVerticesDataPresent(VertexBuffer.NormalKind) && (e.normals = this.toNumberArray(this.getVerticesData(VertexBuffer.NormalKind)),
        this.isVertexBufferUpdatable(VertexBuffer.NormalKind) && (e.normals._updatable = !0)),
        this.isVerticesDataPresent(VertexBuffer.TangentKind) && (e.tangents = this.toNumberArray(this.getVerticesData(VertexBuffer.TangentKind)),
        this.isVertexBufferUpdatable(VertexBuffer.TangentKind) && (e.tangents._updatable = !0)),
        this.isVerticesDataPresent(VertexBuffer.UVKind) && (e.uvs = this.toNumberArray(this.getVerticesData(VertexBuffer.UVKind)),
        this.isVertexBufferUpdatable(VertexBuffer.UVKind) && (e.uvs._updatable = !0)),
        this.isVerticesDataPresent(VertexBuffer.UV2Kind) && (e.uv2s = this.toNumberArray(this.getVerticesData(VertexBuffer.UV2Kind)),
        this.isVertexBufferUpdatable(VertexBuffer.UV2Kind) && (e.uv2s._updatable = !0)),
        this.isVerticesDataPresent(VertexBuffer.UV3Kind) && (e.uv3s = this.toNumberArray(this.getVerticesData(VertexBuffer.UV3Kind)),
        this.isVertexBufferUpdatable(VertexBuffer.UV3Kind) && (e.uv3s._updatable = !0)),
        this.isVerticesDataPresent(VertexBuffer.UV4Kind) && (e.uv4s = this.toNumberArray(this.getVerticesData(VertexBuffer.UV4Kind)),
        this.isVertexBufferUpdatable(VertexBuffer.UV4Kind) && (e.uv4s._updatable = !0)),
        this.isVerticesDataPresent(VertexBuffer.UV5Kind) && (e.uv5s = this.toNumberArray(this.getVerticesData(VertexBuffer.UV5Kind)),
        this.isVertexBufferUpdatable(VertexBuffer.UV5Kind) && (e.uv5s._updatable = !0)),
        this.isVerticesDataPresent(VertexBuffer.UV6Kind) && (e.uv6s = this.toNumberArray(this.getVerticesData(VertexBuffer.UV6Kind)),
        this.isVertexBufferUpdatable(VertexBuffer.UV6Kind) && (e.uv6s._updatable = !0)),
        this.isVerticesDataPresent(VertexBuffer.ColorKind) && (e.colors = this.toNumberArray(this.getVerticesData(VertexBuffer.ColorKind)),
        this.isVertexBufferUpdatable(VertexBuffer.ColorKind) && (e.colors._updatable = !0)),
        this.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind) && (e.matricesIndices = this.toNumberArray(this.getVerticesData(VertexBuffer.MatricesIndicesKind)),
        e.matricesIndices._isExpanded = !0,
        this.isVertexBufferUpdatable(VertexBuffer.MatricesIndicesKind) && (e.matricesIndices._updatable = !0)),
        this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind) && (e.matricesWeights = this.toNumberArray(this.getVerticesData(VertexBuffer.MatricesWeightsKind)),
        this.isVertexBufferUpdatable(VertexBuffer.MatricesWeightsKind) && (e.matricesWeights._updatable = !0)),
        e.indices = this.toNumberArray(this.getIndices()),
        e
    }
    ,
    i.ExtractFromMesh = function(e, t) {
        var r = e._geometry;
        return r ? r.copy(t) : null
    }
    ,
    i.RandomId = function() {
        return Tools.RandomId()
    }
    ,
    i._GetGeometryByLoadedUniqueId = function(e, t) {
        for (var r = 0; r < t.geometries.length; r++)
            if (t.geometries[r]._loadedUniqueId === e)
                return t.geometries[r];
        return null
    }
    ,
    i._ImportGeometry = function(e, t) {
        var r = t.getScene()
          , n = e.geometryUniqueId
          , o = e.geometryId;
        if (n || o) {
            var a = n ? this._GetGeometryByLoadedUniqueId(n, r) : r.getGeometryById(o);
            a && a.applyToMesh(t)
        } else if (e instanceof ArrayBuffer) {
            var s = t._binaryInfo;
            if (s.positionsAttrDesc && s.positionsAttrDesc.count > 0) {
                var l = new Float32Array(e,s.positionsAttrDesc.offset,s.positionsAttrDesc.count);
                t.setVerticesData(VertexBuffer.PositionKind, l, !1)
            }
            if (s.normalsAttrDesc && s.normalsAttrDesc.count > 0) {
                var u = new Float32Array(e,s.normalsAttrDesc.offset,s.normalsAttrDesc.count);
                t.setVerticesData(VertexBuffer.NormalKind, u, !1)
            }
            if (s.tangetsAttrDesc && s.tangetsAttrDesc.count > 0) {
                var c = new Float32Array(e,s.tangetsAttrDesc.offset,s.tangetsAttrDesc.count);
                t.setVerticesData(VertexBuffer.TangentKind, c, !1)
            }
            if (s.uvsAttrDesc && s.uvsAttrDesc.count > 0) {
                var h = new Float32Array(e,s.uvsAttrDesc.offset,s.uvsAttrDesc.count);
                t.setVerticesData(VertexBuffer.UVKind, h, !1)
            }
            if (s.uvs2AttrDesc && s.uvs2AttrDesc.count > 0) {
                var f = new Float32Array(e,s.uvs2AttrDesc.offset,s.uvs2AttrDesc.count);
                t.setVerticesData(VertexBuffer.UV2Kind, f, !1)
            }
            if (s.uvs3AttrDesc && s.uvs3AttrDesc.count > 0) {
                var d = new Float32Array(e,s.uvs3AttrDesc.offset,s.uvs3AttrDesc.count);
                t.setVerticesData(VertexBuffer.UV3Kind, d, !1)
            }
            if (s.uvs4AttrDesc && s.uvs4AttrDesc.count > 0) {
                var _ = new Float32Array(e,s.uvs4AttrDesc.offset,s.uvs4AttrDesc.count);
                t.setVerticesData(VertexBuffer.UV4Kind, _, !1)
            }
            if (s.uvs5AttrDesc && s.uvs5AttrDesc.count > 0) {
                var g = new Float32Array(e,s.uvs5AttrDesc.offset,s.uvs5AttrDesc.count);
                t.setVerticesData(VertexBuffer.UV5Kind, g, !1)
            }
            if (s.uvs6AttrDesc && s.uvs6AttrDesc.count > 0) {
                var m = new Float32Array(e,s.uvs6AttrDesc.offset,s.uvs6AttrDesc.count);
                t.setVerticesData(VertexBuffer.UV6Kind, m, !1)
            }
            if (s.colorsAttrDesc && s.colorsAttrDesc.count > 0) {
                var v = new Float32Array(e,s.colorsAttrDesc.offset,s.colorsAttrDesc.count);
                t.setVerticesData(VertexBuffer.ColorKind, v, !1, s.colorsAttrDesc.stride)
            }
            if (s.matricesIndicesAttrDesc && s.matricesIndicesAttrDesc.count > 0) {
                for (var y = new Int32Array(e,s.matricesIndicesAttrDesc.offset,s.matricesIndicesAttrDesc.count), b = [], T = 0; T < y.length; T++) {
                    var C = y[T];
                    b.push(C & 255),
                    b.push((C & 65280) >> 8),
                    b.push((C & 16711680) >> 16),
                    b.push(C >> 24 & 255)
                }
                t.setVerticesData(VertexBuffer.MatricesIndicesKind, b, !1)
            }
            if (s.matricesIndicesExtraAttrDesc && s.matricesIndicesExtraAttrDesc.count > 0) {
                for (var y = new Int32Array(e,s.matricesIndicesExtraAttrDesc.offset,s.matricesIndicesExtraAttrDesc.count), b = [], T = 0; T < y.length; T++) {
                    var C = y[T];
                    b.push(C & 255),
                    b.push((C & 65280) >> 8),
                    b.push((C & 16711680) >> 16),
                    b.push(C >> 24 & 255)
                }
                t.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, b, !1)
            }
            if (s.matricesWeightsAttrDesc && s.matricesWeightsAttrDesc.count > 0) {
                var A = new Float32Array(e,s.matricesWeightsAttrDesc.offset,s.matricesWeightsAttrDesc.count);
                t.setVerticesData(VertexBuffer.MatricesWeightsKind, A, !1)
            }
            if (s.indicesAttrDesc && s.indicesAttrDesc.count > 0) {
                var S = new Int32Array(e,s.indicesAttrDesc.offset,s.indicesAttrDesc.count);
                t.setIndices(S, null)
            }
            if (s.subMeshesAttrDesc && s.subMeshesAttrDesc.count > 0) {
                var P = new Int32Array(e,s.subMeshesAttrDesc.offset,s.subMeshesAttrDesc.count * 5);
                t.subMeshes = [];
                for (var T = 0; T < s.subMeshesAttrDesc.count; T++) {
                    var R = P[T * 5 + 0]
                      , M = P[T * 5 + 1]
                      , x = P[T * 5 + 2]
                      , I = P[T * 5 + 3]
                      , w = P[T * 5 + 4];
                    SubMesh.AddToMesh(R, M, x, I, w, t)
                }
            }
        } else if (e.positions && e.normals && e.indices) {
            if (t.setVerticesData(VertexBuffer.PositionKind, e.positions, e.positions._updatable),
            t.setVerticesData(VertexBuffer.NormalKind, e.normals, e.normals._updatable),
            e.tangents && t.setVerticesData(VertexBuffer.TangentKind, e.tangents, e.tangents._updatable),
            e.uvs && t.setVerticesData(VertexBuffer.UVKind, e.uvs, e.uvs._updatable),
            e.uvs2 && t.setVerticesData(VertexBuffer.UV2Kind, e.uvs2, e.uvs2._updatable),
            e.uvs3 && t.setVerticesData(VertexBuffer.UV3Kind, e.uvs3, e.uvs3._updatable),
            e.uvs4 && t.setVerticesData(VertexBuffer.UV4Kind, e.uvs4, e.uvs4._updatable),
            e.uvs5 && t.setVerticesData(VertexBuffer.UV5Kind, e.uvs5, e.uvs5._updatable),
            e.uvs6 && t.setVerticesData(VertexBuffer.UV6Kind, e.uvs6, e.uvs6._updatable),
            e.colors && t.setVerticesData(VertexBuffer.ColorKind, Color4.CheckColors4(e.colors, e.positions.length / 3), e.colors._updatable),
            e.matricesIndices)
                if (e.matricesIndices._isExpanded)
                    delete e.matricesIndices._isExpanded,
                    t.setVerticesData(VertexBuffer.MatricesIndicesKind, e.matricesIndices, e.matricesIndices._updatable);
                else {
                    for (var b = [], T = 0; T < e.matricesIndices.length; T++) {
                        var O = e.matricesIndices[T];
                        b.push(O & 255),
                        b.push((O & 65280) >> 8),
                        b.push((O & 16711680) >> 16),
                        b.push(O >> 24 & 255)
                    }
                    t.setVerticesData(VertexBuffer.MatricesIndicesKind, b, e.matricesIndices._updatable)
                }
            if (e.matricesIndicesExtra)
                if (e.matricesIndicesExtra._isExpanded)
                    delete e.matricesIndices._isExpanded,
                    t.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, e.matricesIndicesExtra, e.matricesIndicesExtra._updatable);
                else {
                    for (var b = [], T = 0; T < e.matricesIndicesExtra.length; T++) {
                        var O = e.matricesIndicesExtra[T];
                        b.push(O & 255),
                        b.push((O & 65280) >> 8),
                        b.push((O & 16711680) >> 16),
                        b.push(O >> 24 & 255)
                    }
                    t.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, b, e.matricesIndicesExtra._updatable)
                }
            e.matricesWeights && (i._CleanMatricesWeights(e, t),
            t.setVerticesData(VertexBuffer.MatricesWeightsKind, e.matricesWeights, e.matricesWeights._updatable)),
            e.matricesWeightsExtra && t.setVerticesData(VertexBuffer.MatricesWeightsExtraKind, e.matricesWeightsExtra, e.matricesWeights._updatable),
            t.setIndices(e.indices, null)
        }
        if (e.subMeshes) {
            t.subMeshes = [];
            for (var D = 0; D < e.subMeshes.length; D++) {
                var F = e.subMeshes[D];
                SubMesh.AddToMesh(F.materialIndex, F.verticesStart, F.verticesCount, F.indexStart, F.indexCount, t)
            }
        }
        t._shouldGenerateFlatShading && (t.convertToFlatShadedMesh(),
        t._shouldGenerateFlatShading = !1),
        t.computeWorldMatrix(!0),
        r.onMeshImportedObservable.notifyObservers(t)
    }
    ,
    i._CleanMatricesWeights = function(e, t) {
        var r = .001;
        if (!!SceneLoaderFlags.CleanBoneMatrixWeights) {
            var n = 0;
            if (e.skeletonId > -1) {
                var o = t.getScene().getLastSkeletonById(e.skeletonId);
                if (!o)
                    return;
                n = o.bones.length
            } else
                return;
            for (var a = t.getVerticesData(VertexBuffer.MatricesIndicesKind), s = t.getVerticesData(VertexBuffer.MatricesIndicesExtraKind), l = e.matricesWeights, u = e.matricesWeightsExtra, c = e.numBoneInfluencer, h = l.length, f = 0; f < h; f += 4) {
                for (var d = 0, _ = -1, g = 0; g < 4; g++) {
                    var m = l[f + g];
                    d += m,
                    m < r && _ < 0 && (_ = g)
                }
                if (u)
                    for (var g = 0; g < 4; g++) {
                        var m = u[f + g];
                        d += m,
                        m < r && _ < 0 && (_ = g + 4)
                    }
                if ((_ < 0 || _ > c - 1) && (_ = c - 1),
                d > r) {
                    for (var v = 1 / d, g = 0; g < 4; g++)
                        l[f + g] *= v;
                    if (u)
                        for (var g = 0; g < 4; g++)
                            u[f + g] *= v
                } else
                    _ >= 4 ? (u[f + _ - 4] = 1 - d,
                    s[f + _ - 4] = n) : (l[f + _] = 1 - d,
                    a[f + _] = n)
            }
            t.setVerticesData(VertexBuffer.MatricesIndicesKind, a),
            e.matricesWeightsExtra && t.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, s)
        }
    }
    ,
    i.Parse = function(e, t, r) {
        var n = new i(e.id,t,void 0,e.updatable);
        return n._loadedUniqueId = e.uniqueId,
        Tags && Tags.AddTagsTo(n, e.tags),
        e.delayLoadingFile ? (n.delayLoadState = 4,
        n.delayLoadingFile = r + e.delayLoadingFile,
        n._boundingInfo = new BoundingInfo(Vector3.FromArray(e.boundingBoxMinimum),Vector3.FromArray(e.boundingBoxMaximum)),
        n._delayInfo = [],
        e.hasUVs && n._delayInfo.push(VertexBuffer.UVKind),
        e.hasUVs2 && n._delayInfo.push(VertexBuffer.UV2Kind),
        e.hasUVs3 && n._delayInfo.push(VertexBuffer.UV3Kind),
        e.hasUVs4 && n._delayInfo.push(VertexBuffer.UV4Kind),
        e.hasUVs5 && n._delayInfo.push(VertexBuffer.UV5Kind),
        e.hasUVs6 && n._delayInfo.push(VertexBuffer.UV6Kind),
        e.hasColors && n._delayInfo.push(VertexBuffer.ColorKind),
        e.hasMatricesIndices && n._delayInfo.push(VertexBuffer.MatricesIndicesKind),
        e.hasMatricesWeights && n._delayInfo.push(VertexBuffer.MatricesWeightsKind),
        n._delayLoadingFunction = VertexData.ImportVertexData) : VertexData.ImportVertexData(e, n),
        t.pushGeometry(n, !0),
        n
    }
    ,
    i
}()
  , TransformNode = function(i) {
    __extends(e, i);
    function e(t, r, n) {
        r === void 0 && (r = null),
        n === void 0 && (n = !0);
        var o = i.call(this, t, r) || this;
        return o._forward = new Vector3(0,0,1),
        o._forwardInverted = new Vector3(0,0,-1),
        o._up = new Vector3(0,1,0),
        o._right = new Vector3(1,0,0),
        o._rightInverted = new Vector3(-1,0,0),
        o._position = Vector3.Zero(),
        o._rotation = Vector3.Zero(),
        o._rotationQuaternion = null,
        o._scaling = Vector3.One(),
        o._transformToBoneReferal = null,
        o._isAbsoluteSynced = !1,
        o._billboardMode = e.BILLBOARDMODE_NONE,
        o._preserveParentRotationForBillboard = !1,
        o.scalingDeterminant = 1,
        o._infiniteDistance = !1,
        o.ignoreNonUniformScaling = !1,
        o.reIntegrateRotationIntoRotationQuaternion = !1,
        o._poseMatrix = null,
        o._localMatrix = Matrix.Zero(),
        o._usePivotMatrix = !1,
        o._absolutePosition = Vector3.Zero(),
        o._absoluteScaling = Vector3.Zero(),
        o._absoluteRotationQuaternion = Quaternion.Identity(),
        o._pivotMatrix = Matrix.Identity(),
        o._postMultiplyPivotMatrix = !1,
        o._isWorldMatrixFrozen = !1,
        o._indexInSceneTransformNodesArray = -1,
        o.onAfterWorldMatrixUpdateObservable = new Observable,
        o._nonUniformScaling = !1,
        n && o.getScene().addTransformNode(o),
        o
    }
    return Object.defineProperty(e.prototype, "billboardMode", {
        get: function() {
            return this._billboardMode
        },
        set: function(t) {
            this._billboardMode !== t && (this._billboardMode = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "preserveParentRotationForBillboard", {
        get: function() {
            return this._preserveParentRotationForBillboard
        },
        set: function(t) {
            t !== this._preserveParentRotationForBillboard && (this._preserveParentRotationForBillboard = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "infiniteDistance", {
        get: function() {
            return this._infiniteDistance
        },
        set: function(t) {
            this._infiniteDistance !== t && (this._infiniteDistance = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getClassName = function() {
        return "TransformNode"
    }
    ,
    Object.defineProperty(e.prototype, "position", {
        get: function() {
            return this._position
        },
        set: function(t) {
            this._position = t,
            this._isDirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.isUsingPivotMatrix = function() {
        return this._usePivotMatrix
    }
    ,
    Object.defineProperty(e.prototype, "rotation", {
        get: function() {
            return this._rotation
        },
        set: function(t) {
            this._rotation = t,
            this._rotationQuaternion = null,
            this._isDirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "scaling", {
        get: function() {
            return this._scaling
        },
        set: function(t) {
            this._scaling = t,
            this._isDirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "rotationQuaternion", {
        get: function() {
            return this._rotationQuaternion
        },
        set: function(t) {
            this._rotationQuaternion = t,
            t && this._rotation.setAll(0),
            this._isDirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "forward", {
        get: function() {
            return Vector3.Normalize(Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "up", {
        get: function() {
            return Vector3.Normalize(Vector3.TransformNormal(this._up, this.getWorldMatrix()))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "right", {
        get: function() {
            return Vector3.Normalize(Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()))
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.updatePoseMatrix = function(t) {
        return this._poseMatrix ? (this._poseMatrix.copyFrom(t),
        this) : (this._poseMatrix = t.clone(),
        this)
    }
    ,
    e.prototype.getPoseMatrix = function() {
        return this._poseMatrix || (this._poseMatrix = Matrix.Identity()),
        this._poseMatrix
    }
    ,
    e.prototype._isSynchronized = function() {
        var t = this._cache;
        return !(this.billboardMode !== t.billboardMode || this.billboardMode !== e.BILLBOARDMODE_NONE || t.pivotMatrixUpdated || this.infiniteDistance || this.position._isDirty || this.scaling._isDirty || this._rotationQuaternion && this._rotationQuaternion._isDirty || this.rotation._isDirty)
    }
    ,
    e.prototype._initCache = function() {
        i.prototype._initCache.call(this);
        var t = this._cache;
        t.localMatrixUpdated = !1,
        t.billboardMode = -1,
        t.infiniteDistance = !1
    }
    ,
    Object.defineProperty(e.prototype, "absolutePosition", {
        get: function() {
            return this.getAbsolutePosition()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "absoluteScaling", {
        get: function() {
            return this._syncAbsoluteScalingAndRotation(),
            this._absoluteScaling
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "absoluteRotationQuaternion", {
        get: function() {
            return this._syncAbsoluteScalingAndRotation(),
            this._absoluteRotationQuaternion
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.setPreTransformMatrix = function(t) {
        return this.setPivotMatrix(t, !1)
    }
    ,
    e.prototype.setPivotMatrix = function(t, r) {
        return r === void 0 && (r = !0),
        this._pivotMatrix.copyFrom(t),
        this._usePivotMatrix = !this._pivotMatrix.isIdentity(),
        this._cache.pivotMatrixUpdated = !0,
        this._postMultiplyPivotMatrix = r,
        this._postMultiplyPivotMatrix && (this._pivotMatrixInverse ? this._pivotMatrix.invertToRef(this._pivotMatrixInverse) : this._pivotMatrixInverse = Matrix.Invert(this._pivotMatrix)),
        this
    }
    ,
    e.prototype.getPivotMatrix = function() {
        return this._pivotMatrix
    }
    ,
    e.prototype.instantiateHierarchy = function(t, r, n) {
        t === void 0 && (t = null);
        var o = this.clone("Clone of " + (this.name || this.id), t || this.parent, !0);
        o && n && n(this, o);
        for (var a = 0, s = this.getChildTransformNodes(!0); a < s.length; a++) {
            var l = s[a];
            l.instantiateHierarchy(o, r, n)
        }
        return o
    }
    ,
    e.prototype.freezeWorldMatrix = function(t, r) {
        return t === void 0 && (t = null),
        r === void 0 && (r = !1),
        t ? r ? (this._rotation.setAll(0),
        this._rotationQuaternion = this._rotationQuaternion || Quaternion.Identity(),
        t.decompose(this._scaling, this._rotationQuaternion, this._position),
        this.computeWorldMatrix(!0)) : (this._worldMatrix = t,
        this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]),
        this._afterComputeWorldMatrix()) : (this._isWorldMatrixFrozen = !1,
        this.computeWorldMatrix(!0)),
        this._isDirty = !1,
        this._isWorldMatrixFrozen = !0,
        this
    }
    ,
    e.prototype.unfreezeWorldMatrix = function() {
        return this._isWorldMatrixFrozen = !1,
        this.computeWorldMatrix(!0),
        this
    }
    ,
    Object.defineProperty(e.prototype, "isWorldMatrixFrozen", {
        get: function() {
            return this._isWorldMatrixFrozen
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getAbsolutePosition = function() {
        return this.computeWorldMatrix(),
        this._absolutePosition
    }
    ,
    e.prototype.setAbsolutePosition = function(t) {
        if (!t)
            return this;
        var r, n, o;
        if (t.x === void 0) {
            if (arguments.length < 3)
                return this;
            r = arguments[0],
            n = arguments[1],
            o = arguments[2]
        } else
            r = t.x,
            n = t.y,
            o = t.z;
        if (this.parent) {
            var a = TmpVectors.Matrix[0];
            this.parent.getWorldMatrix().invertToRef(a),
            Vector3.TransformCoordinatesFromFloatsToRef(r, n, o, a, this.position)
        } else
            this.position.x = r,
            this.position.y = n,
            this.position.z = o;
        return this._absolutePosition.copyFrom(t),
        this
    }
    ,
    e.prototype.setPositionWithLocalVector = function(t) {
        return this.computeWorldMatrix(),
        this.position = Vector3.TransformNormal(t, this._localMatrix),
        this
    }
    ,
    e.prototype.getPositionExpressedInLocalSpace = function() {
        this.computeWorldMatrix();
        var t = TmpVectors.Matrix[0];
        return this._localMatrix.invertToRef(t),
        Vector3.TransformNormal(this.position, t)
    }
    ,
    e.prototype.locallyTranslate = function(t) {
        return this.computeWorldMatrix(!0),
        this.position = Vector3.TransformCoordinates(t, this._localMatrix),
        this
    }
    ,
    e.prototype.lookAt = function(t, r, n, o, a) {
        r === void 0 && (r = 0),
        n === void 0 && (n = 0),
        o === void 0 && (o = 0),
        a === void 0 && (a = Space.LOCAL);
        var s = e._lookAtVectorCache
          , l = a === Space.LOCAL ? this.position : this.getAbsolutePosition();
        if (t.subtractToRef(l, s),
        this.setDirection(s, r, n, o),
        a === Space.WORLD && this.parent)
            if (this.rotationQuaternion) {
                var u = TmpVectors.Matrix[0];
                this.rotationQuaternion.toRotationMatrix(u);
                var c = TmpVectors.Matrix[1];
                this.parent.getWorldMatrix().getRotationMatrixToRef(c),
                c.invert(),
                u.multiplyToRef(c, u),
                this.rotationQuaternion.fromRotationMatrix(u)
            } else {
                var h = TmpVectors.Quaternion[0];
                Quaternion.FromEulerVectorToRef(this.rotation, h);
                var u = TmpVectors.Matrix[0];
                h.toRotationMatrix(u);
                var c = TmpVectors.Matrix[1];
                this.parent.getWorldMatrix().getRotationMatrixToRef(c),
                c.invert(),
                u.multiplyToRef(c, u),
                h.fromRotationMatrix(u),
                h.toEulerAnglesToRef(this.rotation)
            }
        return this
    }
    ,
    e.prototype.getDirection = function(t) {
        var r = Vector3.Zero();
        return this.getDirectionToRef(t, r),
        r
    }
    ,
    e.prototype.getDirectionToRef = function(t, r) {
        return Vector3.TransformNormalToRef(t, this.getWorldMatrix(), r),
        this
    }
    ,
    e.prototype.setDirection = function(t, r, n, o) {
        r === void 0 && (r = 0),
        n === void 0 && (n = 0),
        o === void 0 && (o = 0);
        var a = -Math.atan2(t.z, t.x) + Math.PI / 2
          , s = Math.sqrt(t.x * t.x + t.z * t.z)
          , l = -Math.atan2(t.y, s);
        return this.rotationQuaternion ? Quaternion.RotationYawPitchRollToRef(a + r, l + n, o, this.rotationQuaternion) : (this.rotation.x = l + n,
        this.rotation.y = a + r,
        this.rotation.z = o),
        this
    }
    ,
    e.prototype.setPivotPoint = function(t, r) {
        r === void 0 && (r = Space.LOCAL),
        this.getScene().getRenderId() == 0 && this.computeWorldMatrix(!0);
        var n = this.getWorldMatrix();
        if (r == Space.WORLD) {
            var o = TmpVectors.Matrix[0];
            n.invertToRef(o),
            t = Vector3.TransformCoordinates(t, o)
        }
        return this.setPivotMatrix(Matrix.Translation(-t.x, -t.y, -t.z), !0)
    }
    ,
    e.prototype.getPivotPoint = function() {
        var t = Vector3.Zero();
        return this.getPivotPointToRef(t),
        t
    }
    ,
    e.prototype.getPivotPointToRef = function(t) {
        return t.x = -this._pivotMatrix.m[12],
        t.y = -this._pivotMatrix.m[13],
        t.z = -this._pivotMatrix.m[14],
        this
    }
    ,
    e.prototype.getAbsolutePivotPoint = function() {
        var t = Vector3.Zero();
        return this.getAbsolutePivotPointToRef(t),
        t
    }
    ,
    e.prototype.getAbsolutePivotPointToRef = function(t) {
        return this.getPivotPointToRef(t),
        Vector3.TransformCoordinatesToRef(t, this.getWorldMatrix(), t),
        this
    }
    ,
    e.prototype.markAsDirty = function(t) {
        if (this._children)
            for (var r = 0, n = this._children; r < n.length; r++) {
                var o = n[r];
                o.markAsDirty(t)
            }
        return i.prototype.markAsDirty.call(this, t)
    }
    ,
    e.prototype.setParent = function(t, r) {
        if (r === void 0 && (r = !1),
        !t && !this.parent)
            return this;
        var n = TmpVectors.Quaternion[0]
          , o = TmpVectors.Vector3[0]
          , a = TmpVectors.Vector3[1]
          , s = TmpVectors.Matrix[1];
        Matrix.IdentityToRef(s);
        var l = TmpVectors.Matrix[0];
        this.computeWorldMatrix(!0);
        var u = this.rotationQuaternion;
        return u || (u = e._TmpRotation,
        Quaternion.RotationYawPitchRollToRef(this._rotation.y, this._rotation.x, this._rotation.z, u)),
        Matrix.ComposeToRef(this.scaling, u, this.position, l),
        this.parent && l.multiplyToRef(this.parent.computeWorldMatrix(!0), l),
        t && (t.computeWorldMatrix(!0).invertToRef(s),
        l.multiplyToRef(s, l)),
        l.decompose(a, n, o, r ? this : void 0),
        this.rotationQuaternion ? this.rotationQuaternion.copyFrom(n) : n.toEulerAnglesToRef(this.rotation),
        this.scaling.copyFrom(a),
        this.position.copyFrom(o),
        this.parent = t,
        this
    }
    ,
    Object.defineProperty(e.prototype, "nonUniformScaling", {
        get: function() {
            return this._nonUniformScaling
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._updateNonUniformScalingState = function(t) {
        return this._nonUniformScaling === t ? !1 : (this._nonUniformScaling = t,
        !0)
    }
    ,
    e.prototype.attachToBone = function(t, r) {
        return this._currentParentWhenAttachingToBone = this.parent,
        this._transformToBoneReferal = r,
        this.parent = t,
        t.getSkeleton().prepare(),
        t.getWorldMatrix().determinant() < 0 && (this.scalingDeterminant *= -1),
        this
    }
    ,
    e.prototype.detachFromBone = function(t) {
        return t === void 0 && (t = !1),
        this.parent ? (this.parent.getWorldMatrix().determinant() < 0 && (this.scalingDeterminant *= -1),
        this._transformToBoneReferal = null,
        t ? this.parent = this._currentParentWhenAttachingToBone : this.parent = null,
        this) : (t && (this.parent = this._currentParentWhenAttachingToBone),
        this)
    }
    ,
    e.prototype.rotate = function(t, r, n) {
        t.normalize(),
        this.rotationQuaternion || (this.rotationQuaternion = this.rotation.toQuaternion(),
        this.rotation.setAll(0));
        var o;
        if (!n || n === Space.LOCAL)
            o = Quaternion.RotationAxisToRef(t, r, e._rotationAxisCache),
            this.rotationQuaternion.multiplyToRef(o, this.rotationQuaternion);
        else {
            if (this.parent) {
                var a = TmpVectors.Matrix[0];
                this.parent.getWorldMatrix().invertToRef(a),
                t = Vector3.TransformNormal(t, a)
            }
            o = Quaternion.RotationAxisToRef(t, r, e._rotationAxisCache),
            o.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion)
        }
        return this
    }
    ,
    e.prototype.rotateAround = function(t, r, n) {
        r.normalize(),
        this.rotationQuaternion || (this.rotationQuaternion = Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z),
        this.rotation.setAll(0));
        var o = TmpVectors.Vector3[0]
          , a = TmpVectors.Vector3[1]
          , s = TmpVectors.Vector3[2]
          , l = TmpVectors.Quaternion[0]
          , u = TmpVectors.Matrix[0]
          , c = TmpVectors.Matrix[1]
          , h = TmpVectors.Matrix[2]
          , f = TmpVectors.Matrix[3];
        return t.subtractToRef(this.position, o),
        Matrix.TranslationToRef(o.x, o.y, o.z, u),
        Matrix.TranslationToRef(-o.x, -o.y, -o.z, c),
        Matrix.RotationAxisToRef(r, n, h),
        c.multiplyToRef(h, f),
        f.multiplyToRef(u, f),
        f.decompose(a, l, s),
        this.position.addInPlace(s),
        l.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion),
        this
    }
    ,
    e.prototype.translate = function(t, r, n) {
        var o = t.scale(r);
        if (!n || n === Space.LOCAL) {
            var a = this.getPositionExpressedInLocalSpace().add(o);
            this.setPositionWithLocalVector(a)
        } else
            this.setAbsolutePosition(this.getAbsolutePosition().add(o));
        return this
    }
    ,
    e.prototype.addRotation = function(t, r, n) {
        var o;
        this.rotationQuaternion ? o = this.rotationQuaternion : (o = TmpVectors.Quaternion[1],
        Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, o));
        var a = TmpVectors.Quaternion[0];
        return Quaternion.RotationYawPitchRollToRef(r, t, n, a),
        o.multiplyInPlace(a),
        this.rotationQuaternion || o.toEulerAnglesToRef(this.rotation),
        this
    }
    ,
    e.prototype._getEffectiveParent = function() {
        return this.parent
    }
    ,
    e.prototype.computeWorldMatrix = function(t) {
        if (this._isWorldMatrixFrozen && !this._isDirty)
            return this._worldMatrix;
        var r = this.getScene().getRenderId();
        if (!this._isDirty && !t && this.isSynchronized())
            return this._currentRenderId = r,
            this._worldMatrix;
        var n = this.getScene().activeCamera
          , o = (this._billboardMode & e.BILLBOARDMODE_USE_POSITION) !== 0
          , a = this._billboardMode !== e.BILLBOARDMODE_NONE && !this.preserveParentRotationForBillboard;
        a && n && o && (this.lookAt(n.position),
        (this.billboardMode & e.BILLBOARDMODE_X) !== e.BILLBOARDMODE_X && (this.rotation.x = 0),
        (this.billboardMode & e.BILLBOARDMODE_Y) !== e.BILLBOARDMODE_Y && (this.rotation.y = 0),
        (this.billboardMode & e.BILLBOARDMODE_Z) !== e.BILLBOARDMODE_Z && (this.rotation.z = 0)),
        this._updateCache();
        var s = this._cache;
        s.pivotMatrixUpdated = !1,
        s.billboardMode = this.billboardMode,
        s.infiniteDistance = this.infiniteDistance,
        this._currentRenderId = r,
        this._childUpdateId += 1,
        this._isDirty = !1,
        this._position._isDirty = !1,
        this._rotation._isDirty = !1,
        this._scaling._isDirty = !1;
        var l = this._getEffectiveParent()
          , u = e._TmpScaling
          , c = this._position;
        if (this._infiniteDistance && !this.parent && n) {
            var h = n.getWorldMatrix()
              , f = new Vector3(h.m[12],h.m[13],h.m[14]);
            c = e._TmpTranslation,
            c.copyFromFloats(this._position.x + f.x, this._position.y + f.y, this._position.z + f.z)
        }
        u.copyFromFloats(this._scaling.x * this.scalingDeterminant, this._scaling.y * this.scalingDeterminant, this._scaling.z * this.scalingDeterminant);
        var d;
        if (this._rotationQuaternion) {
            if (this._rotationQuaternion._isDirty = !1,
            d = this._rotationQuaternion,
            this.reIntegrateRotationIntoRotationQuaternion) {
                var _ = this.rotation.lengthSquared();
                _ && (this._rotationQuaternion.multiplyInPlace(Quaternion.RotationYawPitchRoll(this._rotation.y, this._rotation.x, this._rotation.z)),
                this._rotation.copyFromFloats(0, 0, 0))
            }
        } else
            d = e._TmpRotation,
            Quaternion.RotationYawPitchRollToRef(this._rotation.y, this._rotation.x, this._rotation.z, d);
        if (this._usePivotMatrix) {
            var g = TmpVectors.Matrix[1];
            Matrix.ScalingToRef(u.x, u.y, u.z, g);
            var m = TmpVectors.Matrix[0];
            d.toRotationMatrix(m),
            this._pivotMatrix.multiplyToRef(g, TmpVectors.Matrix[4]),
            TmpVectors.Matrix[4].multiplyToRef(m, this._localMatrix),
            this._postMultiplyPivotMatrix && this._localMatrix.multiplyToRef(this._pivotMatrixInverse, this._localMatrix),
            this._localMatrix.addTranslationFromFloats(c.x, c.y, c.z)
        } else
            Matrix.ComposeToRef(u, d, c, this._localMatrix);
        if (l && l.getWorldMatrix) {
            if (t && l.computeWorldMatrix(t),
            a) {
                this._transformToBoneReferal ? l.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), TmpVectors.Matrix[7]) : TmpVectors.Matrix[7].copyFrom(l.getWorldMatrix());
                var v = TmpVectors.Vector3[5]
                  , y = TmpVectors.Vector3[6];
                TmpVectors.Matrix[7].decompose(y, void 0, v),
                Matrix.ScalingToRef(y.x, y.y, y.z, TmpVectors.Matrix[7]),
                TmpVectors.Matrix[7].setTranslation(v),
                this._localMatrix.multiplyToRef(TmpVectors.Matrix[7], this._worldMatrix)
            } else
                this._transformToBoneReferal ? (this._localMatrix.multiplyToRef(l.getWorldMatrix(), TmpVectors.Matrix[6]),
                TmpVectors.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix)) : this._localMatrix.multiplyToRef(l.getWorldMatrix(), this._worldMatrix);
            this._markSyncedWithParent()
        } else
            this._worldMatrix.copyFrom(this._localMatrix);
        if (a && n && this.billboardMode && !o) {
            var b = TmpVectors.Vector3[0];
            if (this._worldMatrix.getTranslationToRef(b),
            TmpVectors.Matrix[1].copyFrom(n.getViewMatrix()),
            TmpVectors.Matrix[1].setTranslationFromFloats(0, 0, 0),
            TmpVectors.Matrix[1].invertToRef(TmpVectors.Matrix[0]),
            (this.billboardMode & e.BILLBOARDMODE_ALL) !== e.BILLBOARDMODE_ALL) {
                TmpVectors.Matrix[0].decompose(void 0, TmpVectors.Quaternion[0], void 0);
                var T = TmpVectors.Vector3[1];
                TmpVectors.Quaternion[0].toEulerAnglesToRef(T),
                (this.billboardMode & e.BILLBOARDMODE_X) !== e.BILLBOARDMODE_X && (T.x = 0),
                (this.billboardMode & e.BILLBOARDMODE_Y) !== e.BILLBOARDMODE_Y && (T.y = 0),
                (this.billboardMode & e.BILLBOARDMODE_Z) !== e.BILLBOARDMODE_Z && (T.z = 0),
                Matrix.RotationYawPitchRollToRef(T.y, T.x, T.z, TmpVectors.Matrix[0])
            }
            this._worldMatrix.setTranslationFromFloats(0, 0, 0),
            this._worldMatrix.multiplyToRef(TmpVectors.Matrix[0], this._worldMatrix),
            this._worldMatrix.setTranslation(TmpVectors.Vector3[0])
        }
        return this.ignoreNonUniformScaling ? this._updateNonUniformScalingState(!1) : this._scaling.isNonUniformWithinEpsilon(1e-6) ? this._updateNonUniformScalingState(!0) : l && l._nonUniformScaling ? this._updateNonUniformScalingState(l._nonUniformScaling) : this._updateNonUniformScalingState(!1),
        this._afterComputeWorldMatrix(),
        this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]),
        this._isAbsoluteSynced = !1,
        this.onAfterWorldMatrixUpdateObservable.notifyObservers(this),
        this._poseMatrix || (this._poseMatrix = Matrix.Invert(this._worldMatrix)),
        this._worldMatrixDeterminantIsDirty = !0,
        this._worldMatrix
    }
    ,
    e.prototype.resetLocalMatrix = function(t) {
        if (t === void 0 && (t = !0),
        this.computeWorldMatrix(),
        t)
            for (var r = this.getChildren(), n = 0; n < r.length; ++n) {
                var o = r[n];
                if (o) {
                    o.computeWorldMatrix();
                    var a = TmpVectors.Matrix[0];
                    o._localMatrix.multiplyToRef(this._localMatrix, a);
                    var s = TmpVectors.Quaternion[0];
                    a.decompose(o.scaling, s, o.position),
                    o.rotationQuaternion ? o.rotationQuaternion.copyFrom(s) : s.toEulerAnglesToRef(o.rotation)
                }
            }
        this.scaling.copyFromFloats(1, 1, 1),
        this.position.copyFromFloats(0, 0, 0),
        this.rotation.copyFromFloats(0, 0, 0),
        this.rotationQuaternion && (this.rotationQuaternion = Quaternion.Identity()),
        this._worldMatrix = Matrix.Identity()
    }
    ,
    e.prototype._afterComputeWorldMatrix = function() {}
    ,
    e.prototype.registerAfterWorldMatrixUpdate = function(t) {
        return this.onAfterWorldMatrixUpdateObservable.add(t),
        this
    }
    ,
    e.prototype.unregisterAfterWorldMatrixUpdate = function(t) {
        return this.onAfterWorldMatrixUpdateObservable.removeCallback(t),
        this
    }
    ,
    e.prototype.getPositionInCameraSpace = function(t) {
        return t === void 0 && (t = null),
        t || (t = this.getScene().activeCamera),
        Vector3.TransformCoordinates(this.getAbsolutePosition(), t.getViewMatrix())
    }
    ,
    e.prototype.getDistanceToCamera = function(t) {
        return t === void 0 && (t = null),
        t || (t = this.getScene().activeCamera),
        this.getAbsolutePosition().subtract(t.globalPosition).length()
    }
    ,
    e.prototype.clone = function(t, r, n) {
        var o = this
          , a = SerializationHelper.Clone(function() {
            return new e(t,o.getScene())
        }, this);
        if (a.name = t,
        a.id = t,
        r && (a.parent = r),
        !n)
            for (var s = this.getDescendants(!0), l = 0; l < s.length; l++) {
                var u = s[l];
                u.clone && u.clone(t + "." + u.name, a)
            }
        return a
    }
    ,
    e.prototype.serialize = function(t) {
        var r = SerializationHelper.Serialize(this, t);
        return r.type = this.getClassName(),
        r.uniqueId = this.uniqueId,
        this.parent && (r.parentId = this.parent.uniqueId),
        r.localMatrix = this.getPivotMatrix().asArray(),
        r.isEnabled = this.isEnabled(),
        this.parent && (r.parentId = this.parent.uniqueId),
        r
    }
    ,
    e.Parse = function(t, r, n) {
        var o = SerializationHelper.Parse(function() {
            return new e(t.name,r)
        }, t, r, n);
        return t.localMatrix ? o.setPreTransformMatrix(Matrix.FromArray(t.localMatrix)) : t.pivotMatrix && o.setPivotMatrix(Matrix.FromArray(t.pivotMatrix)),
        o.setEnabled(t.isEnabled),
        t.parentId && (o._waitingParentId = t.parentId),
        o
    }
    ,
    e.prototype.getChildTransformNodes = function(t, r) {
        var n = [];
        return this._getDescendants(n, t, function(o) {
            return (!r || r(o)) && o instanceof e
        }),
        n
    }
    ,
    e.prototype.dispose = function(t, r) {
        if (r === void 0 && (r = !1),
        this.getScene().stopAnimation(this),
        this.getScene().removeTransformNode(this),
        this._parentContainer) {
            var n = this._parentContainer.transformNodes.indexOf(this);
            n > -1 && this._parentContainer.transformNodes.splice(n, 1),
            this._parentContainer = null
        }
        if (this.onAfterWorldMatrixUpdateObservable.clear(),
        t)
            for (var o = this.getChildTransformNodes(!0), a = 0, s = o; a < s.length; a++) {
                var l = s[a];
                l.parent = null,
                l.computeWorldMatrix(!0)
            }
        i.prototype.dispose.call(this, t, r)
    }
    ,
    e.prototype.normalizeToUnitCube = function(t, r, n) {
        t === void 0 && (t = !0),
        r === void 0 && (r = !1);
        var o = null
          , a = null;
        r && (this.rotationQuaternion ? (a = this.rotationQuaternion.clone(),
        this.rotationQuaternion.copyFromFloats(0, 0, 0, 1)) : this.rotation && (o = this.rotation.clone(),
        this.rotation.copyFromFloats(0, 0, 0)));
        var s = this.getHierarchyBoundingVectors(t, n)
          , l = s.max.subtract(s.min)
          , u = Math.max(l.x, l.y, l.z);
        if (u === 0)
            return this;
        var c = 1 / u;
        return this.scaling.scaleInPlace(c),
        r && (this.rotationQuaternion && a ? this.rotationQuaternion.copyFrom(a) : this.rotation && o && this.rotation.copyFrom(o)),
        this
    }
    ,
    e.prototype._syncAbsoluteScalingAndRotation = function() {
        this._isAbsoluteSynced || (this._worldMatrix.decompose(this._absoluteScaling, this._absoluteRotationQuaternion),
        this._isAbsoluteSynced = !0)
    }
    ,
    e.BILLBOARDMODE_NONE = 0,
    e.BILLBOARDMODE_X = 1,
    e.BILLBOARDMODE_Y = 2,
    e.BILLBOARDMODE_Z = 4,
    e.BILLBOARDMODE_ALL = 7,
    e.BILLBOARDMODE_USE_POSITION = 128,
    e._TmpRotation = Quaternion.Zero(),
    e._TmpScaling = Vector3.Zero(),
    e._TmpTranslation = Vector3.Zero(),
    e._lookAtVectorCache = new Vector3(0,0,0),
    e._rotationAxisCache = new Quaternion,
    __decorate([serializeAsVector3("position")], e.prototype, "_position", void 0),
    __decorate([serializeAsVector3("rotation")], e.prototype, "_rotation", void 0),
    __decorate([serializeAsQuaternion("rotationQuaternion")], e.prototype, "_rotationQuaternion", void 0),
    __decorate([serializeAsVector3("scaling")], e.prototype, "_scaling", void 0),
    __decorate([serialize("billboardMode")], e.prototype, "_billboardMode", void 0),
    __decorate([serialize()], e.prototype, "scalingDeterminant", void 0),
    __decorate([serialize("infiniteDistance")], e.prototype, "_infiniteDistance", void 0),
    __decorate([serialize()], e.prototype, "ignoreNonUniformScaling", void 0),
    __decorate([serialize()], e.prototype, "reIntegrateRotationIntoRotationQuaternion", void 0),
    e
}(Node$2)
  , _MeshCollisionData = function() {
    function i() {
        this._checkCollisions = !1,
        this._collisionMask = -1,
        this._collisionGroup = -1,
        this._surroundingMeshes = null,
        this._collider = null,
        this._oldPositionForCollisions = new Vector3(0,0,0),
        this._diffPositionForCollisions = new Vector3(0,0,0),
        this._collisionResponse = !0
    }
    return i
}()
  , _FacetDataStorage = function() {
    function i() {
        this.facetNb = 0,
        this.partitioningSubdivisions = 10,
        this.partitioningBBoxRatio = 1.01,
        this.facetDataEnabled = !1,
        this.facetParameters = {},
        this.bbSize = Vector3.Zero(),
        this.subDiv = {
            max: 1,
            X: 1,
            Y: 1,
            Z: 1
        },
        this.facetDepthSort = !1,
        this.facetDepthSortEnabled = !1
    }
    return i
}()
  , _InternalAbstractMeshDataInfo = function() {
    function i() {
        this._hasVertexAlpha = !1,
        this._useVertexColors = !0,
        this._numBoneInfluencers = 4,
        this._applyFog = !0,
        this._receiveShadows = !1,
        this._facetData = new _FacetDataStorage,
        this._visibility = 1,
        this._skeleton = null,
        this._layerMask = 268435455,
        this._computeBonesUsingShaders = !0,
        this._isActive = !1,
        this._onlyForInstances = !1,
        this._isActiveIntermediate = !1,
        this._onlyForInstancesIntermediate = !1,
        this._actAsRegularMesh = !1,
        this._currentLOD = null,
        this._currentLODIsUpToDate = !1,
        this._collisionRetryCount = 3,
        this._morphTargetManager = null,
        this._renderingGroupId = 0,
        this._bakedVertexAnimationManager = null,
        this._material = null,
        this._positions = null,
        this._meshCollisionData = new _MeshCollisionData
    }
    return i
}()
  , AbstractMesh = function(i) {
    __extends(e, i);
    function e(t, r) {
        r === void 0 && (r = null);
        var n = i.call(this, t, r, !1) || this;
        return n._internalAbstractMeshDataInfo = new _InternalAbstractMeshDataInfo,
        n.cullingStrategy = e.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,
        n.onCollideObservable = new Observable,
        n.onCollisionPositionChangeObservable = new Observable,
        n.onMaterialChangedObservable = new Observable,
        n.definedFacingForward = !0,
        n._occlusionQuery = null,
        n._renderingGroup = null,
        n.alphaIndex = Number.MAX_VALUE,
        n.isVisible = !0,
        n.isPickable = !0,
        n.isNearPickable = !1,
        n.isNearGrabbable = !1,
        n.showSubMeshesBoundingBox = !1,
        n.isBlocker = !1,
        n.enablePointerMoveEvents = !1,
        n.outlineColor = Color3.Red(),
        n.outlineWidth = .02,
        n.overlayColor = Color3.Red(),
        n.overlayAlpha = .5,
        n.useOctreeForRenderingSelection = !0,
        n.useOctreeForPicking = !0,
        n.useOctreeForCollisions = !0,
        n.alwaysSelectAsActiveMesh = !1,
        n.doNotSyncBoundingInfo = !1,
        n.actionManager = null,
        n.ellipsoid = new Vector3(.5,1,.5),
        n.ellipsoidOffset = new Vector3(0,0,0),
        n.edgesWidth = 1,
        n.edgesColor = new Color4(1,0,0,1),
        n._edgesRenderer = null,
        n._masterMesh = null,
        n._boundingInfo = null,
        n._boundingInfoIsDirty = !0,
        n._renderId = 0,
        n._intersectionsInProgress = new Array,
        n._unIndexed = !1,
        n._lightSources = new Array,
        n._waitingData = {
            lods: null,
            actions: null,
            freezeWorldMatrix: null
        },
        n._bonesTransformMatrices = null,
        n._transformMatrixTexture = null,
        n.onRebuildObservable = new Observable,
        n._onCollisionPositionChange = function(o, a, s) {
            s === void 0 && (s = null),
            a.subtractToRef(n._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions, n._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),
            n._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length() > Engine.CollisionsEpsilon && n.position.addInPlace(n._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),
            s && n.onCollideObservable.notifyObservers(s),
            n.onCollisionPositionChangeObservable.notifyObservers(n.position)
        }
        ,
        n.getScene().addMesh(n),
        n._resyncLightSources(),
        n._uniformBuffer = new UniformBuffer(n.getScene().getEngine(),void 0,void 0,t),
        n._buildUniformLayout(),
        n
    }
    return Object.defineProperty(e, "BILLBOARDMODE_NONE", {
        get: function() {
            return TransformNode.BILLBOARDMODE_NONE
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e, "BILLBOARDMODE_X", {
        get: function() {
            return TransformNode.BILLBOARDMODE_X
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e, "BILLBOARDMODE_Y", {
        get: function() {
            return TransformNode.BILLBOARDMODE_Y
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e, "BILLBOARDMODE_Z", {
        get: function() {
            return TransformNode.BILLBOARDMODE_Z
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e, "BILLBOARDMODE_ALL", {
        get: function() {
            return TransformNode.BILLBOARDMODE_ALL
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e, "BILLBOARDMODE_USE_POSITION", {
        get: function() {
            return TransformNode.BILLBOARDMODE_USE_POSITION
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "facetNb", {
        get: function() {
            return this._internalAbstractMeshDataInfo._facetData.facetNb
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "partitioningSubdivisions", {
        get: function() {
            return this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions
        },
        set: function(t) {
            this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "partitioningBBoxRatio", {
        get: function() {
            return this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio
        },
        set: function(t) {
            this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "mustDepthSortFacets", {
        get: function() {
            return this._internalAbstractMeshDataInfo._facetData.facetDepthSort
        },
        set: function(t) {
            this._internalAbstractMeshDataInfo._facetData.facetDepthSort = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "facetDepthSortFrom", {
        get: function() {
            return this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom
        },
        set: function(t) {
            this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "collisionRetryCount", {
        get: function() {
            return this._internalAbstractMeshDataInfo._collisionRetryCount
        },
        set: function(t) {
            this._internalAbstractMeshDataInfo._collisionRetryCount = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "isFacetDataEnabled", {
        get: function() {
            return this._internalAbstractMeshDataInfo._facetData.facetDataEnabled
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "morphTargetManager", {
        get: function() {
            return this._internalAbstractMeshDataInfo._morphTargetManager
        },
        set: function(t) {
            this._internalAbstractMeshDataInfo._morphTargetManager !== t && (this._internalAbstractMeshDataInfo._morphTargetManager = t,
            this._syncGeometryWithMorphTargetManager())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "bakedVertexAnimationManager", {
        get: function() {
            return this._internalAbstractMeshDataInfo._bakedVertexAnimationManager
        },
        set: function(t) {
            this._internalAbstractMeshDataInfo._bakedVertexAnimationManager !== t && (this._internalAbstractMeshDataInfo._bakedVertexAnimationManager = t,
            this._markSubMeshesAsAttributesDirty())
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._syncGeometryWithMorphTargetManager = function() {}
    ,
    e.prototype._updateNonUniformScalingState = function(t) {
        return i.prototype._updateNonUniformScalingState.call(this, t) ? (this._markSubMeshesAsMiscDirty(),
        !0) : !1
    }
    ,
    Object.defineProperty(e.prototype, "onCollide", {
        set: function(t) {
            this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver && this.onCollideObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver),
            this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver = this.onCollideObservable.add(t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "onCollisionPositionChange", {
        set: function(t) {
            this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver && this.onCollisionPositionChangeObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver),
            this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "visibility", {
        get: function() {
            return this._internalAbstractMeshDataInfo._visibility
        },
        set: function(t) {
            if (this._internalAbstractMeshDataInfo._visibility !== t) {
                var r = this._internalAbstractMeshDataInfo._visibility;
                this._internalAbstractMeshDataInfo._visibility = t,
                (r === 1 && t !== 1 || r !== 1 && t === 1) && this._markSubMeshesAsMiscDirty()
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "renderingGroupId", {
        get: function() {
            return this._internalAbstractMeshDataInfo._renderingGroupId
        },
        set: function(t) {
            this._internalAbstractMeshDataInfo._renderingGroupId = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "material", {
        get: function() {
            return this._internalAbstractMeshDataInfo._material
        },
        set: function(t) {
            this._internalAbstractMeshDataInfo._material !== t && (this._internalAbstractMeshDataInfo._material && this._internalAbstractMeshDataInfo._material.meshMap && (this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId] = void 0),
            this._internalAbstractMeshDataInfo._material = t,
            t && t.meshMap && (t.meshMap[this.uniqueId] = this),
            this.onMaterialChangedObservable.hasObservers() && this.onMaterialChangedObservable.notifyObservers(this),
            this.subMeshes && (this.resetDrawCache(),
            this._unBindEffect()))
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getMaterialForRenderPass = function(t) {
        var r;
        return (r = this._internalAbstractMeshDataInfo._materialForRenderPass) === null || r === void 0 ? void 0 : r[t]
    }
    ,
    e.prototype.setMaterialForRenderPass = function(t, r) {
        this._internalAbstractMeshDataInfo._materialForRenderPass || (this._internalAbstractMeshDataInfo._materialForRenderPass = []),
        this._internalAbstractMeshDataInfo._materialForRenderPass[t] = r
    }
    ,
    Object.defineProperty(e.prototype, "receiveShadows", {
        get: function() {
            return this._internalAbstractMeshDataInfo._receiveShadows
        },
        set: function(t) {
            this._internalAbstractMeshDataInfo._receiveShadows !== t && (this._internalAbstractMeshDataInfo._receiveShadows = t,
            this._markSubMeshesAsLightDirty())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "hasVertexAlpha", {
        get: function() {
            return this._internalAbstractMeshDataInfo._hasVertexAlpha
        },
        set: function(t) {
            this._internalAbstractMeshDataInfo._hasVertexAlpha !== t && (this._internalAbstractMeshDataInfo._hasVertexAlpha = t,
            this._markSubMeshesAsAttributesDirty(),
            this._markSubMeshesAsMiscDirty())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "useVertexColors", {
        get: function() {
            return this._internalAbstractMeshDataInfo._useVertexColors
        },
        set: function(t) {
            this._internalAbstractMeshDataInfo._useVertexColors !== t && (this._internalAbstractMeshDataInfo._useVertexColors = t,
            this._markSubMeshesAsAttributesDirty())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "computeBonesUsingShaders", {
        get: function() {
            return this._internalAbstractMeshDataInfo._computeBonesUsingShaders
        },
        set: function(t) {
            this._internalAbstractMeshDataInfo._computeBonesUsingShaders !== t && (this._internalAbstractMeshDataInfo._computeBonesUsingShaders = t,
            this._markSubMeshesAsAttributesDirty())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "numBoneInfluencers", {
        get: function() {
            return this._internalAbstractMeshDataInfo._numBoneInfluencers
        },
        set: function(t) {
            this._internalAbstractMeshDataInfo._numBoneInfluencers !== t && (this._internalAbstractMeshDataInfo._numBoneInfluencers = t,
            this._markSubMeshesAsAttributesDirty())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "applyFog", {
        get: function() {
            return this._internalAbstractMeshDataInfo._applyFog
        },
        set: function(t) {
            this._internalAbstractMeshDataInfo._applyFog !== t && (this._internalAbstractMeshDataInfo._applyFog = t,
            this._markSubMeshesAsMiscDirty())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "layerMask", {
        get: function() {
            return this._internalAbstractMeshDataInfo._layerMask
        },
        set: function(t) {
            t !== this._internalAbstractMeshDataInfo._layerMask && (this._internalAbstractMeshDataInfo._layerMask = t,
            this._resyncLightSources())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "collisionMask", {
        get: function() {
            return this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask
        },
        set: function(t) {
            this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask = isNaN(t) ? -1 : t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "collisionResponse", {
        get: function() {
            return this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse
        },
        set: function(t) {
            this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "collisionGroup", {
        get: function() {
            return this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup
        },
        set: function(t) {
            this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup = isNaN(t) ? -1 : t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "surroundingMeshes", {
        get: function() {
            return this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes
        },
        set: function(t) {
            this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "lightSources", {
        get: function() {
            return this._lightSources
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "_positions", {
        get: function() {
            return null
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "skeleton", {
        get: function() {
            return this._internalAbstractMeshDataInfo._skeleton
        },
        set: function(t) {
            var r = this._internalAbstractMeshDataInfo._skeleton;
            r && r.needInitialSkinMatrix && r._unregisterMeshWithPoseMatrix(this),
            t && t.needInitialSkinMatrix && t._registerMeshWithPoseMatrix(this),
            this._internalAbstractMeshDataInfo._skeleton = t,
            this._internalAbstractMeshDataInfo._skeleton || (this._bonesTransformMatrices = null),
            this._markSubMeshesAsAttributesDirty()
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._buildUniformLayout = function() {
        this._uniformBuffer.addUniform("world", 16),
        this._uniformBuffer.addUniform("visibility", 1),
        this._uniformBuffer.create()
    }
    ,
    e.prototype.transferToEffect = function(t) {
        var r = this._uniformBuffer;
        r.updateMatrix("world", t),
        r.updateFloat("visibility", this._internalAbstractMeshDataInfo._visibility),
        r.update()
    }
    ,
    e.prototype.getMeshUniformBuffer = function() {
        return this._uniformBuffer
    }
    ,
    e.prototype.getClassName = function() {
        return "AbstractMesh"
    }
    ,
    e.prototype.toString = function(t) {
        var r = "Name: " + this.name + ", isInstance: " + (this.getClassName() !== "InstancedMesh" ? "YES" : "NO");
        r += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
        var n = this._internalAbstractMeshDataInfo._skeleton;
        return n && (r += ", skeleton: " + n.name),
        t && (r += ", billboard mode: " + ["NONE", "X", "Y", null, "Z", null, null, "ALL"][this.billboardMode],
        r += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingData.freezeWorldMatrix ? "YES" : "NO")),
        r
    }
    ,
    e.prototype._getEffectiveParent = function() {
        return this._masterMesh && this.billboardMode !== TransformNode.BILLBOARDMODE_NONE ? this._masterMesh : i.prototype._getEffectiveParent.call(this)
    }
    ,
    e.prototype._getActionManagerForTrigger = function(t, r) {
        if (r === void 0 && (r = !0),
        this.actionManager && (r || this.actionManager.isRecursive))
            if (t) {
                if (this.actionManager.hasSpecificTrigger(t))
                    return this.actionManager
            } else
                return this.actionManager;
        return this.parent ? this.parent._getActionManagerForTrigger(t, !1) : null
    }
    ,
    e.prototype._rebuild = function(t) {
        if (this.onRebuildObservable.notifyObservers(this),
        this._occlusionQuery !== null && (this._occlusionQuery = null),
        !!this.subMeshes)
            for (var r = 0, n = this.subMeshes; r < n.length; r++) {
                var o = n[r];
                o._rebuild()
            }
    }
    ,
    e.prototype._resyncLightSources = function() {
        this._lightSources.length = 0;
        for (var t = 0, r = this.getScene().lights; t < r.length; t++) {
            var n = r[t];
            !n.isEnabled() || n.canAffectMesh(this) && this._lightSources.push(n)
        }
        this._markSubMeshesAsLightDirty()
    }
    ,
    e.prototype._resyncLightSource = function(t) {
        var r = t.isEnabled() && t.canAffectMesh(this)
          , n = this._lightSources.indexOf(t)
          , o = !1;
        if (n === -1) {
            if (!r)
                return;
            this._lightSources.push(t)
        } else {
            if (r)
                return;
            o = !0,
            this._lightSources.splice(n, 1)
        }
        this._markSubMeshesAsLightDirty(o)
    }
    ,
    e.prototype._unBindEffect = function() {
        for (var t = 0, r = this.subMeshes; t < r.length; t++) {
            var n = r[t];
            n.setEffect(null)
        }
    }
    ,
    e.prototype._removeLightSource = function(t, r) {
        var n = this._lightSources.indexOf(t);
        n !== -1 && (this._lightSources.splice(n, 1),
        this._markSubMeshesAsLightDirty(r))
    }
    ,
    e.prototype._markSubMeshesAsDirty = function(t) {
        if (!!this.subMeshes)
            for (var r = 0, n = this.subMeshes; r < n.length; r++)
                for (var o = n[r], a = 0; a < o._drawWrappers.length; ++a) {
                    var s = o._drawWrappers[a];
                    !s || !s.defines || !s.defines.markAllAsDirty || t(s.defines)
                }
    }
    ,
    e.prototype._markSubMeshesAsLightDirty = function(t) {
        t === void 0 && (t = !1),
        this._markSubMeshesAsDirty(function(r) {
            return r.markAsLightDirty(t)
        })
    }
    ,
    e.prototype._markSubMeshesAsAttributesDirty = function() {
        this._markSubMeshesAsDirty(function(t) {
            return t.markAsAttributesDirty()
        })
    }
    ,
    e.prototype._markSubMeshesAsMiscDirty = function() {
        this._markSubMeshesAsDirty(function(t) {
            return t.markAsMiscDirty()
        })
    }
    ,
    e.prototype.markAsDirty = function(t) {
        return this._currentRenderId = Number.MAX_VALUE,
        this._isDirty = !0,
        this
    }
    ,
    e.prototype.resetDrawCache = function() {
        if (!!this.subMeshes)
            for (var t = 0, r = this.subMeshes; t < r.length; t++) {
                var n = r[t];
                n.resetDrawCache()
            }
    }
    ,
    Object.defineProperty(e.prototype, "scaling", {
        get: function() {
            return this._scaling
        },
        set: function(t) {
            this._scaling = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "isBlocked", {
        get: function() {
            return !1
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getLOD = function(t) {
        return this
    }
    ,
    e.prototype.getTotalVertices = function() {
        return 0
    }
    ,
    e.prototype.getTotalIndices = function() {
        return 0
    }
    ,
    e.prototype.getIndices = function() {
        return null
    }
    ,
    e.prototype.getVerticesData = function(t) {
        return null
    }
    ,
    e.prototype.setVerticesData = function(t, r, n, o) {
        return this
    }
    ,
    e.prototype.updateVerticesData = function(t, r, n, o) {
        return this
    }
    ,
    e.prototype.setIndices = function(t, r) {
        return this
    }
    ,
    e.prototype.isVerticesDataPresent = function(t) {
        return !1
    }
    ,
    e.prototype.getBoundingInfo = function() {
        return this._masterMesh ? this._masterMesh.getBoundingInfo() : (this._boundingInfoIsDirty && (this._boundingInfoIsDirty = !1,
        this._updateBoundingInfo()),
        this._boundingInfo)
    }
    ,
    e.prototype.setBoundingInfo = function(t) {
        return this._boundingInfo = t,
        this
    }
    ,
    Object.defineProperty(e.prototype, "hasBoundingInfo", {
        get: function() {
            return this._boundingInfo !== null
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.buildBoundingInfo = function(t, r, n) {
        return this._boundingInfo = new BoundingInfo(t,r,n),
        this._boundingInfo
    }
    ,
    e.prototype.normalizeToUnitCube = function(t, r, n) {
        return t === void 0 && (t = !0),
        r === void 0 && (r = !1),
        i.prototype.normalizeToUnitCube.call(this, t, r, n)
    }
    ,
    Object.defineProperty(e.prototype, "useBones", {
        get: function() {
            return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind)
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._preActivate = function() {}
    ,
    e.prototype._preActivateForIntermediateRendering = function(t) {}
    ,
    e.prototype._activate = function(t, r) {
        return this._renderId = t,
        !0
    }
    ,
    e.prototype._postActivate = function() {}
    ,
    e.prototype._freeze = function() {}
    ,
    e.prototype._unFreeze = function() {}
    ,
    e.prototype.getWorldMatrix = function() {
        return this._masterMesh && this.billboardMode === TransformNode.BILLBOARDMODE_NONE ? this._masterMesh.getWorldMatrix() : i.prototype.getWorldMatrix.call(this)
    }
    ,
    e.prototype._getWorldMatrixDeterminant = function() {
        return this._masterMesh ? this._masterMesh._getWorldMatrixDeterminant() : i.prototype._getWorldMatrixDeterminant.call(this)
    }
    ,
    Object.defineProperty(e.prototype, "isAnInstance", {
        get: function() {
            return !1
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "hasInstances", {
        get: function() {
            return !1
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "hasThinInstances", {
        get: function() {
            return !1
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.movePOV = function(t, r, n) {
        return this.position.addInPlace(this.calcMovePOV(t, r, n)),
        this
    }
    ,
    e.prototype.calcMovePOV = function(t, r, n) {
        var o = new Matrix
          , a = this.rotationQuaternion ? this.rotationQuaternion : Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
        a.toRotationMatrix(o);
        var s = Vector3.Zero()
          , l = this.definedFacingForward ? -1 : 1;
        return Vector3.TransformCoordinatesFromFloatsToRef(t * l, r, n * l, o, s),
        s
    }
    ,
    e.prototype.rotatePOV = function(t, r, n) {
        return this.rotation.addInPlace(this.calcRotatePOV(t, r, n)),
        this
    }
    ,
    e.prototype.calcRotatePOV = function(t, r, n) {
        var o = this.definedFacingForward ? 1 : -1;
        return new Vector3(t * o,r,n * o)
    }
    ,
    e.prototype.refreshBoundingInfo = function(t, r) {
        return t === void 0 && (t = !1),
        r === void 0 && (r = !1),
        this._boundingInfo && this._boundingInfo.isLocked ? this : (this._refreshBoundingInfo(this._getPositionData(t, r), null),
        this)
    }
    ,
    e.prototype._refreshBoundingInfo = function(t, r) {
        if (t) {
            var n = extractMinAndMax(t, 0, this.getTotalVertices(), r);
            this._boundingInfo ? this._boundingInfo.reConstruct(n.minimum, n.maximum) : this._boundingInfo = new BoundingInfo(n.minimum,n.maximum)
        }
        if (this.subMeshes)
            for (var o = 0; o < this.subMeshes.length; o++)
                this.subMeshes[o].refreshBoundingInfo(t);
        this._updateBoundingInfo()
    }
    ,
    e.prototype._getPositionData = function(t, r) {
        var n, o = this.getVerticesData(VertexBuffer.PositionKind);
        if (this._internalAbstractMeshDataInfo._positions && (this._internalAbstractMeshDataInfo._positions = null),
        o && (t && this.skeleton || r && this.morphTargetManager) && (o = Tools.Slice(o),
        this._generatePointsArray(),
        this._positions)) {
            var a = this._positions;
            this._internalAbstractMeshDataInfo._positions = new Array(a.length);
            for (var s = 0; s < a.length; s++)
                this._internalAbstractMeshDataInfo._positions[s] = ((n = a[s]) === null || n === void 0 ? void 0 : n.clone()) || new Vector3
        }
        if (o && r && this.morphTargetManager)
            for (var l = 0, u = 0, c = 0; c < o.length; c++) {
                for (var h = 0; h < this.morphTargetManager.numTargets; h++) {
                    var f = this.morphTargetManager.getTarget(h)
                      , d = f.influence;
                    if (d > 0) {
                        var _ = f.getPositions();
                        _ && (o[c] += (_[c] - o[c]) * d)
                    }
                }
                if (l++,
                this._positions && l === 3) {
                    l = 0;
                    var g = u * 3;
                    this._positions[u++].copyFromFloats(o[g], o[g + 1], o[g + 2])
                }
            }
        if (o && t && this.skeleton) {
            var m = this.getVerticesData(VertexBuffer.MatricesIndicesKind)
              , v = this.getVerticesData(VertexBuffer.MatricesWeightsKind);
            if (v && m) {
                var y = this.numBoneInfluencers > 4
                  , b = y ? this.getVerticesData(VertexBuffer.MatricesIndicesExtraKind) : null
                  , T = y ? this.getVerticesData(VertexBuffer.MatricesWeightsExtraKind) : null;
                this.skeleton.prepare();
                for (var C = this.skeleton.getTransformMatrices(this), A = TmpVectors.Vector3[0], S = TmpVectors.Matrix[0], P = TmpVectors.Matrix[1], R = 0, M = 0; M < o.length; M += 3,
                R += 4) {
                    S.reset();
                    var x, I;
                    for (x = 0; x < 4; x++)
                        I = v[R + x],
                        I > 0 && (Matrix.FromFloat32ArrayToRefScaled(C, Math.floor(m[R + x] * 16), I, P),
                        S.addToSelf(P));
                    if (y)
                        for (x = 0; x < 4; x++)
                            I = T[R + x],
                            I > 0 && (Matrix.FromFloat32ArrayToRefScaled(C, Math.floor(b[R + x] * 16), I, P),
                            S.addToSelf(P));
                    Vector3.TransformCoordinatesFromFloatsToRef(o[M], o[M + 1], o[M + 2], S, A),
                    A.toArray(o, M),
                    this._positions && this._positions[M / 3].copyFrom(A)
                }
            }
        }
        return o
    }
    ,
    e.prototype._updateBoundingInfo = function() {
        var t = this._effectiveMesh;
        return this._boundingInfo ? this._boundingInfo.update(t.worldMatrixFromCache) : this._boundingInfo = new BoundingInfo(this.position,this.position,t.worldMatrixFromCache),
        this._updateSubMeshesBoundingInfo(t.worldMatrixFromCache),
        this
    }
    ,
    e.prototype._updateSubMeshesBoundingInfo = function(t) {
        if (!this.subMeshes)
            return this;
        for (var r = this.subMeshes.length, n = 0; n < r; n++) {
            var o = this.subMeshes[n];
            (r > 1 || !o.IsGlobal) && o.updateBoundingInfo(t)
        }
        return this
    }
    ,
    e.prototype._afterComputeWorldMatrix = function() {
        this.doNotSyncBoundingInfo || (this._boundingInfoIsDirty = !0)
    }
    ,
    Object.defineProperty(e.prototype, "_effectiveMesh", {
        get: function() {
            return this.skeleton && this.skeleton.overrideMesh || this
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.isInFrustum = function(t) {
        return this.getBoundingInfo().isInFrustum(t, this.cullingStrategy)
    }
    ,
    e.prototype.isCompletelyInFrustum = function(t) {
        return this.getBoundingInfo().isCompletelyInFrustum(t)
    }
    ,
    e.prototype.intersectsMesh = function(t, r, n) {
        r === void 0 && (r = !1);
        var o = this.getBoundingInfo()
          , a = t.getBoundingInfo();
        if (o.intersects(a, r))
            return !0;
        if (n)
            for (var s = 0, l = this.getChildMeshes(); s < l.length; s++) {
                var u = l[s];
                if (u.intersectsMesh(t, r, !0))
                    return !0
            }
        return !1
    }
    ,
    e.prototype.intersectsPoint = function(t) {
        return this.getBoundingInfo().intersectsPoint(t)
    }
    ,
    Object.defineProperty(e.prototype, "checkCollisions", {
        get: function() {
            return this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions
        },
        set: function(t) {
            this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "collider", {
        get: function() {
            return this._internalAbstractMeshDataInfo._meshCollisionData._collider
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.moveWithCollisions = function(t) {
        var r = this.getAbsolutePosition();
        r.addToRef(this.ellipsoidOffset, this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions);
        var n = this.getScene().collisionCoordinator;
        return this._internalAbstractMeshDataInfo._meshCollisionData._collider || (this._internalAbstractMeshDataInfo._meshCollisionData._collider = n.createCollider()),
        this._internalAbstractMeshDataInfo._meshCollisionData._collider._radius = this.ellipsoid,
        n.getNewPosition(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions, t, this._internalAbstractMeshDataInfo._meshCollisionData._collider, this.collisionRetryCount, this, this._onCollisionPositionChange, this.uniqueId),
        this
    }
    ,
    e.prototype._collideForSubMesh = function(t, r, n) {
        if (this._generatePointsArray(),
        !this._positions)
            return this;
        if (!t._lastColliderWorldVertices || !t._lastColliderTransformMatrix.equals(r)) {
            t._lastColliderTransformMatrix = r.clone(),
            t._lastColliderWorldVertices = [],
            t._trianglePlanes = [];
            for (var o = t.verticesStart, a = t.verticesStart + t.verticesCount, s = o; s < a; s++)
                t._lastColliderWorldVertices.push(Vector3.TransformCoordinates(this._positions[s], r))
        }
        return n._collide(t._trianglePlanes, t._lastColliderWorldVertices, this.getIndices(), t.indexStart, t.indexStart + t.indexCount, t.verticesStart, !!t.getMaterial(), this),
        this
    }
    ,
    e.prototype._processCollisionsForSubMeshes = function(t, r) {
        for (var n = this._scene.getCollidingSubMeshCandidates(this, t), o = n.length, a = 0; a < o; a++) {
            var s = n.data[a];
            o > 1 && !s._checkCollision(t) || this._collideForSubMesh(s, r, t)
        }
        return this
    }
    ,
    e.prototype._checkCollision = function(t) {
        if (!this.getBoundingInfo()._checkCollision(t))
            return this;
        var r = TmpVectors.Matrix[0]
          , n = TmpVectors.Matrix[1];
        return Matrix.ScalingToRef(1 / t._radius.x, 1 / t._radius.y, 1 / t._radius.z, r),
        this.worldMatrixFromCache.multiplyToRef(r, n),
        this._processCollisionsForSubMeshes(t, n),
        this
    }
    ,
    e.prototype._generatePointsArray = function() {
        return !1
    }
    ,
    e.prototype.intersects = function(t, r, n, o, a, s) {
        o === void 0 && (o = !1),
        s === void 0 && (s = !1);
        var l = new PickingInfo
          , u = this.getClassName() === "InstancedLinesMesh" || this.getClassName() === "LinesMesh" ? this.intersectionThreshold : 0
          , c = this.getBoundingInfo();
        if (!this.subMeshes || !s && (!t.intersectsSphere(c.boundingSphere, u) || !t.intersectsBox(c.boundingBox, u)))
            return l;
        if (o)
            return l.hit = !s,
            l.pickedMesh = s ? null : this,
            l.distance = s ? 0 : Vector3.Distance(t.origin, c.boundingSphere.center),
            l.subMeshId = 0,
            l;
        if (!this._generatePointsArray())
            return l;
        for (var h = null, f = this._scene.getIntersectingSubMeshCandidates(this, t), d = f.length, _ = !1, g = 0; g < d; g++) {
            var m = f.data[g]
              , v = m.getMaterial();
            if (!!v && (v.fillMode == 7 || v.fillMode == 0 || v.fillMode == 1 || v.fillMode == 2)) {
                _ = !0;
                break
            }
        }
        if (!_)
            return l.hit = !0,
            l.pickedMesh = this,
            l.distance = Vector3.Distance(t.origin, c.boundingSphere.center),
            l.subMeshId = -1,
            l;
        for (var g = 0; g < d; g++) {
            var m = f.data[g];
            if (!(d > 1 && !m.canIntersects(t))) {
                var y = m.intersects(t, this._positions, this.getIndices(), r, n);
                if (y && (r || !h || y.distance < h.distance) && (h = y,
                h.subMeshId = g,
                r))
                    break
            }
        }
        if (h) {
            var b = a != null ? a : this.skeleton && this.skeleton.overrideMesh ? this.skeleton.overrideMesh.getWorldMatrix() : this.getWorldMatrix()
              , T = TmpVectors.Vector3[0]
              , C = TmpVectors.Vector3[1];
            Vector3.TransformCoordinatesToRef(t.origin, b, T),
            t.direction.scaleToRef(h.distance, C);
            var A = Vector3.TransformNormal(C, b)
              , S = A.addInPlace(T);
            return l.hit = !0,
            l.distance = Vector3.Distance(T, S),
            l.pickedPoint = S,
            l.pickedMesh = this,
            l.bu = h.bu || 0,
            l.bv = h.bv || 0,
            l.subMeshFaceId = h.faceId,
            l.faceId = h.faceId + f.data[h.subMeshId].indexStart / (this.getClassName().indexOf("LinesMesh") !== -1 ? 2 : 3),
            l.subMeshId = h.subMeshId,
            l
        }
        return l
    }
    ,
    e.prototype.clone = function(t, r, n) {
        return null
    }
    ,
    e.prototype.releaseSubMeshes = function() {
        if (this.subMeshes)
            for (; this.subMeshes.length; )
                this.subMeshes[0].dispose();
        else
            this.subMeshes = new Array;
        return this
    }
    ,
    e.prototype.dispose = function(t, r) {
        var n = this;
        r === void 0 && (r = !1);
        var o;
        for (this._scene.useMaterialMeshMap && this._internalAbstractMeshDataInfo._material && this._internalAbstractMeshDataInfo._material.meshMap && (this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId] = void 0),
        this.getScene().freeActiveMeshes(),
        this.getScene().freeRenderingGroups(),
        this.actionManager !== void 0 && this.actionManager !== null && (this.actionManager.dispose(),
        this.actionManager = null),
        this._internalAbstractMeshDataInfo._skeleton = null,
        this._transformMatrixTexture && (this._transformMatrixTexture.dispose(),
        this._transformMatrixTexture = null),
        o = 0; o < this._intersectionsInProgress.length; o++) {
            var a = this._intersectionsInProgress[o]
              , s = a._intersectionsInProgress.indexOf(this);
            a._intersectionsInProgress.splice(s, 1)
        }
        this._intersectionsInProgress = [];
        var l = this.getScene().lights;
        l.forEach(function(h) {
            var f = h.includedOnlyMeshes.indexOf(n);
            f !== -1 && h.includedOnlyMeshes.splice(f, 1),
            f = h.excludedMeshes.indexOf(n),
            f !== -1 && h.excludedMeshes.splice(f, 1);
            var d = h.getShadowGenerator();
            if (d) {
                var _ = d.getShadowMap();
                _ && _.renderList && (f = _.renderList.indexOf(n),
                f !== -1 && _.renderList.splice(f, 1))
            }
        }),
        (this.getClassName() !== "InstancedMesh" || this.getClassName() !== "InstancedLinesMesh") && this.releaseSubMeshes();
        var u = this.getScene().getEngine();
        if (this._occlusionQuery !== null && (this.isOcclusionQueryInProgress = !1,
        u.deleteQuery(this._occlusionQuery),
        this._occlusionQuery = null),
        u.wipeCaches(),
        this.getScene().removeMesh(this),
        this._parentContainer) {
            var c = this._parentContainer.meshes.indexOf(this);
            c > -1 && this._parentContainer.meshes.splice(c, 1),
            this._parentContainer = null
        }
        if (r && this.material && (this.material.getClassName() === "MultiMaterial" ? this.material.dispose(!1, !0, !0) : this.material.dispose(!1, !0)),
        !t)
            for (o = 0; o < this.getScene().particleSystems.length; o++)
                this.getScene().particleSystems[o].emitter === this && (this.getScene().particleSystems[o].dispose(),
                o--);
        this._internalAbstractMeshDataInfo._facetData.facetDataEnabled && this.disableFacetData(),
        this._uniformBuffer.dispose(),
        this.onAfterWorldMatrixUpdateObservable.clear(),
        this.onCollideObservable.clear(),
        this.onCollisionPositionChangeObservable.clear(),
        this.onRebuildObservable.clear(),
        i.prototype.dispose.call(this, t, r)
    }
    ,
    e.prototype.addChild = function(t, r) {
        return r === void 0 && (r = !1),
        t.setParent(this, r),
        this
    }
    ,
    e.prototype.removeChild = function(t, r) {
        return r === void 0 && (r = !1),
        t.setParent(null, r),
        this
    }
    ,
    e.prototype._initFacetData = function() {
        var t = this._internalAbstractMeshDataInfo._facetData;
        t.facetNormals || (t.facetNormals = new Array),
        t.facetPositions || (t.facetPositions = new Array),
        t.facetPartitioning || (t.facetPartitioning = new Array),
        t.facetNb = this.getIndices().length / 3 | 0,
        t.partitioningSubdivisions = t.partitioningSubdivisions ? t.partitioningSubdivisions : 10,
        t.partitioningBBoxRatio = t.partitioningBBoxRatio ? t.partitioningBBoxRatio : 1.01;
        for (var r = 0; r < t.facetNb; r++)
            t.facetNormals[r] = Vector3.Zero(),
            t.facetPositions[r] = Vector3.Zero();
        return t.facetDataEnabled = !0,
        this
    }
    ,
    e.prototype.updateFacetData = function() {
        var t = this._internalAbstractMeshDataInfo._facetData;
        t.facetDataEnabled || this._initFacetData();
        var r = this.getVerticesData(VertexBuffer.PositionKind)
          , n = this.getIndices()
          , o = this.getVerticesData(VertexBuffer.NormalKind)
          , a = this.getBoundingInfo();
        if (t.facetDepthSort && !t.facetDepthSortEnabled) {
            if (t.facetDepthSortEnabled = !0,
            n instanceof Uint16Array)
                t.depthSortedIndices = new Uint16Array(n);
            else if (n instanceof Uint32Array)
                t.depthSortedIndices = new Uint32Array(n);
            else {
                for (var s = !1, l = 0; l < n.length; l++)
                    if (n[l] > 65535) {
                        s = !0;
                        break
                    }
                s ? t.depthSortedIndices = new Uint32Array(n) : t.depthSortedIndices = new Uint16Array(n)
            }
            if (t.facetDepthSortFunction = function(g, m) {
                return m.sqDistance - g.sqDistance
            }
            ,
            !t.facetDepthSortFrom) {
                var u = this.getScene().activeCamera;
                t.facetDepthSortFrom = u ? u.position : Vector3.Zero()
            }
            t.depthSortedFacets = [];
            for (var c = 0; c < t.facetNb; c++) {
                var h = {
                    ind: c * 3,
                    sqDistance: 0
                };
                t.depthSortedFacets.push(h)
            }
            t.invertedMatrix = Matrix.Identity(),
            t.facetDepthSortOrigin = Vector3.Zero()
        }
        t.bbSize.x = a.maximum.x - a.minimum.x > Epsilon ? a.maximum.x - a.minimum.x : Epsilon,
        t.bbSize.y = a.maximum.y - a.minimum.y > Epsilon ? a.maximum.y - a.minimum.y : Epsilon,
        t.bbSize.z = a.maximum.z - a.minimum.z > Epsilon ? a.maximum.z - a.minimum.z : Epsilon;
        var f = t.bbSize.x > t.bbSize.y ? t.bbSize.x : t.bbSize.y;
        if (f = f > t.bbSize.z ? f : t.bbSize.z,
        t.subDiv.max = t.partitioningSubdivisions,
        t.subDiv.X = Math.floor(t.subDiv.max * t.bbSize.x / f),
        t.subDiv.Y = Math.floor(t.subDiv.max * t.bbSize.y / f),
        t.subDiv.Z = Math.floor(t.subDiv.max * t.bbSize.z / f),
        t.subDiv.X = t.subDiv.X < 1 ? 1 : t.subDiv.X,
        t.subDiv.Y = t.subDiv.Y < 1 ? 1 : t.subDiv.Y,
        t.subDiv.Z = t.subDiv.Z < 1 ? 1 : t.subDiv.Z,
        t.facetParameters.facetNormals = this.getFacetLocalNormals(),
        t.facetParameters.facetPositions = this.getFacetLocalPositions(),
        t.facetParameters.facetPartitioning = this.getFacetLocalPartitioning(),
        t.facetParameters.bInfo = a,
        t.facetParameters.bbSize = t.bbSize,
        t.facetParameters.subDiv = t.subDiv,
        t.facetParameters.ratio = this.partitioningBBoxRatio,
        t.facetParameters.depthSort = t.facetDepthSort,
        t.facetDepthSort && t.facetDepthSortEnabled && (this.computeWorldMatrix(!0),
        this._worldMatrix.invertToRef(t.invertedMatrix),
        Vector3.TransformCoordinatesToRef(t.facetDepthSortFrom, t.invertedMatrix, t.facetDepthSortOrigin),
        t.facetParameters.distanceTo = t.facetDepthSortOrigin),
        t.facetParameters.depthSortedFacets = t.depthSortedFacets,
        o && VertexData.ComputeNormals(r, n, o, t.facetParameters),
        t.facetDepthSort && t.facetDepthSortEnabled) {
            t.depthSortedFacets.sort(t.facetDepthSortFunction);
            for (var d = t.depthSortedIndices.length / 3 | 0, c = 0; c < d; c++) {
                var _ = t.depthSortedFacets[c].ind;
                t.depthSortedIndices[c * 3] = n[_],
                t.depthSortedIndices[c * 3 + 1] = n[_ + 1],
                t.depthSortedIndices[c * 3 + 2] = n[_ + 2]
            }
            this.updateIndices(t.depthSortedIndices, void 0, !0)
        }
        return this
    }
    ,
    e.prototype.getFacetLocalNormals = function() {
        var t = this._internalAbstractMeshDataInfo._facetData;
        return t.facetNormals || this.updateFacetData(),
        t.facetNormals
    }
    ,
    e.prototype.getFacetLocalPositions = function() {
        var t = this._internalAbstractMeshDataInfo._facetData;
        return t.facetPositions || this.updateFacetData(),
        t.facetPositions
    }
    ,
    e.prototype.getFacetLocalPartitioning = function() {
        var t = this._internalAbstractMeshDataInfo._facetData;
        return t.facetPartitioning || this.updateFacetData(),
        t.facetPartitioning
    }
    ,
    e.prototype.getFacetPosition = function(t) {
        var r = Vector3.Zero();
        return this.getFacetPositionToRef(t, r),
        r
    }
    ,
    e.prototype.getFacetPositionToRef = function(t, r) {
        var n = this.getFacetLocalPositions()[t]
          , o = this.getWorldMatrix();
        return Vector3.TransformCoordinatesToRef(n, o, r),
        this
    }
    ,
    e.prototype.getFacetNormal = function(t) {
        var r = Vector3.Zero();
        return this.getFacetNormalToRef(t, r),
        r
    }
    ,
    e.prototype.getFacetNormalToRef = function(t, r) {
        var n = this.getFacetLocalNormals()[t];
        return Vector3.TransformNormalToRef(n, this.getWorldMatrix(), r),
        this
    }
    ,
    e.prototype.getFacetsAtLocalCoordinates = function(t, r, n) {
        var o = this.getBoundingInfo()
          , a = this._internalAbstractMeshDataInfo._facetData
          , s = Math.floor((t - o.minimum.x * a.partitioningBBoxRatio) * a.subDiv.X * a.partitioningBBoxRatio / a.bbSize.x)
          , l = Math.floor((r - o.minimum.y * a.partitioningBBoxRatio) * a.subDiv.Y * a.partitioningBBoxRatio / a.bbSize.y)
          , u = Math.floor((n - o.minimum.z * a.partitioningBBoxRatio) * a.subDiv.Z * a.partitioningBBoxRatio / a.bbSize.z);
        return s < 0 || s > a.subDiv.max || l < 0 || l > a.subDiv.max || u < 0 || u > a.subDiv.max ? null : a.facetPartitioning[s + a.subDiv.max * l + a.subDiv.max * a.subDiv.max * u]
    }
    ,
    e.prototype.getClosestFacetAtCoordinates = function(t, r, n, o, a, s) {
        a === void 0 && (a = !1),
        s === void 0 && (s = !0);
        var l = this.getWorldMatrix()
          , u = TmpVectors.Matrix[5];
        l.invertToRef(u);
        var c = TmpVectors.Vector3[8];
        Vector3.TransformCoordinatesFromFloatsToRef(t, r, n, u, c);
        var h = this.getClosestFacetAtLocalCoordinates(c.x, c.y, c.z, o, a, s);
        return o && Vector3.TransformCoordinatesFromFloatsToRef(o.x, o.y, o.z, l, o),
        h
    }
    ,
    e.prototype.getClosestFacetAtLocalCoordinates = function(t, r, n, o, a, s) {
        a === void 0 && (a = !1),
        s === void 0 && (s = !0);
        var l = null
          , u = 0
          , c = 0
          , h = 0
          , f = 0
          , d = 0
          , _ = 0
          , g = 0
          , m = 0
          , v = this.getFacetLocalPositions()
          , y = this.getFacetLocalNormals()
          , b = this.getFacetsAtLocalCoordinates(t, r, n);
        if (!b)
            return null;
        for (var T = Number.MAX_VALUE, C = T, A, S, P, R = 0; R < b.length; R++)
            A = b[R],
            S = y[A],
            P = v[A],
            f = (t - P.x) * S.x + (r - P.y) * S.y + (n - P.z) * S.z,
            (!a || a && s && f >= 0 || a && !s && f <= 0) && (f = S.x * P.x + S.y * P.y + S.z * P.z,
            d = -(S.x * t + S.y * r + S.z * n - f) / (S.x * S.x + S.y * S.y + S.z * S.z),
            _ = t + S.x * d,
            g = r + S.y * d,
            m = n + S.z * d,
            u = _ - t,
            c = g - r,
            h = m - n,
            C = u * u + c * c + h * h,
            C < T && (T = C,
            l = A,
            o && (o.x = _,
            o.y = g,
            o.z = m)));
        return l
    }
    ,
    e.prototype.getFacetDataParameters = function() {
        return this._internalAbstractMeshDataInfo._facetData.facetParameters
    }
    ,
    e.prototype.disableFacetData = function() {
        var t = this._internalAbstractMeshDataInfo._facetData;
        return t.facetDataEnabled && (t.facetDataEnabled = !1,
        t.facetPositions = new Array,
        t.facetNormals = new Array,
        t.facetPartitioning = new Array,
        t.facetParameters = null,
        t.depthSortedIndices = new Uint32Array(0)),
        this
    }
    ,
    e.prototype.updateIndices = function(t, r, n) {
        return this
    }
    ,
    e.prototype.createNormals = function(t) {
        var r = this.getVerticesData(VertexBuffer.PositionKind), n = this.getIndices(), o;
        return this.isVerticesDataPresent(VertexBuffer.NormalKind) ? o = this.getVerticesData(VertexBuffer.NormalKind) : o = [],
        VertexData.ComputeNormals(r, n, o, {
            useRightHandedSystem: this.getScene().useRightHandedSystem
        }),
        this.setVerticesData(VertexBuffer.NormalKind, o, t),
        this
    }
    ,
    e.prototype.alignWithNormal = function(t, r) {
        r || (r = Axis.Y);
        var n = TmpVectors.Vector3[0]
          , o = TmpVectors.Vector3[1];
        return Vector3.CrossToRef(r, t, o),
        Vector3.CrossToRef(t, o, n),
        this.rotationQuaternion ? Quaternion.RotationQuaternionFromAxisToRef(n, t, o, this.rotationQuaternion) : Vector3.RotationFromAxisToRef(n, t, o, this.rotation),
        this
    }
    ,
    e.prototype._checkOcclusionQuery = function() {
        return !1
    }
    ,
    e.prototype.disableEdgesRendering = function() {
        throw _WarnImport("EdgesRenderer")
    }
    ,
    e.prototype.enableEdgesRendering = function(t, r, n) {
        throw _WarnImport("EdgesRenderer")
    }
    ,
    e.prototype.getConnectedParticleSystems = function() {
        var t = this;
        return this._scene.particleSystems.filter(function(r) {
            return r.emitter === t
        })
    }
    ,
    e.OCCLUSION_TYPE_NONE = 0,
    e.OCCLUSION_TYPE_OPTIMISTIC = 1,
    e.OCCLUSION_TYPE_STRICT = 2,
    e.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0,
    e.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1,
    e.CULLINGSTRATEGY_STANDARD = 0,
    e.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1,
    e.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION = 2,
    e.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY = 3,
    e
}(TransformNode);
RegisterClass("BABYLON.AbstractMesh", AbstractMesh);
var Viewport = function() {
    function i(e, t, r, n) {
        this.x = e,
        this.y = t,
        this.width = r,
        this.height = n
    }
    return i.prototype.toGlobal = function(e, t) {
        return new i(this.x * e,this.y * t,this.width * e,this.height * t)
    }
    ,
    i.prototype.toGlobalToRef = function(e, t, r) {
        return r.x = this.x * e,
        r.y = this.y * t,
        r.width = this.width * e,
        r.height = this.height * t,
        this
    }
    ,
    i.prototype.clone = function() {
        return new i(this.x,this.y,this.width,this.height)
    }
    ,
    i
}()
  , Camera$1 = function(i) {
    __extends(e, i);
    function e(t, r, n, o) {
        o === void 0 && (o = !0);
        var a = i.call(this, t, n) || this;
        return a._position = Vector3.Zero(),
        a._upVector = Vector3.Up(),
        a.orthoLeft = null,
        a.orthoRight = null,
        a.orthoBottom = null,
        a.orthoTop = null,
        a.fov = .8,
        a.projectionPlaneTilt = 0,
        a.minZ = 1,
        a.maxZ = 1e4,
        a.inertia = .9,
        a.mode = e.PERSPECTIVE_CAMERA,
        a.isIntermediate = !1,
        a.viewport = new Viewport(0,0,1,1),
        a.layerMask = 268435455,
        a.fovMode = e.FOVMODE_VERTICAL_FIXED,
        a.cameraRigMode = e.RIG_MODE_NONE,
        a.customRenderTargets = new Array,
        a.outputRenderTarget = null,
        a.onViewMatrixChangedObservable = new Observable,
        a.onProjectionMatrixChangedObservable = new Observable,
        a.onAfterCheckInputsObservable = new Observable,
        a.onRestoreStateObservable = new Observable,
        a.isRigCamera = !1,
        a._rigCameras = new Array,
        a._webvrViewMatrix = Matrix.Identity(),
        a._skipRendering = !1,
        a._projectionMatrix = new Matrix,
        a._postProcesses = new Array,
        a._activeMeshes = new SmartArray(256),
        a._globalPosition = Vector3.Zero(),
        a._computedViewMatrix = Matrix.Identity(),
        a._doNotComputeProjectionMatrix = !1,
        a._transformMatrix = Matrix.Zero(),
        a._refreshFrustumPlanes = !0,
        a._absoluteRotation = Quaternion.Identity(),
        a._isCamera = !0,
        a._isLeftCamera = !1,
        a._isRightCamera = !1,
        a.getScene().addCamera(a),
        o && !a.getScene().activeCamera && (a.getScene().activeCamera = a),
        a.position = r,
        a.renderPassId = a.getScene().getEngine().createRenderPassId("Camera " + t),
        a
    }
    return Object.defineProperty(e.prototype, "position", {
        get: function() {
            return this._position
        },
        set: function(t) {
            this._position = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "upVector", {
        get: function() {
            return this._upVector
        },
        set: function(t) {
            this._upVector = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "screenArea", {
        get: function() {
            var t, r, n, o, a = 0, s = 0;
            if (this.mode === e.PERSPECTIVE_CAMERA)
                this.fovMode === e.FOVMODE_VERTICAL_FIXED ? (s = this.minZ * 2 * Math.tan(this.fov / 2),
                a = this.getEngine().getAspectRatio(this) * s) : (a = this.minZ * 2 * Math.tan(this.fov / 2),
                s = a / this.getEngine().getAspectRatio(this));
            else {
                var l = this.getEngine().getRenderWidth() / 2
                  , u = this.getEngine().getRenderHeight() / 2;
                a = ((t = this.orthoRight) !== null && t !== void 0 ? t : l) - ((r = this.orthoLeft) !== null && r !== void 0 ? r : -l),
                s = ((n = this.orthoTop) !== null && n !== void 0 ? n : u) - ((o = this.orthoBottom) !== null && o !== void 0 ? o : -u)
            }
            return a * s
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.storeState = function() {
        return this._stateStored = !0,
        this._storedFov = this.fov,
        this
    }
    ,
    e.prototype._restoreStateValues = function() {
        return this._stateStored ? (this.fov = this._storedFov,
        !0) : !1
    }
    ,
    e.prototype.restoreState = function() {
        return this._restoreStateValues() ? (this.onRestoreStateObservable.notifyObservers(this),
        !0) : !1
    }
    ,
    e.prototype.getClassName = function() {
        return "Camera"
    }
    ,
    e.prototype.toString = function(t) {
        var r = "Name: " + this.name;
        if (r += ", type: " + this.getClassName(),
        this.animations)
            for (var n = 0; n < this.animations.length; n++)
                r += ", animation[0]: " + this.animations[n].toString(t);
        return r
    }
    ,
    e.prototype.applyVerticalCorrection = function() {
        var t = this.absoluteRotation.toEulerAngles();
        this.projectionPlaneTilt = this._scene.useRightHandedSystem ? -t.x : t.x
    }
    ,
    Object.defineProperty(e.prototype, "globalPosition", {
        get: function() {
            return this._globalPosition
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getActiveMeshes = function() {
        return this._activeMeshes
    }
    ,
    e.prototype.isActiveMesh = function(t) {
        return this._activeMeshes.indexOf(t) !== -1
    }
    ,
    e.prototype.isReady = function(t) {
        if (t === void 0 && (t = !1),
        t)
            for (var r = 0, n = this._postProcesses; r < n.length; r++) {
                var o = n[r];
                if (o && !o.isReady())
                    return !1
            }
        return i.prototype.isReady.call(this, t)
    }
    ,
    e.prototype._initCache = function() {
        i.prototype._initCache.call(this),
        this._cache.position = new Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),
        this._cache.upVector = new Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),
        this._cache.mode = void 0,
        this._cache.minZ = void 0,
        this._cache.maxZ = void 0,
        this._cache.fov = void 0,
        this._cache.fovMode = void 0,
        this._cache.aspectRatio = void 0,
        this._cache.orthoLeft = void 0,
        this._cache.orthoRight = void 0,
        this._cache.orthoBottom = void 0,
        this._cache.orthoTop = void 0,
        this._cache.renderWidth = void 0,
        this._cache.renderHeight = void 0
    }
    ,
    e.prototype._updateCache = function(t) {
        t || i.prototype._updateCache.call(this),
        this._cache.position.copyFrom(this.position),
        this._cache.upVector.copyFrom(this.upVector)
    }
    ,
    e.prototype._isSynchronized = function() {
        return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix()
    }
    ,
    e.prototype._isSynchronizedViewMatrix = function() {
        return i.prototype._isSynchronized.call(this) ? this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent() : !1
    }
    ,
    e.prototype._isSynchronizedProjectionMatrix = function() {
        var t = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
        if (!t)
            return !1;
        var r = this.getEngine();
        return this.mode === e.PERSPECTIVE_CAMERA ? t = this._cache.fov === this.fov && this._cache.fovMode === this.fovMode && this._cache.aspectRatio === r.getAspectRatio(this) && this._cache.projectionPlaneTilt === this.projectionPlaneTilt : t = this._cache.orthoLeft === this.orthoLeft && this._cache.orthoRight === this.orthoRight && this._cache.orthoBottom === this.orthoBottom && this._cache.orthoTop === this.orthoTop && this._cache.renderWidth === r.getRenderWidth() && this._cache.renderHeight === r.getRenderHeight(),
        t
    }
    ,
    e.prototype.attachControl = function(t, r) {}
    ,
    e.prototype.detachControl = function(t) {}
    ,
    e.prototype.update = function() {
        this._checkInputs(),
        this.cameraRigMode !== e.RIG_MODE_NONE && this._updateRigCameras()
    }
    ,
    e.prototype._checkInputs = function() {
        this.onAfterCheckInputsObservable.notifyObservers(this)
    }
    ,
    Object.defineProperty(e.prototype, "rigCameras", {
        get: function() {
            return this._rigCameras
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "rigPostProcess", {
        get: function() {
            return this._rigPostProcess
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._getFirstPostProcess = function() {
        for (var t = 0; t < this._postProcesses.length; t++)
            if (this._postProcesses[t] !== null)
                return this._postProcesses[t];
        return null
    }
    ,
    e.prototype._cascadePostProcessesToRigCams = function() {
        var t = this._getFirstPostProcess();
        t && t.markTextureDirty();
        for (var r = 0, n = this._rigCameras.length; r < n; r++) {
            var o = this._rigCameras[r]
              , a = o._rigPostProcess;
            if (a) {
                var s = a.getEffectName() === "pass";
                s && (o.isIntermediate = this._postProcesses.length === 0),
                o._postProcesses = this._postProcesses.slice(0).concat(a),
                a.markTextureDirty()
            } else
                o._postProcesses = this._postProcesses.slice(0)
        }
    }
    ,
    e.prototype.attachPostProcess = function(t, r) {
        return r === void 0 && (r = null),
        !t.isReusable() && this._postProcesses.indexOf(t) > -1 ? (Logger$2.Error("You're trying to reuse a post process not defined as reusable."),
        0) : (r == null || r < 0 ? this._postProcesses.push(t) : this._postProcesses[r] === null ? this._postProcesses[r] = t : this._postProcesses.splice(r, 0, t),
        this._cascadePostProcessesToRigCams(),
        this._scene.prePassRenderer && this._scene.prePassRenderer.markAsDirty(),
        this._postProcesses.indexOf(t))
    }
    ,
    e.prototype.detachPostProcess = function(t) {
        var r = this._postProcesses.indexOf(t);
        r !== -1 && (this._postProcesses[r] = null),
        this._scene.prePassRenderer && this._scene.prePassRenderer.markAsDirty(),
        this._cascadePostProcessesToRigCams()
    }
    ,
    e.prototype.getWorldMatrix = function() {
        return this._isSynchronizedViewMatrix() ? this._worldMatrix : (this.getViewMatrix(),
        this._worldMatrix)
    }
    ,
    e.prototype._getViewMatrix = function() {
        return Matrix.Identity()
    }
    ,
    e.prototype.getViewMatrix = function(t) {
        return !t && this._isSynchronizedViewMatrix() ? this._computedViewMatrix : (this.updateCache(),
        this._computedViewMatrix = this._getViewMatrix(),
        this._currentRenderId = this.getScene().getRenderId(),
        this._childUpdateId++,
        this._refreshFrustumPlanes = !0,
        this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix && this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix),
        this.parent && this.parent.onViewMatrixChangedObservable && this.parent.onViewMatrixChangedObservable.notifyObservers(this.parent),
        this.onViewMatrixChangedObservable.notifyObservers(this),
        this._computedViewMatrix.invertToRef(this._worldMatrix),
        this._computedViewMatrix)
    }
    ,
    e.prototype.freezeProjectionMatrix = function(t) {
        this._doNotComputeProjectionMatrix = !0,
        t !== void 0 && (this._projectionMatrix = t)
    }
    ,
    e.prototype.unfreezeProjectionMatrix = function() {
        this._doNotComputeProjectionMatrix = !1
    }
    ,
    e.prototype.getProjectionMatrix = function(t) {
        var r, n, o, a, s, l, u, c;
        if (this._doNotComputeProjectionMatrix || !t && this._isSynchronizedProjectionMatrix())
            return this._projectionMatrix;
        this._cache.mode = this.mode,
        this._cache.minZ = this.minZ,
        this._cache.maxZ = this.maxZ,
        this._refreshFrustumPlanes = !0;
        var h = this.getEngine()
          , f = this.getScene();
        if (this.mode === e.PERSPECTIVE_CAMERA) {
            this._cache.fov = this.fov,
            this._cache.fovMode = this.fovMode,
            this._cache.aspectRatio = h.getAspectRatio(this),
            this._cache.projectionPlaneTilt = this.projectionPlaneTilt,
            this.minZ <= 0 && (this.minZ = .1);
            var d = h.useReverseDepthBuffer
              , _ = void 0;
            f.useRightHandedSystem ? _ = Matrix.PerspectiveFovRHToRef : _ = Matrix.PerspectiveFovLHToRef,
            _(this.fov, h.getAspectRatio(this), d ? this.maxZ : this.minZ, d ? this.minZ : this.maxZ, this._projectionMatrix, this.fovMode === e.FOVMODE_VERTICAL_FIXED, h.isNDCHalfZRange, this.projectionPlaneTilt, h.useReverseDepthBuffer)
        } else {
            var g = h.getRenderWidth() / 2
              , m = h.getRenderHeight() / 2;
            f.useRightHandedSystem ? Matrix.OrthoOffCenterRHToRef((r = this.orthoLeft) !== null && r !== void 0 ? r : -g, (n = this.orthoRight) !== null && n !== void 0 ? n : g, (o = this.orthoBottom) !== null && o !== void 0 ? o : -m, (a = this.orthoTop) !== null && a !== void 0 ? a : m, this.minZ, this.maxZ, this._projectionMatrix, h.isNDCHalfZRange) : Matrix.OrthoOffCenterLHToRef((s = this.orthoLeft) !== null && s !== void 0 ? s : -g, (l = this.orthoRight) !== null && l !== void 0 ? l : g, (u = this.orthoBottom) !== null && u !== void 0 ? u : -m, (c = this.orthoTop) !== null && c !== void 0 ? c : m, this.minZ, this.maxZ, this._projectionMatrix, h.isNDCHalfZRange),
            this._cache.orthoLeft = this.orthoLeft,
            this._cache.orthoRight = this.orthoRight,
            this._cache.orthoBottom = this.orthoBottom,
            this._cache.orthoTop = this.orthoTop,
            this._cache.renderWidth = h.getRenderWidth(),
            this._cache.renderHeight = h.getRenderHeight()
        }
        return this.onProjectionMatrixChangedObservable.notifyObservers(this),
        this._projectionMatrix
    }
    ,
    e.prototype.getTransformationMatrix = function() {
        return this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix),
        this._transformMatrix
    }
    ,
    e.prototype._updateFrustumPlanes = function() {
        !this._refreshFrustumPlanes || (this.getTransformationMatrix(),
        this._frustumPlanes ? Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes) : this._frustumPlanes = Frustum.GetPlanes(this._transformMatrix),
        this._refreshFrustumPlanes = !1)
    }
    ,
    e.prototype.isInFrustum = function(t, r) {
        if (r === void 0 && (r = !1),
        this._updateFrustumPlanes(),
        r && this.rigCameras.length > 0) {
            var n = !1;
            return this.rigCameras.forEach(function(o) {
                o._updateFrustumPlanes(),
                n = n || t.isInFrustum(o._frustumPlanes)
            }),
            n
        } else
            return t.isInFrustum(this._frustumPlanes)
    }
    ,
    e.prototype.isCompletelyInFrustum = function(t) {
        return this._updateFrustumPlanes(),
        t.isCompletelyInFrustum(this._frustumPlanes)
    }
    ,
    e.prototype.getForwardRay = function(t, r, n) {
        throw _WarnImport("Ray")
    }
    ,
    e.prototype.getForwardRayToRef = function(t, r, n, o) {
        throw _WarnImport("Ray")
    }
    ,
    e.prototype.dispose = function(t, r) {
        for (r === void 0 && (r = !1),
        this.onViewMatrixChangedObservable.clear(),
        this.onProjectionMatrixChangedObservable.clear(),
        this.onAfterCheckInputsObservable.clear(),
        this.onRestoreStateObservable.clear(),
        this.inputs && this.inputs.clear(),
        this.getScene().stopAnimation(this),
        this.getScene().removeCamera(this); this._rigCameras.length > 0; ) {
            var n = this._rigCameras.pop();
            n && n.dispose()
        }
        if (this._parentContainer) {
            var o = this._parentContainer.cameras.indexOf(this);
            o > -1 && this._parentContainer.cameras.splice(o, 1),
            this._parentContainer = null
        }
        if (this._rigPostProcess)
            this._rigPostProcess.dispose(this),
            this._rigPostProcess = null,
            this._postProcesses = [];
        else if (this.cameraRigMode !== e.RIG_MODE_NONE)
            this._rigPostProcess = null,
            this._postProcesses = [];
        else
            for (var s = this._postProcesses.length; --s >= 0; ) {
                var a = this._postProcesses[s];
                a && a.dispose(this)
            }
        for (var s = this.customRenderTargets.length; --s >= 0; )
            this.customRenderTargets[s].dispose();
        this.customRenderTargets = [],
        this._activeMeshes.dispose(),
        this.getScene().getEngine().releaseRenderPassId(this.renderPassId),
        i.prototype.dispose.call(this, t, r)
    }
    ,
    Object.defineProperty(e.prototype, "isLeftCamera", {
        get: function() {
            return this._isLeftCamera
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "isRightCamera", {
        get: function() {
            return this._isRightCamera
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "leftCamera", {
        get: function() {
            return this._rigCameras.length < 1 ? null : this._rigCameras[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "rightCamera", {
        get: function() {
            return this._rigCameras.length < 2 ? null : this._rigCameras[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getLeftTarget = function() {
        return this._rigCameras.length < 1 ? null : this._rigCameras[0].getTarget()
    }
    ,
    e.prototype.getRightTarget = function() {
        return this._rigCameras.length < 2 ? null : this._rigCameras[1].getTarget()
    }
    ,
    e.prototype.setCameraRigMode = function(t, r) {
        if (this.cameraRigMode !== t) {
            for (; this._rigCameras.length > 0; ) {
                var n = this._rigCameras.pop();
                n && n.dispose()
            }
            if (this.cameraRigMode = t,
            this._cameraRigParams = {},
            this._cameraRigParams.interaxialDistance = r.interaxialDistance || .0637,
            this._cameraRigParams.stereoHalfAngle = Tools.ToRadians(this._cameraRigParams.interaxialDistance / .0637),
            this.cameraRigMode !== e.RIG_MODE_NONE) {
                var o = this.createRigCamera(this.name + "_L", 0);
                o && (o._isLeftCamera = !0);
                var a = this.createRigCamera(this.name + "_R", 1);
                a && (a._isRightCamera = !0),
                o && a && (this._rigCameras.push(o),
                this._rigCameras.push(a))
            }
            this._setRigMode(r),
            this._cascadePostProcessesToRigCams(),
            this.update()
        }
    }
    ,
    e.prototype._setRigMode = function(t) {}
    ,
    e.prototype._getVRProjectionMatrix = function() {
        return Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix, !0, this.getEngine().isNDCHalfZRange),
        this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix),
        this._projectionMatrix
    }
    ,
    e.prototype._updateCameraRotationMatrix = function() {}
    ,
    e.prototype._updateWebVRCameraRotationMatrix = function() {}
    ,
    e.prototype._getWebVRProjectionMatrix = function() {
        return Matrix.Identity()
    }
    ,
    e.prototype._getWebVRViewMatrix = function() {
        return Matrix.Identity()
    }
    ,
    e.prototype.setCameraRigParameter = function(t, r) {
        this._cameraRigParams || (this._cameraRigParams = {}),
        this._cameraRigParams[t] = r,
        t === "interaxialDistance" && (this._cameraRigParams.stereoHalfAngle = Tools.ToRadians(r / .0637))
    }
    ,
    e.prototype.createRigCamera = function(t, r) {
        return null
    }
    ,
    e.prototype._updateRigCameras = function() {
        for (var t = 0; t < this._rigCameras.length; t++)
            this._rigCameras[t].minZ = this.minZ,
            this._rigCameras[t].maxZ = this.maxZ,
            this._rigCameras[t].fov = this.fov,
            this._rigCameras[t].upVector.copyFrom(this.upVector);
        this.cameraRigMode === e.RIG_MODE_STEREOSCOPIC_ANAGLYPH && (this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport)
    }
    ,
    e.prototype._setupInputs = function() {}
    ,
    e.prototype.serialize = function() {
        var t = SerializationHelper.Serialize(this);
        return t.uniqueId = this.uniqueId,
        t.type = this.getClassName(),
        this.parent && (t.parentId = this.parent.uniqueId),
        this.inputs && this.inputs.serialize(t),
        SerializationHelper.AppendSerializedAnimations(this, t),
        t.ranges = this.serializeAnimationRanges(),
        t.isEnabled = this.isEnabled(),
        t
    }
    ,
    e.prototype.clone = function(t) {
        var r = SerializationHelper.Clone(e.GetConstructorFromName(this.getClassName(), t, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
        return r.name = t,
        this.onClonedObservable.notifyObservers(r),
        r
    }
    ,
    e.prototype.getDirection = function(t) {
        var r = Vector3.Zero();
        return this.getDirectionToRef(t, r),
        r
    }
    ,
    Object.defineProperty(e.prototype, "absoluteRotation", {
        get: function() {
            return this.getWorldMatrix().decompose(void 0, this._absoluteRotation),
            this._absoluteRotation
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getDirectionToRef = function(t, r) {
        Vector3.TransformNormalToRef(t, this.getWorldMatrix(), r)
    }
    ,
    e.GetConstructorFromName = function(t, r, n, o, a) {
        o === void 0 && (o = 0),
        a === void 0 && (a = !0);
        var s = Node$2.Construct(t, r, n, {
            interaxial_distance: o,
            isStereoscopicSideBySide: a
        });
        return s || function() {
            return e._createDefaultParsedCamera(r, n)
        }
    }
    ,
    e.prototype.computeWorldMatrix = function() {
        return this.getWorldMatrix()
    }
    ,
    e.Parse = function(t, r) {
        var n = t.type
          , o = e.GetConstructorFromName(n, t.name, r, t.interaxial_distance, t.isStereoscopicSideBySide)
          , a = SerializationHelper.Parse(o, t, r);
        if (t.parentId && (a._waitingParentId = t.parentId),
        a.inputs && (a.inputs.parse(t),
        a._setupInputs()),
        t.upVector && (a.upVector = Vector3.FromArray(t.upVector)),
        a.setPosition && (a.position.copyFromFloats(0, 0, 0),
        a.setPosition(Vector3.FromArray(t.position))),
        t.target && a.setTarget && a.setTarget(Vector3.FromArray(t.target)),
        t.cameraRigMode) {
            var s = t.interaxial_distance ? {
                interaxialDistance: t.interaxial_distance
            } : {};
            a.setCameraRigMode(t.cameraRigMode, s)
        }
        if (t.animations) {
            for (var l = 0; l < t.animations.length; l++) {
                var u = t.animations[l]
                  , c = GetClass("BABYLON.Animation");
                c && a.animations.push(c.Parse(u))
            }
            Node$2.ParseAnimationRanges(a, t, r)
        }
        return t.autoAnimate && r.beginAnimation(a, t.autoAnimateFrom, t.autoAnimateTo, t.autoAnimateLoop, t.autoAnimateSpeed || 1),
        t.isEnabled !== void 0 && a.setEnabled(t.isEnabled),
        a
    }
    ,
    e._createDefaultParsedCamera = function(t, r) {
        throw _WarnImport("UniversalCamera")
    }
    ,
    e.PERSPECTIVE_CAMERA = 0,
    e.ORTHOGRAPHIC_CAMERA = 1,
    e.FOVMODE_VERTICAL_FIXED = 0,
    e.FOVMODE_HORIZONTAL_FIXED = 1,
    e.RIG_MODE_NONE = 0,
    e.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10,
    e.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11,
    e.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12,
    e.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13,
    e.RIG_MODE_STEREOSCOPIC_INTERLACED = 14,
    e.RIG_MODE_VR = 20,
    e.RIG_MODE_WEBVR = 21,
    e.RIG_MODE_CUSTOM = 22,
    e.ForceAttachControlToAlwaysPreventDefault = !1,
    __decorate([serializeAsVector3("position")], e.prototype, "_position", void 0),
    __decorate([serializeAsVector3("upVector")], e.prototype, "_upVector", void 0),
    __decorate([serialize()], e.prototype, "orthoLeft", void 0),
    __decorate([serialize()], e.prototype, "orthoRight", void 0),
    __decorate([serialize()], e.prototype, "orthoBottom", void 0),
    __decorate([serialize()], e.prototype, "orthoTop", void 0),
    __decorate([serialize()], e.prototype, "fov", void 0),
    __decorate([serialize()], e.prototype, "projectionPlaneTilt", void 0),
    __decorate([serialize()], e.prototype, "minZ", void 0),
    __decorate([serialize()], e.prototype, "maxZ", void 0),
    __decorate([serialize()], e.prototype, "inertia", void 0),
    __decorate([serialize()], e.prototype, "mode", void 0),
    __decorate([serialize()], e.prototype, "layerMask", void 0),
    __decorate([serialize()], e.prototype, "fovMode", void 0),
    __decorate([serialize()], e.prototype, "cameraRigMode", void 0),
    __decorate([serialize()], e.prototype, "interaxialDistance", void 0),
    __decorate([serialize()], e.prototype, "isStereoscopicSideBySide", void 0),
    e
}(Node$2)
  , Light = function(i) {
    __extends(e, i);
    function e(t, r) {
        var n = i.call(this, t, r) || this;
        return n.diffuse = new Color3(1,1,1),
        n.specular = new Color3(1,1,1),
        n.falloffType = e.FALLOFF_DEFAULT,
        n.intensity = 1,
        n._range = Number.MAX_VALUE,
        n._inverseSquaredRange = 0,
        n._photometricScale = 1,
        n._intensityMode = e.INTENSITYMODE_AUTOMATIC,
        n._radius = 1e-5,
        n.renderPriority = 0,
        n._shadowEnabled = !0,
        n._excludeWithLayerMask = 0,
        n._includeOnlyWithLayerMask = 0,
        n._lightmapMode = 0,
        n._excludedMeshesIds = new Array,
        n._includedOnlyMeshesIds = new Array,
        n._isLight = !0,
        n.getScene().addLight(n),
        n._uniformBuffer = new UniformBuffer(n.getScene().getEngine(),void 0,void 0,t),
        n._buildUniformLayout(),
        n.includedOnlyMeshes = new Array,
        n.excludedMeshes = new Array,
        n._resyncMeshes(),
        n
    }
    return Object.defineProperty(e.prototype, "range", {
        get: function() {
            return this._range
        },
        set: function(t) {
            this._range = t,
            this._inverseSquaredRange = 1 / (this.range * this.range)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "intensityMode", {
        get: function() {
            return this._intensityMode
        },
        set: function(t) {
            this._intensityMode = t,
            this._computePhotometricScale()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "radius", {
        get: function() {
            return this._radius
        },
        set: function(t) {
            this._radius = t,
            this._computePhotometricScale()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "shadowEnabled", {
        get: function() {
            return this._shadowEnabled
        },
        set: function(t) {
            this._shadowEnabled !== t && (this._shadowEnabled = t,
            this._markMeshesAsLightDirty())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "includedOnlyMeshes", {
        get: function() {
            return this._includedOnlyMeshes
        },
        set: function(t) {
            this._includedOnlyMeshes = t,
            this._hookArrayForIncludedOnly(t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "excludedMeshes", {
        get: function() {
            return this._excludedMeshes
        },
        set: function(t) {
            this._excludedMeshes = t,
            this._hookArrayForExcluded(t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "excludeWithLayerMask", {
        get: function() {
            return this._excludeWithLayerMask
        },
        set: function(t) {
            this._excludeWithLayerMask = t,
            this._resyncMeshes()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "includeOnlyWithLayerMask", {
        get: function() {
            return this._includeOnlyWithLayerMask
        },
        set: function(t) {
            this._includeOnlyWithLayerMask = t,
            this._resyncMeshes()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "lightmapMode", {
        get: function() {
            return this._lightmapMode
        },
        set: function(t) {
            this._lightmapMode !== t && (this._lightmapMode = t,
            this._markMeshesAsLightDirty())
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.transferTexturesToEffect = function(t, r) {
        return this
    }
    ,
    e.prototype._bindLight = function(t, r, n, o, a) {
        a === void 0 && (a = !0);
        var s = t.toString()
          , l = !1;
        if (this._uniformBuffer.bindToEffect(n, "Light" + s),
        this._renderId !== r.getRenderId() || !this._uniformBuffer.useUbo) {
            this._renderId = r.getRenderId();
            var u = this.getScaledIntensity();
            this.transferToEffect(n, s),
            this.diffuse.scaleToRef(u, TmpColors.Color3[0]),
            this._uniformBuffer.updateColor4("vLightDiffuse", TmpColors.Color3[0], this.range, s),
            o && (this.specular.scaleToRef(u, TmpColors.Color3[1]),
            this._uniformBuffer.updateColor4("vLightSpecular", TmpColors.Color3[1], this.radius, s)),
            l = !0
        }
        if (this.transferTexturesToEffect(n, s),
        r.shadowsEnabled && this.shadowEnabled && a) {
            var c = this.getShadowGenerator();
            c && (c.bindShadowLight(s, n),
            l = !0)
        }
        l ? this._uniformBuffer.update() : this._uniformBuffer.bindUniformBuffer()
    }
    ,
    e.prototype.getClassName = function() {
        return "Light"
    }
    ,
    e.prototype.toString = function(t) {
        var r = "Name: " + this.name;
        if (r += ", type: " + ["Point", "Directional", "Spot", "Hemispheric"][this.getTypeID()],
        this.animations)
            for (var n = 0; n < this.animations.length; n++)
                r += ", animation[0]: " + this.animations[n].toString(t);
        return r
    }
    ,
    e.prototype._syncParentEnabledState = function() {
        i.prototype._syncParentEnabledState.call(this),
        this.isDisposed() || this._resyncMeshes()
    }
    ,
    e.prototype.setEnabled = function(t) {
        i.prototype.setEnabled.call(this, t),
        this._resyncMeshes()
    }
    ,
    e.prototype.getShadowGenerator = function() {
        return this._shadowGenerator
    }
    ,
    e.prototype.getAbsolutePosition = function() {
        return Vector3.Zero()
    }
    ,
    e.prototype.canAffectMesh = function(t) {
        return t ? !(this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(t) === -1 || this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(t) !== -1 || this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & t.layerMask) === 0 || this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & t.layerMask) : !0
    }
    ,
    e.prototype.dispose = function(t, r) {
        if (r === void 0 && (r = !1),
        this._shadowGenerator && (this._shadowGenerator.dispose(),
        this._shadowGenerator = null),
        this.getScene().stopAnimation(this),
        this._parentContainer) {
            var n = this._parentContainer.lights.indexOf(this);
            n > -1 && this._parentContainer.lights.splice(n, 1),
            this._parentContainer = null
        }
        for (var o = 0, a = this.getScene().meshes; o < a.length; o++) {
            var s = a[o];
            s._removeLightSource(this, !0)
        }
        this._uniformBuffer.dispose(),
        this.getScene().removeLight(this),
        i.prototype.dispose.call(this, t, r)
    }
    ,
    e.prototype.getTypeID = function() {
        return 0
    }
    ,
    e.prototype.getScaledIntensity = function() {
        return this._photometricScale * this.intensity
    }
    ,
    e.prototype.clone = function(t, r) {
        r === void 0 && (r = null);
        var n = e.GetConstructorFromName(this.getTypeID(), t, this.getScene());
        if (!n)
            return null;
        var o = SerializationHelper.Clone(n, this);
        return t && (o.name = t),
        r && (o.parent = r),
        o.setEnabled(this.isEnabled()),
        this.onClonedObservable.notifyObservers(o),
        o
    }
    ,
    e.prototype.serialize = function() {
        var t = SerializationHelper.Serialize(this);
        return t.uniqueId = this.uniqueId,
        t.type = this.getTypeID(),
        this.parent && (t.parentId = this.parent.uniqueId),
        this.excludedMeshes.length > 0 && (t.excludedMeshesIds = [],
        this.excludedMeshes.forEach(function(r) {
            t.excludedMeshesIds.push(r.id)
        })),
        this.includedOnlyMeshes.length > 0 && (t.includedOnlyMeshesIds = [],
        this.includedOnlyMeshes.forEach(function(r) {
            t.includedOnlyMeshesIds.push(r.id)
        })),
        SerializationHelper.AppendSerializedAnimations(this, t),
        t.ranges = this.serializeAnimationRanges(),
        t.isEnabled = this.isEnabled(),
        t
    }
    ,
    e.GetConstructorFromName = function(t, r, n) {
        var o = Node$2.Construct("Light_Type_" + t, r, n);
        return o || null
    }
    ,
    e.Parse = function(t, r) {
        var n = e.GetConstructorFromName(t.type, t.name, r);
        if (!n)
            return null;
        var o = SerializationHelper.Parse(n, t, r);
        if (t.excludedMeshesIds && (o._excludedMeshesIds = t.excludedMeshesIds),
        t.includedOnlyMeshesIds && (o._includedOnlyMeshesIds = t.includedOnlyMeshesIds),
        t.parentId && (o._waitingParentId = t.parentId),
        t.falloffType !== void 0 && (o.falloffType = t.falloffType),
        t.lightmapMode !== void 0 && (o.lightmapMode = t.lightmapMode),
        t.animations) {
            for (var a = 0; a < t.animations.length; a++) {
                var s = t.animations[a]
                  , l = GetClass("BABYLON.Animation");
                l && o.animations.push(l.Parse(s))
            }
            Node$2.ParseAnimationRanges(o, t, r)
        }
        return t.autoAnimate && r.beginAnimation(o, t.autoAnimateFrom, t.autoAnimateTo, t.autoAnimateLoop, t.autoAnimateSpeed || 1),
        t.isEnabled !== void 0 && o.setEnabled(t.isEnabled),
        o
    }
    ,
    e.prototype._hookArrayForExcluded = function(t) {
        var r = this
          , n = t.push;
        t.push = function() {
            for (var u = [], c = 0; c < arguments.length; c++)
                u[c] = arguments[c];
            for (var h = n.apply(t, u), f = 0, d = u; f < d.length; f++) {
                var _ = d[f];
                _._resyncLightSource(r)
            }
            return h
        }
        ;
        var o = t.splice;
        t.splice = function(u, c) {
            for (var h = o.apply(t, [u, c]), f = 0, d = h; f < d.length; f++) {
                var _ = d[f];
                _._resyncLightSource(r)
            }
            return h
        }
        ;
        for (var a = 0, s = t; a < s.length; a++) {
            var l = s[a];
            l._resyncLightSource(this)
        }
    }
    ,
    e.prototype._hookArrayForIncludedOnly = function(t) {
        var r = this
          , n = t.push;
        t.push = function() {
            for (var a = [], s = 0; s < arguments.length; s++)
                a[s] = arguments[s];
            var l = n.apply(t, a);
            return r._resyncMeshes(),
            l
        }
        ;
        var o = t.splice;
        t.splice = function(a, s) {
            var l = o.apply(t, [a, s]);
            return r._resyncMeshes(),
            l
        }
        ,
        this._resyncMeshes()
    }
    ,
    e.prototype._resyncMeshes = function() {
        for (var t = 0, r = this.getScene().meshes; t < r.length; t++) {
            var n = r[t];
            n._resyncLightSource(this)
        }
    }
    ,
    e.prototype._markMeshesAsLightDirty = function() {
        for (var t = 0, r = this.getScene().meshes; t < r.length; t++) {
            var n = r[t];
            n.lightSources.indexOf(this) !== -1 && n._markSubMeshesAsLightDirty()
        }
    }
    ,
    e.prototype._computePhotometricScale = function() {
        this._photometricScale = this._getPhotometricScale(),
        this.getScene().resetCachedMaterial()
    }
    ,
    e.prototype._getPhotometricScale = function() {
        var t = 0
          , r = this.getTypeID()
          , n = this.intensityMode;
        switch (n === e.INTENSITYMODE_AUTOMATIC && (r === e.LIGHTTYPEID_DIRECTIONALLIGHT ? n = e.INTENSITYMODE_ILLUMINANCE : n = e.INTENSITYMODE_LUMINOUSINTENSITY),
        r) {
        case e.LIGHTTYPEID_POINTLIGHT:
        case e.LIGHTTYPEID_SPOTLIGHT:
            switch (n) {
            case e.INTENSITYMODE_LUMINOUSPOWER:
                t = 1 / (4 * Math.PI);
                break;
            case e.INTENSITYMODE_LUMINOUSINTENSITY:
                t = 1;
                break;
            case e.INTENSITYMODE_LUMINANCE:
                t = this.radius * this.radius;
                break
            }
            break;
        case e.LIGHTTYPEID_DIRECTIONALLIGHT:
            switch (n) {
            case e.INTENSITYMODE_ILLUMINANCE:
                t = 1;
                break;
            case e.INTENSITYMODE_LUMINANCE:
                var o = this.radius;
                o = Math.max(o, .001);
                var a = 2 * Math.PI * (1 - Math.cos(o));
                t = a;
                break
            }
            break;
        case e.LIGHTTYPEID_HEMISPHERICLIGHT:
            t = 1;
            break
        }
        return t
    }
    ,
    e.prototype._reorderLightsInScene = function() {
        var t = this.getScene();
        this._renderPriority != 0 && (t.requireLightSorting = !0),
        this.getScene().sortLightsByPriority()
    }
    ,
    e.FALLOFF_DEFAULT = LightConstants.FALLOFF_DEFAULT,
    e.FALLOFF_PHYSICAL = LightConstants.FALLOFF_PHYSICAL,
    e.FALLOFF_GLTF = LightConstants.FALLOFF_GLTF,
    e.FALLOFF_STANDARD = LightConstants.FALLOFF_STANDARD,
    e.LIGHTMAP_DEFAULT = LightConstants.LIGHTMAP_DEFAULT,
    e.LIGHTMAP_SPECULAR = LightConstants.LIGHTMAP_SPECULAR,
    e.LIGHTMAP_SHADOWSONLY = LightConstants.LIGHTMAP_SHADOWSONLY,
    e.INTENSITYMODE_AUTOMATIC = LightConstants.INTENSITYMODE_AUTOMATIC,
    e.INTENSITYMODE_LUMINOUSPOWER = LightConstants.INTENSITYMODE_LUMINOUSPOWER,
    e.INTENSITYMODE_LUMINOUSINTENSITY = LightConstants.INTENSITYMODE_LUMINOUSINTENSITY,
    e.INTENSITYMODE_ILLUMINANCE = LightConstants.INTENSITYMODE_ILLUMINANCE,
    e.INTENSITYMODE_LUMINANCE = LightConstants.INTENSITYMODE_LUMINANCE,
    e.LIGHTTYPEID_POINTLIGHT = LightConstants.LIGHTTYPEID_POINTLIGHT,
    e.LIGHTTYPEID_DIRECTIONALLIGHT = LightConstants.LIGHTTYPEID_DIRECTIONALLIGHT,
    e.LIGHTTYPEID_SPOTLIGHT = LightConstants.LIGHTTYPEID_SPOTLIGHT,
    e.LIGHTTYPEID_HEMISPHERICLIGHT = LightConstants.LIGHTTYPEID_HEMISPHERICLIGHT,
    __decorate([serializeAsColor3()], e.prototype, "diffuse", void 0),
    __decorate([serializeAsColor3()], e.prototype, "specular", void 0),
    __decorate([serialize()], e.prototype, "falloffType", void 0),
    __decorate([serialize()], e.prototype, "intensity", void 0),
    __decorate([serialize()], e.prototype, "range", null),
    __decorate([serialize()], e.prototype, "intensityMode", null),
    __decorate([serialize()], e.prototype, "radius", null),
    __decorate([serialize()], e.prototype, "_renderPriority", void 0),
    __decorate([expandToProperty("_reorderLightsInScene")], e.prototype, "renderPriority", void 0),
    __decorate([serialize("shadowEnabled")], e.prototype, "_shadowEnabled", void 0),
    __decorate([serialize("excludeWithLayerMask")], e.prototype, "_excludeWithLayerMask", void 0),
    __decorate([serialize("includeOnlyWithLayerMask")], e.prototype, "_includeOnlyWithLayerMask", void 0),
    __decorate([serialize("lightmapMode")], e.prototype, "_lightmapMode", void 0),
    e
}(Node$2)
  , ThinMaterialHelper = function() {
    function i() {}
    return i.BindClipPlane = function(e, t) {
        if (t.clipPlane) {
            var r = t.clipPlane;
            e.setFloat4("vClipPlane", r.normal.x, r.normal.y, r.normal.z, r.d)
        }
        if (t.clipPlane2) {
            var r = t.clipPlane2;
            e.setFloat4("vClipPlane2", r.normal.x, r.normal.y, r.normal.z, r.d)
        }
        if (t.clipPlane3) {
            var r = t.clipPlane3;
            e.setFloat4("vClipPlane3", r.normal.x, r.normal.y, r.normal.z, r.d)
        }
        if (t.clipPlane4) {
            var r = t.clipPlane4;
            e.setFloat4("vClipPlane4", r.normal.x, r.normal.y, r.normal.z, r.d)
        }
        if (t.clipPlane5) {
            var r = t.clipPlane5;
            e.setFloat4("vClipPlane5", r.normal.x, r.normal.y, r.normal.z, r.d)
        }
        if (t.clipPlane6) {
            var r = t.clipPlane6;
            e.setFloat4("vClipPlane6", r.normal.x, r.normal.y, r.normal.z, r.d)
        }
    }
    ,
    i
}()
  , MaterialHelper = function() {
    function i() {}
    return i.BindSceneUniformBuffer = function(e, t) {
        t.bindToEffect(e, "Scene")
    }
    ,
    i.PrepareDefinesForMergedUV = function(e, t, r) {
        t._needUVs = !0,
        t[r] = !0,
        e.getTextureMatrix().isIdentityAs3x2() ? (t[r + "DIRECTUV"] = e.coordinatesIndex + 1,
        t["MAINUV" + (e.coordinatesIndex + 1)] = !0) : t[r + "DIRECTUV"] = 0
    }
    ,
    i.BindTextureMatrix = function(e, t, r) {
        var n = e.getTextureMatrix();
        t.updateMatrix(r + "Matrix", n)
    }
    ,
    i.GetFogState = function(e, t) {
        return t.fogEnabled && e.applyFog && t.fogMode !== Scene.FOGMODE_NONE
    }
    ,
    i.PrepareDefinesForMisc = function(e, t, r, n, o, a, s) {
        s._areMiscDirty && (s.LOGARITHMICDEPTH = r,
        s.POINTSIZE = n,
        s.FOG = o && this.GetFogState(e, t),
        s.NONUNIFORMSCALING = e.nonUniformScaling,
        s.ALPHATEST = a)
    }
    ,
    i.PrepareDefinesForFrameBoundValues = function(e, t, r, n, o, a) {
        o === void 0 && (o = null),
        a === void 0 && (a = !1);
        var s = !1
          , l = !1
          , u = !1
          , c = !1
          , h = !1
          , f = !1
          , d = !1;
        l = o == null ? e.clipPlane !== void 0 && e.clipPlane !== null : o,
        u = o == null ? e.clipPlane2 !== void 0 && e.clipPlane2 !== null : o,
        c = o == null ? e.clipPlane3 !== void 0 && e.clipPlane3 !== null : o,
        h = o == null ? e.clipPlane4 !== void 0 && e.clipPlane4 !== null : o,
        f = o == null ? e.clipPlane5 !== void 0 && e.clipPlane5 !== null : o,
        d = o == null ? e.clipPlane6 !== void 0 && e.clipPlane6 !== null : o,
        r.CLIPPLANE !== l && (r.CLIPPLANE = l,
        s = !0),
        r.CLIPPLANE2 !== u && (r.CLIPPLANE2 = u,
        s = !0),
        r.CLIPPLANE3 !== c && (r.CLIPPLANE3 = c,
        s = !0),
        r.CLIPPLANE4 !== h && (r.CLIPPLANE4 = h,
        s = !0),
        r.CLIPPLANE5 !== f && (r.CLIPPLANE5 = f,
        s = !0),
        r.CLIPPLANE6 !== d && (r.CLIPPLANE6 = d,
        s = !0),
        r.DEPTHPREPASS !== !t.getColorWrite() && (r.DEPTHPREPASS = !r.DEPTHPREPASS,
        s = !0),
        r.INSTANCES !== n && (r.INSTANCES = n,
        s = !0),
        r.THIN_INSTANCES !== a && (r.THIN_INSTANCES = a,
        s = !0),
        s && r.markAsUnprocessed()
    }
    ,
    i.PrepareDefinesForBones = function(e, t) {
        if (e.useBones && e.computeBonesUsingShaders && e.skeleton) {
            t.NUM_BONE_INFLUENCERS = e.numBoneInfluencers;
            var r = t.BONETEXTURE !== void 0;
            if (e.skeleton.isUsingTextureForMatrices && r)
                t.BONETEXTURE = !0;
            else {
                t.BonesPerMesh = e.skeleton.bones.length + 1,
                t.BONETEXTURE = r ? !1 : void 0;
                var n = e.getScene().prePassRenderer;
                if (n && n.enabled) {
                    var o = n.excludedSkinnedMesh.indexOf(e) === -1;
                    t.BONES_VELOCITY_ENABLED = o
                }
            }
        } else
            t.NUM_BONE_INFLUENCERS = 0,
            t.BonesPerMesh = 0
    }
    ,
    i.PrepareDefinesForMorphTargets = function(e, t) {
        var r = e.morphTargetManager;
        r ? (t.MORPHTARGETS_UV = r.supportsUVs && t.UV1,
        t.MORPHTARGETS_TANGENT = r.supportsTangents && t.TANGENT,
        t.MORPHTARGETS_NORMAL = r.supportsNormals && t.NORMAL,
        t.MORPHTARGETS = r.numInfluencers > 0,
        t.NUM_MORPH_INFLUENCERS = r.numInfluencers,
        t.MORPHTARGETS_TEXTURE = r.isUsingTextureForTargets) : (t.MORPHTARGETS_UV = !1,
        t.MORPHTARGETS_TANGENT = !1,
        t.MORPHTARGETS_NORMAL = !1,
        t.MORPHTARGETS = !1,
        t.NUM_MORPH_INFLUENCERS = 0)
    }
    ,
    i.PrepareDefinesForBakedVertexAnimation = function(e, t) {
        var r = e.bakedVertexAnimationManager;
        t.BAKED_VERTEX_ANIMATION_TEXTURE = !!(r && r.isEnabled)
    }
    ,
    i.PrepareDefinesForAttributes = function(e, t, r, n, o, a, s) {
        if (o === void 0 && (o = !1),
        a === void 0 && (a = !0),
        s === void 0 && (s = !0),
        !t._areAttributesDirty && t._needNormals === t._normals && t._needUVs === t._uvs)
            return !1;
        t._normals = t._needNormals,
        t._uvs = t._needUVs,
        t.NORMAL = t._needNormals && e.isVerticesDataPresent(VertexBuffer.NormalKind),
        t._needNormals && e.isVerticesDataPresent(VertexBuffer.TangentKind) && (t.TANGENT = !0);
        for (var l = 1; l <= 6; ++l)
            t["UV" + l] = t._needUVs ? e.isVerticesDataPresent("uv" + (l === 1 ? "" : l)) : !1;
        if (r) {
            var u = e.useVertexColors && e.isVerticesDataPresent(VertexBuffer.ColorKind);
            t.VERTEXCOLOR = u,
            t.VERTEXALPHA = e.hasVertexAlpha && u && a
        }
        return n && this.PrepareDefinesForBones(e, t),
        o && this.PrepareDefinesForMorphTargets(e, t),
        s && this.PrepareDefinesForBakedVertexAnimation(e, t),
        !0
    }
    ,
    i.PrepareDefinesForMultiview = function(e, t) {
        if (e.activeCamera) {
            var r = t.MULTIVIEW;
            t.MULTIVIEW = e.activeCamera.outputRenderTarget !== null && e.activeCamera.outputRenderTarget.getViewCount() > 1,
            t.MULTIVIEW != r && t.markAsUnprocessed()
        }
    }
    ,
    i.PrepareDefinesForOIT = function(e, t, r) {
        var n = t.ORDER_INDEPENDENT_TRANSPARENCY
          , o = t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS;
        t.ORDER_INDEPENDENT_TRANSPARENCY = e.useOrderIndependentTransparency && r,
        t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS = !e.getEngine().getCaps().textureFloatLinearFiltering,
        (n !== t.ORDER_INDEPENDENT_TRANSPARENCY || o !== t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS) && t.markAsUnprocessed()
    }
    ,
    i.PrepareDefinesForPrePass = function(e, t, r) {
        var n = t.PREPASS;
        if (!!t._arePrePassDirty) {
            var o = [{
                type: 1,
                define: "PREPASS_POSITION",
                index: "PREPASS_POSITION_INDEX"
            }, {
                type: 2,
                define: "PREPASS_VELOCITY",
                index: "PREPASS_VELOCITY_INDEX"
            }, {
                type: 3,
                define: "PREPASS_REFLECTIVITY",
                index: "PREPASS_REFLECTIVITY_INDEX"
            }, {
                type: 0,
                define: "PREPASS_IRRADIANCE",
                index: "PREPASS_IRRADIANCE_INDEX"
            }, {
                type: 7,
                define: "PREPASS_ALBEDO_SQRT",
                index: "PREPASS_ALBEDO_SQRT_INDEX"
            }, {
                type: 5,
                define: "PREPASS_DEPTH",
                index: "PREPASS_DEPTH_INDEX"
            }, {
                type: 6,
                define: "PREPASS_NORMAL",
                index: "PREPASS_NORMAL_INDEX"
            }];
            if (e.prePassRenderer && e.prePassRenderer.enabled && r) {
                t.PREPASS = !0,
                t.SCENE_MRT_COUNT = e.prePassRenderer.mrtCount;
                for (var a = 0; a < o.length; a++) {
                    var s = e.prePassRenderer.getIndex(o[a].type);
                    s !== -1 ? (t[o[a].define] = !0,
                    t[o[a].index] = s) : t[o[a].define] = !1
                }
            } else {
                t.PREPASS = !1;
                for (var a = 0; a < o.length; a++)
                    t[o[a].define] = !1
            }
            t.PREPASS != n && (t.markAsUnprocessed(),
            t.markAsImageProcessingDirty())
        }
    }
    ,
    i.PrepareDefinesForLight = function(e, t, r, n, o, a, s) {
        switch (s.needNormals = !0,
        o["LIGHT" + n] === void 0 && (s.needRebuild = !0),
        o["LIGHT" + n] = !0,
        o["SPOTLIGHT" + n] = !1,
        o["HEMILIGHT" + n] = !1,
        o["POINTLIGHT" + n] = !1,
        o["DIRLIGHT" + n] = !1,
        r.prepareLightSpecificDefines(o, n),
        o["LIGHT_FALLOFF_PHYSICAL" + n] = !1,
        o["LIGHT_FALLOFF_GLTF" + n] = !1,
        o["LIGHT_FALLOFF_STANDARD" + n] = !1,
        r.falloffType) {
        case Light.FALLOFF_GLTF:
            o["LIGHT_FALLOFF_GLTF" + n] = !0;
            break;
        case Light.FALLOFF_PHYSICAL:
            o["LIGHT_FALLOFF_PHYSICAL" + n] = !0;
            break;
        case Light.FALLOFF_STANDARD:
            o["LIGHT_FALLOFF_STANDARD" + n] = !0;
            break
        }
        if (a && !r.specular.equalsFloats(0, 0, 0) && (s.specularEnabled = !0),
        o["SHADOW" + n] = !1,
        o["SHADOWCSM" + n] = !1,
        o["SHADOWCSMDEBUG" + n] = !1,
        o["SHADOWCSMNUM_CASCADES" + n] = !1,
        o["SHADOWCSMUSESHADOWMAXZ" + n] = !1,
        o["SHADOWCSMNOBLEND" + n] = !1,
        o["SHADOWCSM_RIGHTHANDED" + n] = !1,
        o["SHADOWPCF" + n] = !1,
        o["SHADOWPCSS" + n] = !1,
        o["SHADOWPOISSON" + n] = !1,
        o["SHADOWESM" + n] = !1,
        o["SHADOWCLOSEESM" + n] = !1,
        o["SHADOWCUBE" + n] = !1,
        o["SHADOWLOWQUALITY" + n] = !1,
        o["SHADOWMEDIUMQUALITY" + n] = !1,
        t && t.receiveShadows && e.shadowsEnabled && r.shadowEnabled) {
            var l = r.getShadowGenerator();
            if (l) {
                var u = l.getShadowMap();
                u && u.renderList && u.renderList.length > 0 && (s.shadowEnabled = !0,
                l.prepareDefines(o, n))
            }
        }
        r.lightmapMode != Light.LIGHTMAP_DEFAULT ? (s.lightmapMode = !0,
        o["LIGHTMAPEXCLUDED" + n] = !0,
        o["LIGHTMAPNOSPECULAR" + n] = r.lightmapMode == Light.LIGHTMAP_SHADOWSONLY) : (o["LIGHTMAPEXCLUDED" + n] = !1,
        o["LIGHTMAPNOSPECULAR" + n] = !1)
    }
    ,
    i.PrepareDefinesForLights = function(e, t, r, n, o, a) {
        if (o === void 0 && (o = 4),
        a === void 0 && (a = !1),
        !r._areLightsDirty)
            return r._needNormals;
        var s = 0
          , l = {
            needNormals: !1,
            needRebuild: !1,
            lightmapMode: !1,
            shadowEnabled: !1,
            specularEnabled: !1
        };
        if (e.lightsEnabled && !a)
            for (var u = 0, c = t.lightSources; u < c.length; u++) {
                var h = c[u];
                if (this.PrepareDefinesForLight(e, t, h, s, r, n, l),
                s++,
                s === o)
                    break
            }
        r.SPECULARTERM = l.specularEnabled,
        r.SHADOWS = l.shadowEnabled;
        for (var f = s; f < o; f++)
            r["LIGHT" + f] !== void 0 && (r["LIGHT" + f] = !1,
            r["HEMILIGHT" + f] = !1,
            r["POINTLIGHT" + f] = !1,
            r["DIRLIGHT" + f] = !1,
            r["SPOTLIGHT" + f] = !1,
            r["SHADOW" + f] = !1,
            r["SHADOWCSM" + f] = !1,
            r["SHADOWCSMDEBUG" + f] = !1,
            r["SHADOWCSMNUM_CASCADES" + f] = !1,
            r["SHADOWCSMUSESHADOWMAXZ" + f] = !1,
            r["SHADOWCSMNOBLEND" + f] = !1,
            r["SHADOWCSM_RIGHTHANDED" + f] = !1,
            r["SHADOWPCF" + f] = !1,
            r["SHADOWPCSS" + f] = !1,
            r["SHADOWPOISSON" + f] = !1,
            r["SHADOWESM" + f] = !1,
            r["SHADOWCLOSEESM" + f] = !1,
            r["SHADOWCUBE" + f] = !1,
            r["SHADOWLOWQUALITY" + f] = !1,
            r["SHADOWMEDIUMQUALITY" + f] = !1);
        var d = e.getEngine().getCaps();
        return r.SHADOWFLOAT === void 0 && (l.needRebuild = !0),
        r.SHADOWFLOAT = l.shadowEnabled && (d.textureFloatRender && d.textureFloatLinearFiltering || d.textureHalfFloatRender && d.textureHalfFloatLinearFiltering),
        r.LIGHTMAPEXCLUDED = l.lightmapMode,
        l.needRebuild && r.rebuild(),
        l.needNormals
    }
    ,
    i.PrepareUniformsAndSamplersForLight = function(e, t, r, n, o, a) {
        o === void 0 && (o = null),
        a === void 0 && (a = !1),
        o && o.push("Light" + e),
        !a && (t.push("vLightData" + e, "vLightDiffuse" + e, "vLightSpecular" + e, "vLightDirection" + e, "vLightFalloff" + e, "vLightGround" + e, "lightMatrix" + e, "shadowsInfo" + e, "depthValues" + e),
        r.push("shadowSampler" + e),
        r.push("depthSampler" + e),
        t.push("viewFrustumZ" + e, "cascadeBlendFactor" + e, "lightSizeUVCorrection" + e, "depthCorrection" + e, "penumbraDarkness" + e, "frustumLengths" + e),
        n && (r.push("projectionLightSampler" + e),
        t.push("textureProjectionMatrix" + e)))
    }
    ,
    i.PrepareUniformsAndSamplersList = function(e, t, r, n) {
        n === void 0 && (n = 4);
        var o, a = null;
        if (e.uniformsNames) {
            var s = e;
            o = s.uniformsNames,
            a = s.uniformBuffersNames,
            t = s.samplers,
            r = s.defines,
            n = s.maxSimultaneousLights || 0
        } else
            o = e,
            t || (t = []);
        for (var l = 0; l < n && r["LIGHT" + l]; l++)
            this.PrepareUniformsAndSamplersForLight(l, o, t, r["PROJECTEDLIGHTTEXTURE" + l], a);
        r.NUM_MORPH_INFLUENCERS && o.push("morphTargetInfluences"),
        r.BAKED_VERTEX_ANIMATION_TEXTURE && (o.push("bakedVertexAnimationSettings"),
        o.push("bakedVertexAnimationTextureSizeInverted"),
        o.push("bakedVertexAnimationTime"),
        t.push("bakedVertexAnimationTexture"))
    }
    ,
    i.HandleFallbacksForShadows = function(e, t, r, n) {
        r === void 0 && (r = 4),
        n === void 0 && (n = 0);
        for (var o = 0, a = 0; a < r && e["LIGHT" + a]; a++)
            a > 0 && (o = n + a,
            t.addFallback(o, "LIGHT" + a)),
            e.SHADOWS || (e["SHADOW" + a] && t.addFallback(n, "SHADOW" + a),
            e["SHADOWPCF" + a] && t.addFallback(n, "SHADOWPCF" + a),
            e["SHADOWPCSS" + a] && t.addFallback(n, "SHADOWPCSS" + a),
            e["SHADOWPOISSON" + a] && t.addFallback(n, "SHADOWPOISSON" + a),
            e["SHADOWESM" + a] && t.addFallback(n, "SHADOWESM" + a),
            e["SHADOWCLOSEESM" + a] && t.addFallback(n, "SHADOWCLOSEESM" + a));
        return o++
    }
    ,
    i.PrepareAttributesForMorphTargetsInfluencers = function(e, t, r) {
        this._TmpMorphInfluencers.NUM_MORPH_INFLUENCERS = r,
        this.PrepareAttributesForMorphTargets(e, t, this._TmpMorphInfluencers)
    }
    ,
    i.PrepareAttributesForMorphTargets = function(e, t, r) {
        var n = r.NUM_MORPH_INFLUENCERS;
        if (n > 0 && EngineStore.LastCreatedEngine) {
            var o = EngineStore.LastCreatedEngine.getCaps().maxVertexAttribs
              , a = t.morphTargetManager;
            if (a != null && a.isUsingTextureForTargets)
                return;
            for (var s = a && a.supportsNormals && r.NORMAL, l = a && a.supportsTangents && r.TANGENT, u = a && a.supportsUVs && r.UV1, c = 0; c < n; c++)
                e.push(VertexBuffer.PositionKind + c),
                s && e.push(VertexBuffer.NormalKind + c),
                l && e.push(VertexBuffer.TangentKind + c),
                u && e.push(VertexBuffer.UVKind + "_" + c),
                e.length > o && Logger$2.Error("Cannot add more vertex attributes for mesh " + t.name)
        }
    }
    ,
    i.PrepareAttributesForBakedVertexAnimation = function(e, t, r) {
        var n = r.BAKED_VERTEX_ANIMATION_TEXTURE && r.INSTANCES;
        n && (e.push("bakedVertexAnimationSettingsInstanced"),
        e.push("bakedVertexAnimationTimeInstanced"))
    }
    ,
    i.PrepareAttributesForBones = function(e, t, r, n) {
        r.NUM_BONE_INFLUENCERS > 0 && (n.addCPUSkinningFallback(0, t),
        e.push(VertexBuffer.MatricesIndicesKind),
        e.push(VertexBuffer.MatricesWeightsKind),
        r.NUM_BONE_INFLUENCERS > 4 && (e.push(VertexBuffer.MatricesIndicesExtraKind),
        e.push(VertexBuffer.MatricesWeightsExtraKind)))
    }
    ,
    i.PrepareAttributesForInstances = function(e, t) {
        (t.INSTANCES || t.THIN_INSTANCES) && this.PushAttributesForInstances(e, !!t.PREPASS_VELOCITY)
    }
    ,
    i.PushAttributesForInstances = function(e, t) {
        t === void 0 && (t = !1),
        e.push("world0"),
        e.push("world1"),
        e.push("world2"),
        e.push("world3"),
        t && (e.push("previousWorld0"),
        e.push("previousWorld1"),
        e.push("previousWorld2"),
        e.push("previousWorld3"))
    }
    ,
    i.BindLightProperties = function(e, t, r) {
        e.transferToEffect(t, r + "")
    }
    ,
    i.BindLight = function(e, t, r, n, o, a) {
        a === void 0 && (a = !0),
        e._bindLight(t, r, n, o, a)
    }
    ,
    i.BindLights = function(e, t, r, n, o) {
        o === void 0 && (o = 4);
        for (var a = Math.min(t.lightSources.length, o), s = 0; s < a; s++) {
            var l = t.lightSources[s];
            this.BindLight(l, s, e, r, typeof n == "boolean" ? n : n.SPECULARTERM, t.receiveShadows)
        }
    }
    ,
    i.BindFogParameters = function(e, t, r, n) {
        n === void 0 && (n = !1),
        e.fogEnabled && t.applyFog && e.fogMode !== Scene.FOGMODE_NONE && (r.setFloat4("vFogInfos", e.fogMode, e.fogStart, e.fogEnd, e.fogDensity),
        n ? (e.fogColor.toLinearSpaceToRef(this._tempFogColor),
        r.setColor3("vFogColor", this._tempFogColor)) : r.setColor3("vFogColor", e.fogColor))
    }
    ,
    i.BindBonesParameters = function(e, t, r) {
        if (!(!t || !e) && (e.computeBonesUsingShaders && t._bonesComputationForcedToCPU && (e.computeBonesUsingShaders = !1),
        e.useBones && e.computeBonesUsingShaders && e.skeleton)) {
            var n = e.skeleton;
            if (n.isUsingTextureForMatrices && t.getUniformIndex("boneTextureWidth") > -1) {
                var o = n.getTransformMatrixTexture(e);
                t.setTexture("boneSampler", o),
                t.setFloat("boneTextureWidth", 4 * (n.bones.length + 1))
            } else {
                var a = n.getTransformMatrices(e);
                a && (t.setMatrices("mBones", a),
                r && e.getScene().prePassRenderer && e.getScene().prePassRenderer.getIndex(2) && (r.previousBones[e.uniqueId] || (r.previousBones[e.uniqueId] = a.slice()),
                t.setMatrices("mPreviousBones", r.previousBones[e.uniqueId]),
                i._CopyBonesTransformationMatrices(a, r.previousBones[e.uniqueId])))
            }
        }
    }
    ,
    i._CopyBonesTransformationMatrices = function(e, t) {
        return t.set(e),
        t
    }
    ,
    i.BindMorphTargetParameters = function(e, t) {
        var r = e.morphTargetManager;
        !e || !r || t.setFloatArray("morphTargetInfluences", r.influences)
    }
    ,
    i.BindLogDepth = function(e, t, r) {
        if (!e || e.LOGARITHMICDEPTH) {
            var n = r.activeCamera;
            n.mode === Camera$1.ORTHOGRAPHIC_CAMERA && Logger$2.Error("Logarithmic depth is not compatible with orthographic cameras!", 20),
            t.setFloat("logarithmicDepthConstant", 2 / (Math.log(n.maxZ + 1) / Math.LN2))
        }
    }
    ,
    i.BindClipPlane = function(e, t) {
        ThinMaterialHelper.BindClipPlane(e, t)
    }
    ,
    i._TmpMorphInfluencers = {
        NUM_MORPH_INFLUENCERS: 0
    },
    i._tempFogColor = Color3.Black(),
    i
}()
  , MaterialStencilState = function() {
    function i() {
        this.reset()
    }
    return i.prototype.reset = function() {
        this.enabled = !1,
        this.mask = 255,
        this.func = 519,
        this.funcRef = 1,
        this.funcMask = 255,
        this.opStencilFail = 7680,
        this.opDepthFail = 7680,
        this.opStencilDepthPass = 7681
    }
    ,
    Object.defineProperty(i.prototype, "func", {
        get: function() {
            return this._func
        },
        set: function(e) {
            this._func = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "funcRef", {
        get: function() {
            return this._funcRef
        },
        set: function(e) {
            this._funcRef = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "funcMask", {
        get: function() {
            return this._funcMask
        },
        set: function(e) {
            this._funcMask = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "opStencilFail", {
        get: function() {
            return this._opStencilFail
        },
        set: function(e) {
            this._opStencilFail = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "opDepthFail", {
        get: function() {
            return this._opDepthFail
        },
        set: function(e) {
            this._opDepthFail = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "opStencilDepthPass", {
        get: function() {
            return this._opStencilDepthPass
        },
        set: function(e) {
            this._opStencilDepthPass = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "mask", {
        get: function() {
            return this._mask
        },
        set: function(e) {
            this._mask = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "enabled", {
        get: function() {
            return this._enabled
        },
        set: function(e) {
            this._enabled = e
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.getClassName = function() {
        return "MaterialStencilState"
    }
    ,
    i.prototype.copyTo = function(e) {
        SerializationHelper.Clone(function() {
            return e
        }, this)
    }
    ,
    i.prototype.serialize = function() {
        return SerializationHelper.Serialize(this)
    }
    ,
    i.prototype.parse = function(e, t, r) {
        var n = this;
        SerializationHelper.Parse(function() {
            return n
        }, e, t, r)
    }
    ,
    __decorate([serialize()], i.prototype, "func", null),
    __decorate([serialize()], i.prototype, "funcRef", null),
    __decorate([serialize()], i.prototype, "funcMask", null),
    __decorate([serialize()], i.prototype, "opStencilFail", null),
    __decorate([serialize()], i.prototype, "opDepthFail", null),
    __decorate([serialize()], i.prototype, "opStencilDepthPass", null),
    __decorate([serialize()], i.prototype, "mask", null),
    __decorate([serialize()], i.prototype, "enabled", null),
    i
}()
  , Material = function() {
    function i(e, t, r) {
        this.shadowDepthWrapper = null,
        this.allowShaderHotSwapping = !0,
        this.metadata = null,
        this.reservedDataStore = null,
        this.checkReadyOnEveryCall = !1,
        this.checkReadyOnlyOnce = !1,
        this.state = "",
        this._alpha = 1,
        this._backFaceCulling = !0,
        this._cullBackFaces = !0,
        this.onCompiled = null,
        this.onError = null,
        this.getRenderTargetTextures = null,
        this.doNotSerialize = !1,
        this._storeEffectOnSubMeshes = !1,
        this.animations = null,
        this.onDisposeObservable = new Observable,
        this._onDisposeObserver = null,
        this._onUnBindObservable = null,
        this._onBindObserver = null,
        this._alphaMode = 2,
        this._needDepthPrePass = !1,
        this.disableDepthWrite = !1,
        this.disableColorWrite = !1,
        this.forceDepthWrite = !1,
        this.depthFunction = 0,
        this.separateCullingPass = !1,
        this._fogEnabled = !0,
        this.pointSize = 1,
        this.zOffset = 0,
        this.zOffsetUnits = 0,
        this.stencil = new MaterialStencilState,
        this._useUBO = !1,
        this._fillMode = i.TriangleFillMode,
        this._cachedDepthWriteState = !1,
        this._cachedColorWriteState = !1,
        this._cachedDepthFunctionState = 0,
        this._indexInSceneMaterialArray = -1,
        this.meshMap = null,
        this._parentContainer = null,
        this._forceAlphaTest = !1,
        this._transparencyMode = null,
        this.name = e,
        this._scene = t || EngineStore.LastCreatedScene,
        this.id = e || Tools.RandomId(),
        this.uniqueId = this._scene.getUniqueId(),
        this._materialContext = this._scene.getEngine().createMaterialContext(),
        this._drawWrapper = new DrawWrapper(this._scene.getEngine(),!1),
        this._drawWrapper.materialContext = this._materialContext,
        this._scene.useRightHandedSystem ? this.sideOrientation = i.ClockWiseSideOrientation : this.sideOrientation = i.CounterClockWiseSideOrientation,
        this._uniformBuffer = new UniformBuffer(this._scene.getEngine(),void 0,void 0,e),
        this._useUBO = this.getScene().getEngine().supportsUniformBuffers,
        r || this._scene.addMaterial(this),
        this._scene.useMaterialMeshMap && (this.meshMap = {})
    }
    return Object.defineProperty(i.prototype, "canRenderToMRT", {
        get: function() {
            return !1
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "alpha", {
        get: function() {
            return this._alpha
        },
        set: function(e) {
            this._alpha !== e && (this._alpha = e,
            this.markAsDirty(i.MiscDirtyFlag))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "backFaceCulling", {
        get: function() {
            return this._backFaceCulling
        },
        set: function(e) {
            this._backFaceCulling !== e && (this._backFaceCulling = e,
            this.markAsDirty(i.TextureDirtyFlag))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "cullBackFaces", {
        get: function() {
            return this._cullBackFaces
        },
        set: function(e) {
            this._cullBackFaces !== e && (this._cullBackFaces = e,
            this.markAsDirty(i.TextureDirtyFlag))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "hasRenderTargetTextures", {
        get: function() {
            return !1
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "onDispose", {
        set: function(e) {
            this._onDisposeObserver && this.onDisposeObservable.remove(this._onDisposeObserver),
            this._onDisposeObserver = this.onDisposeObservable.add(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "onBindObservable", {
        get: function() {
            return this._onBindObservable || (this._onBindObservable = new Observable),
            this._onBindObservable
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "onBind", {
        set: function(e) {
            this._onBindObserver && this.onBindObservable.remove(this._onBindObserver),
            this._onBindObserver = this.onBindObservable.add(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "onUnBindObservable", {
        get: function() {
            return this._onUnBindObservable || (this._onUnBindObservable = new Observable),
            this._onUnBindObservable
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "onEffectCreatedObservable", {
        get: function() {
            return this._onEffectCreatedObservable || (this._onEffectCreatedObservable = new Observable),
            this._onEffectCreatedObservable
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "alphaMode", {
        get: function() {
            return this._alphaMode
        },
        set: function(e) {
            this._alphaMode !== e && (this._alphaMode = e,
            this.markAsDirty(i.TextureDirtyFlag))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "needDepthPrePass", {
        get: function() {
            return this._needDepthPrePass
        },
        set: function(e) {
            this._needDepthPrePass !== e && (this._needDepthPrePass = e,
            this._needDepthPrePass && (this.checkReadyOnEveryCall = !0))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "isPrePassCapable", {
        get: function() {
            return !1
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "fogEnabled", {
        get: function() {
            return this._fogEnabled
        },
        set: function(e) {
            this._fogEnabled !== e && (this._fogEnabled = e,
            this.markAsDirty(i.MiscDirtyFlag))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "wireframe", {
        get: function() {
            switch (this._fillMode) {
            case i.WireFrameFillMode:
            case i.LineListDrawMode:
            case i.LineLoopDrawMode:
            case i.LineStripDrawMode:
                return !0
            }
            return this._scene.forceWireframe
        },
        set: function(e) {
            this.fillMode = e ? i.WireFrameFillMode : i.TriangleFillMode
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "pointsCloud", {
        get: function() {
            switch (this._fillMode) {
            case i.PointFillMode:
            case i.PointListDrawMode:
                return !0
            }
            return this._scene.forcePointsCloud
        },
        set: function(e) {
            this.fillMode = e ? i.PointFillMode : i.TriangleFillMode
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "fillMode", {
        get: function() {
            return this._fillMode
        },
        set: function(e) {
            this._fillMode !== e && (this._fillMode = e,
            this.markAsDirty(i.MiscDirtyFlag))
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype._getDrawWrapper = function() {
        return this._drawWrapper
    }
    ,
    i.prototype._setDrawWrapper = function(e) {
        this._drawWrapper = e
    }
    ,
    i.prototype.toString = function(e) {
        var t = "Name: " + this.name;
        return t
    }
    ,
    i.prototype.getClassName = function() {
        return "Material"
    }
    ,
    Object.defineProperty(i.prototype, "isFrozen", {
        get: function() {
            return this.checkReadyOnlyOnce
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.freeze = function() {
        this.markDirty(),
        this.checkReadyOnlyOnce = !0
    }
    ,
    i.prototype.unfreeze = function() {
        this.markDirty(),
        this.checkReadyOnlyOnce = !1
    }
    ,
    i.prototype.isReady = function(e, t) {
        return !0
    }
    ,
    i.prototype.isReadyForSubMesh = function(e, t, r) {
        return !1
    }
    ,
    i.prototype.getEffect = function() {
        return this._drawWrapper.effect
    }
    ,
    i.prototype.getScene = function() {
        return this._scene
    }
    ,
    Object.defineProperty(i.prototype, "transparencyMode", {
        get: function() {
            return this._transparencyMode
        },
        set: function(e) {
            this._transparencyMode !== e && (this._transparencyMode = e,
            this._forceAlphaTest = e === i.MATERIAL_ALPHATESTANDBLEND,
            this._markAllSubMeshesAsTexturesAndMiscDirty())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "_disableAlphaBlending", {
        get: function() {
            return this._transparencyMode === i.MATERIAL_OPAQUE || this._transparencyMode === i.MATERIAL_ALPHATEST
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.needAlphaBlending = function() {
        return this._disableAlphaBlending ? !1 : this.alpha < 1
    }
    ,
    i.prototype.needAlphaBlendingForMesh = function(e) {
        return this._disableAlphaBlending && e.visibility >= 1 ? !1 : this.needAlphaBlending() || e.visibility < 1 || e.hasVertexAlpha
    }
    ,
    i.prototype.needAlphaTesting = function() {
        return !!this._forceAlphaTest
    }
    ,
    i.prototype._shouldTurnAlphaTestOn = function(e) {
        return !this.needAlphaBlendingForMesh(e) && this.needAlphaTesting()
    }
    ,
    i.prototype.getAlphaTestTexture = function() {
        return null
    }
    ,
    i.prototype.markDirty = function() {
        for (var e = this.getScene().meshes, t = 0, r = e; t < r.length; t++) {
            var n = r[t];
            if (!!n.subMeshes)
                for (var o = 0, a = n.subMeshes; o < a.length; o++) {
                    var s = a[o];
                    s.getMaterial() === this && (!s.effect || (s.effect._wasPreviouslyReady = !1))
                }
        }
    }
    ,
    i.prototype._preBind = function(e, t) {
        t === void 0 && (t = null);
        var r = this._scene.getEngine()
          , n = t == null ? this.sideOrientation : t
          , o = n === i.ClockWiseSideOrientation;
        return r.enableEffect(e || this._getDrawWrapper()),
        r.setState(this.backFaceCulling, this.zOffset, !1, o, this.cullBackFaces, this.stencil, this.zOffsetUnits),
        o
    }
    ,
    i.prototype.bind = function(e, t) {}
    ,
    i.prototype.bindForSubMesh = function(e, t, r) {}
    ,
    i.prototype.bindOnlyWorldMatrix = function(e) {}
    ,
    i.prototype.bindView = function(e) {
        this._useUBO ? this._needToBindSceneUbo = !0 : e.setMatrix("view", this.getScene().getViewMatrix())
    }
    ,
    i.prototype.bindViewProjection = function(e) {
        this._useUBO ? this._needToBindSceneUbo = !0 : (e.setMatrix("viewProjection", this.getScene().getTransformMatrix()),
        e.setMatrix("projection", this.getScene().getProjectionMatrix()))
    }
    ,
    i.prototype.bindEyePosition = function(e, t) {
        this._useUBO ? this._needToBindSceneUbo = !0 : this._scene.bindEyePosition(e, t)
    }
    ,
    i.prototype._afterBind = function(e, t) {
        if (t === void 0 && (t = null),
        this._scene._cachedMaterial = this,
        this._needToBindSceneUbo && t && (this._needToBindSceneUbo = !1,
        MaterialHelper.BindSceneUniformBuffer(t, this.getScene().getSceneUniformBuffer()),
        this._scene.finalizeSceneUbo()),
        e ? this._scene._cachedVisibility = e.visibility : this._scene._cachedVisibility = 1,
        this._onBindObservable && e && this._onBindObservable.notifyObservers(e),
        this.disableDepthWrite) {
            var r = this._scene.getEngine();
            this._cachedDepthWriteState = r.getDepthWrite(),
            r.setDepthWrite(!1)
        }
        if (this.disableColorWrite) {
            var r = this._scene.getEngine();
            this._cachedColorWriteState = r.getColorWrite(),
            r.setColorWrite(!1)
        }
        if (this.depthFunction !== 0) {
            var r = this._scene.getEngine();
            this._cachedDepthFunctionState = r.getDepthFunction() || 0,
            r.setDepthFunction(this.depthFunction)
        }
    }
    ,
    i.prototype.unbind = function() {
        if (this._onUnBindObservable && this._onUnBindObservable.notifyObservers(this),
        this.depthFunction !== 0) {
            var e = this._scene.getEngine();
            e.setDepthFunction(this._cachedDepthFunctionState)
        }
        if (this.disableDepthWrite) {
            var e = this._scene.getEngine();
            e.setDepthWrite(this._cachedDepthWriteState)
        }
        if (this.disableColorWrite) {
            var e = this._scene.getEngine();
            e.setColorWrite(this._cachedColorWriteState)
        }
    }
    ,
    i.prototype.getActiveTextures = function() {
        return []
    }
    ,
    i.prototype.hasTexture = function(e) {
        return !1
    }
    ,
    i.prototype.clone = function(e) {
        return null
    }
    ,
    i.prototype.getBindedMeshes = function() {
        var e = this;
        if (this.meshMap) {
            var t = new Array;
            for (var r in this.meshMap) {
                var n = this.meshMap[r];
                n && t.push(n)
            }
            return t
        } else {
            var o = this._scene.meshes;
            return o.filter(function(a) {
                return a.material === e
            })
        }
    }
    ,
    i.prototype.forceCompilation = function(e, t, r, n) {
        var o = this
          , a = __assign({
            clipPlane: !1,
            useInstances: !1
        }, r)
          , s = this.getScene()
          , l = this.allowShaderHotSwapping;
        this.allowShaderHotSwapping = !1;
        var u = function() {
            if (!(!o._scene || !o._scene.getEngine())) {
                var c = s.clipPlane;
                if (a.clipPlane && (s.clipPlane = new Plane(0,0,0,1)),
                o._storeEffectOnSubMeshes) {
                    var h = !0
                      , f = null;
                    if (e.subMeshes) {
                        var d = new SubMesh(0,0,0,0,0,e,void 0,!1,!1);
                        d.materialDefines && (d.materialDefines._renderId = -1),
                        o.isReadyForSubMesh(e, d, a.useInstances) || (d.effect && d.effect.getCompilationError() && d.effect.allFallbacksProcessed() ? f = d.effect.getCompilationError() : (h = !1,
                        setTimeout(u, 16)))
                    }
                    h && (o.allowShaderHotSwapping = l,
                    f && n && n(f),
                    t && t(o))
                } else
                    o.isReady() ? (o.allowShaderHotSwapping = l,
                    t && t(o)) : setTimeout(u, 16);
                a.clipPlane && (s.clipPlane = c)
            }
        };
        u()
    }
    ,
    i.prototype.forceCompilationAsync = function(e, t) {
        var r = this;
        return new Promise(function(n, o) {
            r.forceCompilation(e, function() {
                n()
            }, t, function(a) {
                o(a)
            })
        }
        )
    }
    ,
    i.prototype.markAsDirty = function(e) {
        this.getScene().blockMaterialDirtyMechanism || (i._DirtyCallbackArray.length = 0,
        e & i.TextureDirtyFlag && i._DirtyCallbackArray.push(i._TextureDirtyCallBack),
        e & i.LightDirtyFlag && i._DirtyCallbackArray.push(i._LightsDirtyCallBack),
        e & i.FresnelDirtyFlag && i._DirtyCallbackArray.push(i._FresnelDirtyCallBack),
        e & i.AttributesDirtyFlag && i._DirtyCallbackArray.push(i._AttributeDirtyCallBack),
        e & i.MiscDirtyFlag && i._DirtyCallbackArray.push(i._MiscDirtyCallBack),
        e & i.PrePassDirtyFlag && i._DirtyCallbackArray.push(i._PrePassDirtyCallBack),
        i._DirtyCallbackArray.length && this._markAllSubMeshesAsDirty(i._RunDirtyCallBacks),
        this.getScene().resetCachedMaterial())
    }
    ,
    i.prototype._markAllSubMeshesAsDirty = function(e) {
        if (!this.getScene().blockMaterialDirtyMechanism)
            for (var t = this.getScene().meshes, r = 0, n = t; r < n.length; r++) {
                var o = n[r];
                if (!!o.subMeshes)
                    for (var a = 0, s = o.subMeshes; a < s.length; a++) {
                        var l = s[a];
                        if (l.getMaterial() === this)
                            for (var u = 0, c = l._drawWrappers; u < c.length; u++) {
                                var h = c[u];
                                !h || !h.defines || !h.defines.markAllAsDirty || this._materialContext === h.materialContext && e(h.defines)
                            }
                    }
            }
    }
    ,
    i.prototype._markScenePrePassDirty = function() {
        if (!this.getScene().blockMaterialDirtyMechanism) {
            var e = this.getScene().enablePrePassRenderer();
            e && e.markAsDirty()
        }
    }
    ,
    i.prototype._markAllSubMeshesAsAllDirty = function() {
        this._markAllSubMeshesAsDirty(i._AllDirtyCallBack)
    }
    ,
    i.prototype._markAllSubMeshesAsImageProcessingDirty = function() {
        this._markAllSubMeshesAsDirty(i._ImageProcessingDirtyCallBack)
    }
    ,
    i.prototype._markAllSubMeshesAsTexturesDirty = function() {
        this._markAllSubMeshesAsDirty(i._TextureDirtyCallBack)
    }
    ,
    i.prototype._markAllSubMeshesAsFresnelDirty = function() {
        this._markAllSubMeshesAsDirty(i._FresnelDirtyCallBack)
    }
    ,
    i.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function() {
        this._markAllSubMeshesAsDirty(i._FresnelAndMiscDirtyCallBack)
    }
    ,
    i.prototype._markAllSubMeshesAsLightsDirty = function() {
        this._markAllSubMeshesAsDirty(i._LightsDirtyCallBack)
    }
    ,
    i.prototype._markAllSubMeshesAsAttributesDirty = function() {
        this._markAllSubMeshesAsDirty(i._AttributeDirtyCallBack)
    }
    ,
    i.prototype._markAllSubMeshesAsMiscDirty = function() {
        this._markAllSubMeshesAsDirty(i._MiscDirtyCallBack)
    }
    ,
    i.prototype._markAllSubMeshesAsPrePassDirty = function() {
        this._markAllSubMeshesAsDirty(i._MiscDirtyCallBack)
    }
    ,
    i.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function() {
        this._markAllSubMeshesAsDirty(i._TextureAndMiscDirtyCallBack)
    }
    ,
    i.prototype.setPrePassRenderer = function(e) {
        return !1
    }
    ,
    i.prototype.dispose = function(e, t, r) {
        var n = this.getScene();
        if (n.stopAnimation(this),
        n.freeProcessedMaterials(),
        n.removeMaterial(this),
        this._parentContainer) {
            var o = this._parentContainer.materials.indexOf(this);
            o > -1 && this._parentContainer.materials.splice(o, 1),
            this._parentContainer = null
        }
        if (r !== !0)
            if (this.meshMap)
                for (var a in this.meshMap) {
                    var s = this.meshMap[a];
                    s && (s.material = null,
                    this.releaseVertexArrayObject(s, e))
                }
            else
                for (var l = n.meshes, u = 0, c = l; u < c.length; u++) {
                    var s = c[u];
                    s.material === this && !s.sourceMesh && (s.material = null,
                    this.releaseVertexArrayObject(s, e))
                }
        this._uniformBuffer.dispose(),
        e && this._drawWrapper.effect && (this._storeEffectOnSubMeshes || this._drawWrapper.effect.dispose(),
        this._drawWrapper.effect = null),
        this.metadata = null,
        this.onDisposeObservable.notifyObservers(this),
        this.onDisposeObservable.clear(),
        this._onBindObservable && this._onBindObservable.clear(),
        this._onUnBindObservable && this._onUnBindObservable.clear(),
        this._onEffectCreatedObservable && this._onEffectCreatedObservable.clear()
    }
    ,
    i.prototype.releaseVertexArrayObject = function(e, t) {
        if (e.geometry) {
            var r = e.geometry;
            if (this._storeEffectOnSubMeshes)
                for (var n = 0, o = e.subMeshes; n < o.length; n++) {
                    var a = o[n];
                    r._releaseVertexArrayObject(a.effect),
                    t && a.effect && a.effect.dispose()
                }
            else
                r._releaseVertexArrayObject(this._drawWrapper.effect)
        }
    }
    ,
    i.prototype.serialize = function() {
        var e = SerializationHelper.Serialize(this);
        return e.stencil = this.stencil.serialize(),
        e
    }
    ,
    i.Parse = function(e, t, r) {
        if (!e.customType)
            e.customType = "BABYLON.StandardMaterial";
        else if (e.customType === "BABYLON.PBRMaterial" && e.overloadedAlbedo && (e.customType = "BABYLON.LegacyPBRMaterial",
        !BABYLON.LegacyPBRMaterial))
            return Logger$2.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library."),
            null;
        var n = Tools.Instantiate(e.customType);
        return n.Parse(e, t, r)
    }
    ,
    i.TriangleFillMode = 0,
    i.WireFrameFillMode = 1,
    i.PointFillMode = 2,
    i.PointListDrawMode = 3,
    i.LineListDrawMode = 4,
    i.LineLoopDrawMode = 5,
    i.LineStripDrawMode = 6,
    i.TriangleStripDrawMode = 7,
    i.TriangleFanDrawMode = 8,
    i.ClockWiseSideOrientation = 0,
    i.CounterClockWiseSideOrientation = 1,
    i.TextureDirtyFlag = 1,
    i.LightDirtyFlag = 2,
    i.FresnelDirtyFlag = 4,
    i.AttributesDirtyFlag = 8,
    i.MiscDirtyFlag = 16,
    i.PrePassDirtyFlag = 32,
    i.AllDirtyFlag = 63,
    i.MATERIAL_OPAQUE = 0,
    i.MATERIAL_ALPHATEST = 1,
    i.MATERIAL_ALPHABLEND = 2,
    i.MATERIAL_ALPHATESTANDBLEND = 3,
    i.MATERIAL_NORMALBLENDMETHOD_WHITEOUT = 0,
    i.MATERIAL_NORMALBLENDMETHOD_RNM = 1,
    i._AllDirtyCallBack = function(e) {
        return e.markAllAsDirty()
    }
    ,
    i._ImageProcessingDirtyCallBack = function(e) {
        return e.markAsImageProcessingDirty()
    }
    ,
    i._TextureDirtyCallBack = function(e) {
        return e.markAsTexturesDirty()
    }
    ,
    i._FresnelDirtyCallBack = function(e) {
        return e.markAsFresnelDirty()
    }
    ,
    i._MiscDirtyCallBack = function(e) {
        return e.markAsMiscDirty()
    }
    ,
    i._PrePassDirtyCallBack = function(e) {
        return e.markAsPrePassDirty()
    }
    ,
    i._LightsDirtyCallBack = function(e) {
        return e.markAsLightDirty()
    }
    ,
    i._AttributeDirtyCallBack = function(e) {
        return e.markAsAttributesDirty()
    }
    ,
    i._FresnelAndMiscDirtyCallBack = function(e) {
        i._FresnelDirtyCallBack(e),
        i._MiscDirtyCallBack(e)
    }
    ,
    i._TextureAndMiscDirtyCallBack = function(e) {
        i._TextureDirtyCallBack(e),
        i._MiscDirtyCallBack(e)
    }
    ,
    i._DirtyCallbackArray = [],
    i._RunDirtyCallBacks = function(e) {
        for (var t = 0, r = i._DirtyCallbackArray; t < r.length; t++) {
            var n = r[t];
            n(e)
        }
    }
    ,
    __decorate([serialize()], i.prototype, "id", void 0),
    __decorate([serialize()], i.prototype, "uniqueId", void 0),
    __decorate([serialize()], i.prototype, "name", void 0),
    __decorate([serialize()], i.prototype, "metadata", void 0),
    __decorate([serialize()], i.prototype, "checkReadyOnEveryCall", void 0),
    __decorate([serialize()], i.prototype, "checkReadyOnlyOnce", void 0),
    __decorate([serialize()], i.prototype, "state", void 0),
    __decorate([serialize("alpha")], i.prototype, "_alpha", void 0),
    __decorate([serialize("backFaceCulling")], i.prototype, "_backFaceCulling", void 0),
    __decorate([serialize("cullBackFaces")], i.prototype, "_cullBackFaces", void 0),
    __decorate([serialize()], i.prototype, "sideOrientation", void 0),
    __decorate([serialize("alphaMode")], i.prototype, "_alphaMode", void 0),
    __decorate([serialize()], i.prototype, "_needDepthPrePass", void 0),
    __decorate([serialize()], i.prototype, "disableDepthWrite", void 0),
    __decorate([serialize()], i.prototype, "disableColorWrite", void 0),
    __decorate([serialize()], i.prototype, "forceDepthWrite", void 0),
    __decorate([serialize()], i.prototype, "depthFunction", void 0),
    __decorate([serialize()], i.prototype, "separateCullingPass", void 0),
    __decorate([serialize("fogEnabled")], i.prototype, "_fogEnabled", void 0),
    __decorate([serialize()], i.prototype, "pointSize", void 0),
    __decorate([serialize()], i.prototype, "zOffset", void 0),
    __decorate([serialize()], i.prototype, "zOffsetUnits", void 0),
    __decorate([serialize()], i.prototype, "pointsCloud", null),
    __decorate([serialize()], i.prototype, "fillMode", null),
    __decorate([serialize()], i.prototype, "transparencyMode", null),
    i
}()
  , MultiMaterial = function(i) {
    __extends(e, i);
    function e(t, r) {
        var n = i.call(this, t, r, !0) || this;
        return r.multiMaterials.push(n),
        n.subMaterials = new Array,
        n._storeEffectOnSubMeshes = !0,
        n
    }
    return Object.defineProperty(e.prototype, "subMaterials", {
        get: function() {
            return this._subMaterials
        },
        set: function(t) {
            this._subMaterials = t,
            this._hookArray(t)
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getChildren = function() {
        return this.subMaterials
    }
    ,
    e.prototype._hookArray = function(t) {
        var r = this
          , n = t.push;
        t.push = function() {
            for (var a = [], s = 0; s < arguments.length; s++)
                a[s] = arguments[s];
            var l = n.apply(t, a);
            return r._markAllSubMeshesAsTexturesDirty(),
            l
        }
        ;
        var o = t.splice;
        t.splice = function(a, s) {
            var l = o.apply(t, [a, s]);
            return r._markAllSubMeshesAsTexturesDirty(),
            l
        }
    }
    ,
    e.prototype.getSubMaterial = function(t) {
        return t < 0 || t >= this.subMaterials.length ? this.getScene().defaultMaterial : this.subMaterials[t]
    }
    ,
    e.prototype.getActiveTextures = function() {
        var t;
        return (t = i.prototype.getActiveTextures.call(this)).concat.apply(t, this.subMaterials.map(function(r) {
            return r ? r.getActiveTextures() : []
        }))
    }
    ,
    e.prototype.hasTexture = function(t) {
        var r;
        if (i.prototype.hasTexture.call(this, t))
            return !0;
        for (var n = 0; n < this.subMaterials.length; n++)
            if (!((r = this.subMaterials[n]) === null || r === void 0) && r.hasTexture(t))
                return !0;
        return !1
    }
    ,
    e.prototype.getClassName = function() {
        return "MultiMaterial"
    }
    ,
    e.prototype.isReadyForSubMesh = function(t, r, n) {
        for (var o = 0; o < this.subMaterials.length; o++) {
            var a = this.subMaterials[o];
            if (a) {
                if (a._storeEffectOnSubMeshes) {
                    if (!a.isReadyForSubMesh(t, r, n))
                        return !1;
                    continue
                }
                if (!a.isReady(t))
                    return !1
            }
        }
        return !0
    }
    ,
    e.prototype.clone = function(t, r) {
        for (var n = new e(t,this.getScene()), o = 0; o < this.subMaterials.length; o++) {
            var a = null
              , s = this.subMaterials[o];
            r && s ? a = s.clone(t + "-" + s.name) : a = this.subMaterials[o],
            n.subMaterials.push(a)
        }
        return n
    }
    ,
    e.prototype.serialize = function() {
        var t = {};
        t.name = this.name,
        t.id = this.id,
        Tags && (t.tags = Tags.GetTags(this)),
        t.materials = [];
        for (var r = 0; r < this.subMaterials.length; r++) {
            var n = this.subMaterials[r];
            n ? t.materials.push(n.id) : t.materials.push(null)
        }
        return t
    }
    ,
    e.prototype.dispose = function(t, r, n) {
        var o = this.getScene();
        if (!!o) {
            if (n)
                for (var s = 0; s < this.subMaterials.length; s++) {
                    var a = this.subMaterials[s];
                    a && a.dispose(t, r)
                }
            var s = o.multiMaterials.indexOf(this);
            s >= 0 && o.multiMaterials.splice(s, 1),
            i.prototype.dispose.call(this, t, r)
        }
    }
    ,
    e.ParseMultiMaterial = function(t, r) {
        var n = new e(t.name,r);
        n.id = t.id,
        Tags && Tags.AddTagsTo(n, t.tags);
        for (var o = 0; o < t.materials.length; o++) {
            var a = t.materials[o];
            a ? n.subMaterials.push(r.getLastMaterialById(a)) : n.subMaterials.push(null)
        }
        return n
    }
    ,
    e
}(Material);
RegisterClass("BABYLON.MultiMaterial", MultiMaterial);
var MeshLODLevel = function() {
    function i(e, t) {
        this.distanceOrScreenCoverage = e,
        this.mesh = t
    }
    return i
}()
  , _injectLTSMesh = function(i) {
    i.prototype.setMaterialByID = function(e) {
        return this.setMaterialById(e)
    }
    ,
    i.CreateDisc = i.CreateDisc || function() {
        throw _WarnImport("MeshBuilder")
    }
    ,
    i.CreateBox = i.CreateBox || function() {
        throw _WarnImport("MeshBuilder")
    }
    ,
    i.CreateSphere = i.CreateSphere || function() {
        throw _WarnImport("MeshBuilder")
    }
    ,
    i.CreateCylinder = i.CreateCylinder || function() {
        throw _WarnImport("MeshBuilder")
    }
    ,
    i.CreateTorusKnot = i.CreateTorusKnot || function() {
        throw _WarnImport("MeshBuilder")
    }
    ,
    i.CreateTorus = i.CreateTorus || function() {
        throw _WarnImport("MeshBuilder")
    }
    ,
    i.CreatePlane = i.CreatePlane || function() {
        throw _WarnImport("MeshBuilder")
    }
    ,
    i.CreateGround = i.CreateGround || function() {
        throw _WarnImport("MeshBuilder")
    }
    ,
    i.CreateTiledGround = i.CreateTiledGround || function() {
        throw _WarnImport("MeshBuilder")
    }
    ,
    i.CreateGroundFromHeightMap = i.CreateGroundFromHeightMap || function() {
        throw _WarnImport("MeshBuilder")
    }
    ,
    i.CreateTube = i.CreateTube || function() {
        throw _WarnImport("MeshBuilder")
    }
    ,
    i.CreatePolyhedron = i.CreatePolyhedron || function() {
        throw _WarnImport("MeshBuilder")
    }
    ,
    i.CreateIcoSphere = i.CreateIcoSphere || function() {
        throw _WarnImport("MeshBuilder")
    }
    ,
    i.CreateDecal = i.CreateDecal || function() {
        throw _WarnImport("MeshBuilder")
    }
    ,
    i.CreateCapsule = i.CreateCapsule || function() {
        throw _WarnImport("MeshBuilder")
    }
    ,
    i.ExtendToGoldberg = i.ExtendToGoldberg || function() {
        throw _WarnImport("MeshBuilder")
    }
}
  , _CreationDataStorage = function() {
    function i() {}
    return i
}()
  , _InstanceDataStorage = function() {
    function i() {
        this.visibleInstances = {},
        this.batchCache = new _InstancesBatch,
        this.batchCacheReplacementModeInFrozenMode = new _InstancesBatch,
        this.instancesBufferSize = 32 * 16 * 4
    }
    return i
}()
  , _InstancesBatch = function() {
    function i() {
        this.mustReturn = !1,
        this.visibleInstances = new Array,
        this.renderSelf = new Array,
        this.hardwareInstancedRendering = new Array
    }
    return i
}()
  , _ThinInstanceDataStorage = function() {
    function i() {
        this.instancesCount = 0,
        this.matrixBuffer = null,
        this.previousMatrixBuffer = null,
        this.matrixBufferSize = 32 * 16,
        this.matrixData = null,
        this.boundingVectors = [],
        this.worldMatrices = null
    }
    return i
}()
  , _InternalMeshDataInfo = function() {
    function i() {
        this._areNormalsFrozen = !1,
        this._source = null,
        this.meshMap = null,
        this._preActivateId = -1,
        this._LODLevels = new Array,
        this._useLODScreenCoverage = !1,
        this._effectiveMaterial = null,
        this._forcedInstanceCount = 0
    }
    return i
}()
  , Mesh = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a, s) {
        r === void 0 && (r = null),
        n === void 0 && (n = null),
        o === void 0 && (o = null),
        s === void 0 && (s = !0);
        var l = i.call(this, t, r) || this;
        if (l._internalMeshDataInfo = new _InternalMeshDataInfo,
        l.delayLoadState = 0,
        l.instances = new Array,
        l._creationDataStorage = null,
        l._geometry = null,
        l._instanceDataStorage = new _InstanceDataStorage,
        l._thinInstanceDataStorage = new _ThinInstanceDataStorage,
        l._shouldGenerateFlatShading = !1,
        l._originalBuilderSideOrientation = e.DEFAULTSIDE,
        l.overrideMaterialSideOrientation = null,
        l.ignoreCameraMaxZ = !1,
        r = l.getScene(),
        o) {
            if (o._geometry && o._geometry.applyToMesh(l),
            DeepCopier.DeepCopy(o, l, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata", "morphTargetManager", "hasInstances", "source", "worldMatrixInstancedBuffer", "previousWorldMatrixInstancedBuffer", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen", "facetNb", "isFacetDataEnabled", "lightSources", "useBones", "isAnInstance", "collider", "edgesRenderer", "forward", "up", "right", "absolutePosition", "absoluteScaling", "absoluteRotationQuaternion", "isWorldMatrixFrozen", "nonUniformScaling", "behaviors", "worldMatrixFromCache", "hasThinInstances", "cloneMeshMap", "hasBoundingInfo"], ["_poseMatrix"]),
            l._internalMeshDataInfo._source = o,
            r.useClonedMeshMap && (o._internalMeshDataInfo.meshMap || (o._internalMeshDataInfo.meshMap = {}),
            o._internalMeshDataInfo.meshMap[l.uniqueId] = l),
            l._originalBuilderSideOrientation = o._originalBuilderSideOrientation,
            l._creationDataStorage = o._creationDataStorage,
            o._ranges) {
                var u = o._ranges;
                for (var t in u)
                    !u.hasOwnProperty(t) || !u[t] || l.createAnimationRange(t, u[t].from, u[t].to)
            }
            o.metadata && o.metadata.clone ? l.metadata = o.metadata.clone() : l.metadata = o.metadata,
            Tags && Tags.HasTags(o) && Tags.AddTagsTo(l, Tags.GetTags(o, !0)),
            l.setEnabled(o.isEnabled()),
            l.parent = o.parent,
            l.setPivotMatrix(o.getPivotMatrix()),
            l.id = t + "." + o.id,
            l.material = o.material;
            var c;
            if (!a)
                for (var h = o.getDescendants(!0), f = 0; f < h.length; f++) {
                    var d = h[f];
                    d.clone && d.clone(t + "." + d.name, l)
                }
            if (o.morphTargetManager && (l.morphTargetManager = o.morphTargetManager),
            r.getPhysicsEngine) {
                var _ = r.getPhysicsEngine();
                if (s && _) {
                    var g = _.getImpostorForPhysicsObject(o);
                    g && (l.physicsImpostor = g.clone(l))
                }
            }
            for (c = 0; c < r.particleSystems.length; c++) {
                var m = r.particleSystems[c];
                m.emitter === o && m.clone(m.name, l)
            }
            l.refreshBoundingInfo(),
            l.computeWorldMatrix(!0)
        }
        return n !== null && (l.parent = n),
        l._instanceDataStorage.hardwareInstancedRendering = l.getEngine().getCaps().instancedArrays,
        l._internalMeshDataInfo._onMeshReadyObserverAdded = function(v) {
            v.unregisterOnNextCall = !0,
            l.isReady(!0) ? l.onMeshReadyObservable.notifyObservers(l) : l._internalMeshDataInfo._checkReadinessObserver || (l._internalMeshDataInfo._checkReadinessObserver = l._scene.onBeforeRenderObservable.add(function() {
                l.isReady(!0) && (l._scene.onBeforeRenderObservable.remove(l._internalMeshDataInfo._checkReadinessObserver),
                l._internalMeshDataInfo._checkReadinessObserver = null,
                l.onMeshReadyObservable.notifyObservers(l))
            }))
        }
        ,
        l.onMeshReadyObservable = new Observable(l._internalMeshDataInfo._onMeshReadyObserverAdded),
        o && o.onClonedObservable.notifyObservers(l),
        l
    }
    return e._GetDefaultSideOrientation = function(t) {
        return t || e.FRONTSIDE
    }
    ,
    Object.defineProperty(e.prototype, "useLODScreenCoverage", {
        get: function() {
            return this._internalMeshDataInfo._useLODScreenCoverage
        },
        set: function(t) {
            this._internalMeshDataInfo._useLODScreenCoverage = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "computeBonesUsingShaders", {
        get: function() {
            return this._internalAbstractMeshDataInfo._computeBonesUsingShaders
        },
        set: function(t) {
            this._internalAbstractMeshDataInfo._computeBonesUsingShaders !== t && (t && this._internalMeshDataInfo._sourcePositions && (this.setVerticesData(VertexBuffer.PositionKind, this._internalMeshDataInfo._sourcePositions.slice(), !0),
            this._internalMeshDataInfo._sourceNormals && this.setVerticesData(VertexBuffer.NormalKind, this._internalMeshDataInfo._sourceNormals.slice(), !0)),
            this._internalAbstractMeshDataInfo._computeBonesUsingShaders = t,
            this._markSubMeshesAsAttributesDirty())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "onBeforeRenderObservable", {
        get: function() {
            return this._internalMeshDataInfo._onBeforeRenderObservable || (this._internalMeshDataInfo._onBeforeRenderObservable = new Observable),
            this._internalMeshDataInfo._onBeforeRenderObservable
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "onBeforeBindObservable", {
        get: function() {
            return this._internalMeshDataInfo._onBeforeBindObservable || (this._internalMeshDataInfo._onBeforeBindObservable = new Observable),
            this._internalMeshDataInfo._onBeforeBindObservable
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "onAfterRenderObservable", {
        get: function() {
            return this._internalMeshDataInfo._onAfterRenderObservable || (this._internalMeshDataInfo._onAfterRenderObservable = new Observable),
            this._internalMeshDataInfo._onAfterRenderObservable
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "onBetweenPassObservable", {
        get: function() {
            return this._internalMeshDataInfo._onBetweenPassObservable || (this._internalMeshDataInfo._onBetweenPassObservable = new Observable),
            this._internalMeshDataInfo._onBetweenPassObservable
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "onBeforeDrawObservable", {
        get: function() {
            return this._internalMeshDataInfo._onBeforeDrawObservable || (this._internalMeshDataInfo._onBeforeDrawObservable = new Observable),
            this._internalMeshDataInfo._onBeforeDrawObservable
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "onBeforeDraw", {
        set: function(t) {
            this._onBeforeDrawObserver && this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver),
            this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "hasInstances", {
        get: function() {
            return this.instances.length > 0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "hasThinInstances", {
        get: function() {
            var t;
            return ((t = this._thinInstanceDataStorage.instancesCount) !== null && t !== void 0 ? t : 0) > 0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "forcedInstanceCount", {
        get: function() {
            return this._internalMeshDataInfo._forcedInstanceCount
        },
        set: function(t) {
            this._internalMeshDataInfo._forcedInstanceCount = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "source", {
        get: function() {
            return this._internalMeshDataInfo._source
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cloneMeshMap", {
        get: function() {
            return this._internalMeshDataInfo.meshMap
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "isUnIndexed", {
        get: function() {
            return this._unIndexed
        },
        set: function(t) {
            this._unIndexed !== t && (this._unIndexed = t,
            this._markSubMeshesAsAttributesDirty())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "worldMatrixInstancedBuffer", {
        get: function() {
            return this._instanceDataStorage.instancesData
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "previousWorldMatrixInstancedBuffer", {
        get: function() {
            return this._instanceDataStorage.instancesPreviousData
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "manualUpdateOfWorldMatrixInstancedBuffer", {
        get: function() {
            return this._instanceDataStorage.manualUpdate
        },
        set: function(t) {
            this._instanceDataStorage.manualUpdate = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "manualUpdateOfPreviousWorldMatrixInstancedBuffer", {
        get: function() {
            return this._instanceDataStorage.previousManualUpdate
        },
        set: function(t) {
            this._instanceDataStorage.previousManualUpdate = t
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.instantiateHierarchy = function(t, r, n) {
        t === void 0 && (t = null);
        var o = this.getTotalVertices() > 0 && (!r || !r.doNotInstantiate) ? this.createInstance("instance of " + (this.name || this.id)) : this.clone("Clone of " + (this.name || this.id), t || this.parent, !0);
        o && (o.parent = t || this.parent,
        o.position = this.position.clone(),
        o.scaling = this.scaling.clone(),
        this.rotationQuaternion ? o.rotationQuaternion = this.rotationQuaternion.clone() : o.rotation = this.rotation.clone(),
        n && n(this, o));
        for (var a = 0, s = this.getChildTransformNodes(!0); a < s.length; a++) {
            var l = s[a];
            l.instantiateHierarchy(o, r, n)
        }
        return o
    }
    ,
    e.prototype.getClassName = function() {
        return "Mesh"
    }
    ,
    Object.defineProperty(e.prototype, "_isMesh", {
        get: function() {
            return !0
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.toString = function(t) {
        var r = i.prototype.toString.call(this, t);
        if (r += ", n vertices: " + this.getTotalVertices(),
        r += ", parent: " + (this._waitingParentId ? this._waitingParentId : this.parent ? this.parent.name : "NONE"),
        this.animations)
            for (var n = 0; n < this.animations.length; n++)
                r += ", animation[0]: " + this.animations[n].toString(t);
        if (t)
            if (this._geometry) {
                var o = this.getIndices()
                  , a = this.getVerticesData(VertexBuffer.PositionKind);
                a && o && (r += ", flat shading: " + (a.length / 3 === o.length ? "YES" : "NO"))
            } else
                r += ", flat shading: UNKNOWN";
        return r
    }
    ,
    e.prototype._unBindEffect = function() {
        i.prototype._unBindEffect.call(this);
        for (var t = 0, r = this.instances; t < r.length; t++) {
            var n = r[t];
            n._unBindEffect()
        }
    }
    ,
    Object.defineProperty(e.prototype, "hasLODLevels", {
        get: function() {
            return this._internalMeshDataInfo._LODLevels.length > 0
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getLODLevels = function() {
        return this._internalMeshDataInfo._LODLevels
    }
    ,
    e.prototype._sortLODLevels = function() {
        var t = this._internalMeshDataInfo._useLODScreenCoverage ? -1 : 1;
        this._internalMeshDataInfo._LODLevels.sort(function(r, n) {
            return r.distanceOrScreenCoverage < n.distanceOrScreenCoverage ? t : r.distanceOrScreenCoverage > n.distanceOrScreenCoverage ? -t : 0
        })
    }
    ,
    e.prototype.addLODLevel = function(t, r) {
        if (r && r._masterMesh)
            return Logger$2.Warn("You cannot use a mesh as LOD level twice"),
            this;
        var n = new MeshLODLevel(t,r);
        return this._internalMeshDataInfo._LODLevels.push(n),
        r && (r._masterMesh = this),
        this._sortLODLevels(),
        this
    }
    ,
    e.prototype.getLODLevelAtDistance = function(t) {
        for (var r = this._internalMeshDataInfo, n = 0; n < r._LODLevels.length; n++) {
            var o = r._LODLevels[n];
            if (o.distanceOrScreenCoverage === t)
                return o.mesh
        }
        return null
    }
    ,
    e.prototype.removeLODLevel = function(t) {
        for (var r = this._internalMeshDataInfo, n = 0; n < r._LODLevels.length; n++)
            r._LODLevels[n].mesh === t && (r._LODLevels.splice(n, 1),
            t && (t._masterMesh = null));
        return this._sortLODLevels(),
        this
    }
    ,
    e.prototype.getLOD = function(t, r) {
        var n = this._internalMeshDataInfo;
        if (!n._LODLevels || n._LODLevels.length === 0)
            return this;
        var o;
        if (r)
            o = r;
        else {
            var a = this.getBoundingInfo();
            o = a.boundingSphere
        }
        var s = o.centerWorld.subtract(t.globalPosition).length()
          , l = n._useLODScreenCoverage
          , u = s
          , c = 1;
        if (l) {
            var h = t.screenArea
              , f = o.radiusWorld * t.minZ / s;
            f = f * f * Math.PI,
            u = f / h,
            c = -1
        }
        if (c * n._LODLevels[n._LODLevels.length - 1].distanceOrScreenCoverage > c * u)
            return this.onLODLevelSelection && this.onLODLevelSelection(u, this, this),
            this;
        for (var d = 0; d < n._LODLevels.length; d++) {
            var _ = n._LODLevels[d];
            if (c * _.distanceOrScreenCoverage < c * u) {
                if (_.mesh) {
                    if (_.mesh.delayLoadState === 4)
                        return _.mesh._checkDelayState(),
                        this;
                    if (_.mesh.delayLoadState === 2)
                        return this;
                    _.mesh._preActivate(),
                    _.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache)
                }
                return this.onLODLevelSelection && this.onLODLevelSelection(u, this, _.mesh),
                _.mesh
            }
        }
        return this.onLODLevelSelection && this.onLODLevelSelection(u, this, this),
        this
    }
    ,
    Object.defineProperty(e.prototype, "geometry", {
        get: function() {
            return this._geometry
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getTotalVertices = function() {
        return this._geometry === null || this._geometry === void 0 ? 0 : this._geometry.getTotalVertices()
    }
    ,
    e.prototype.getVerticesData = function(t, r, n) {
        var o, a;
        if (!this._geometry)
            return null;
        var s = (a = (o = this._userInstancedBuffersStorage) === null || o === void 0 ? void 0 : o.vertexBuffers[t]) === null || a === void 0 ? void 0 : a.getFloatData(this._geometry.getTotalVertices(), n || r && this._geometry.meshes.length !== 1);
        return s || (s = this._geometry.getVerticesData(t, r, n)),
        s
    }
    ,
    e.prototype.getVertexBuffer = function(t) {
        var r, n;
        return this._geometry ? (n = (r = this._userInstancedBuffersStorage) === null || r === void 0 ? void 0 : r.vertexBuffers[t]) !== null && n !== void 0 ? n : this._geometry.getVertexBuffer(t) : null
    }
    ,
    e.prototype.isVerticesDataPresent = function(t) {
        var r;
        return this._geometry ? ((r = this._userInstancedBuffersStorage) === null || r === void 0 ? void 0 : r.vertexBuffers[t]) !== void 0 || this._geometry.isVerticesDataPresent(t) : this._delayInfo ? this._delayInfo.indexOf(t) !== -1 : !1
    }
    ,
    e.prototype.isVertexBufferUpdatable = function(t) {
        var r, n;
        return this._geometry ? ((n = (r = this._userInstancedBuffersStorage) === null || r === void 0 ? void 0 : r.vertexBuffers[t]) === null || n === void 0 ? void 0 : n.isUpdatable()) || this._geometry.isVertexBufferUpdatable(t) : this._delayInfo ? this._delayInfo.indexOf(t) !== -1 : !1
    }
    ,
    e.prototype.getVerticesDataKinds = function() {
        if (!this._geometry) {
            var t = new Array;
            return this._delayInfo && this._delayInfo.forEach(function(o) {
                t.push(o)
            }),
            t
        }
        var r = this._geometry.getVerticesDataKinds();
        if (this._userInstancedBuffersStorage)
            for (var n in this._userInstancedBuffersStorage.vertexBuffers)
                r.push(n);
        return r
    }
    ,
    e.prototype.getTotalIndices = function() {
        return this._geometry ? this._geometry.getTotalIndices() : 0
    }
    ,
    e.prototype.getIndices = function(t, r) {
        return this._geometry ? this._geometry.getIndices(t, r) : []
    }
    ,
    Object.defineProperty(e.prototype, "isBlocked", {
        get: function() {
            return this._masterMesh !== null && this._masterMesh !== void 0
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.isReady = function(t, r) {
        var n, o, a, s, l, u;
        if (t === void 0 && (t = !1),
        r === void 0 && (r = !1),
        this.delayLoadState === 2 || !i.prototype.isReady.call(this, t))
            return !1;
        if (!this.subMeshes || this.subMeshes.length === 0 || !t)
            return !0;
        var c = this.getEngine()
          , h = this.getScene()
          , f = r || c.getCaps().instancedArrays && (this.instances.length > 0 || this.hasThinInstances);
        this.computeWorldMatrix();
        var d = this.material || h.defaultMaterial;
        if (d) {
            if (d._storeEffectOnSubMeshes)
                for (var _ = 0, g = this.subMeshes; _ < g.length; _++) {
                    var m = g[_]
                      , v = m.getMaterial();
                    if (v) {
                        if (v._storeEffectOnSubMeshes) {
                            if (!v.isReadyForSubMesh(this, m, f))
                                return !1
                        } else if (!v.isReady(this, f))
                            return !1
                    }
                }
            else if (!d.isReady(this, f))
                return !1
        }
        for (var y = c.currentRenderPassId, b = 0, T = this.lightSources; b < T.length; b++) {
            var C = T[b]
              , A = C.getShadowGenerator();
            if (A && (!(!((n = A.getShadowMap()) === null || n === void 0) && n.renderList) || ((o = A.getShadowMap()) === null || o === void 0 ? void 0 : o.renderList) && ((s = (a = A.getShadowMap()) === null || a === void 0 ? void 0 : a.renderList) === null || s === void 0 ? void 0 : s.indexOf(this)) !== -1)) {
                A.getShadowMap() && (c.currentRenderPassId = A.getShadowMap().renderPassId);
                for (var S = 0, P = this.subMeshes; S < P.length; S++) {
                    var m = P[S];
                    if (!A.isReady(m, f, (u = (l = m.getMaterial()) === null || l === void 0 ? void 0 : l.needAlphaBlendingForMesh(this)) !== null && u !== void 0 ? u : !1))
                        return c.currentRenderPassId = y,
                        !1
                }
                c.currentRenderPassId = y
            }
        }
        for (var R = 0, M = this._internalMeshDataInfo._LODLevels; R < M.length; R++) {
            var x = M[R];
            if (x.mesh && !x.mesh.isReady(f))
                return !1
        }
        return !0
    }
    ,
    Object.defineProperty(e.prototype, "areNormalsFrozen", {
        get: function() {
            return this._internalMeshDataInfo._areNormalsFrozen
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.freezeNormals = function() {
        return this._internalMeshDataInfo._areNormalsFrozen = !0,
        this
    }
    ,
    e.prototype.unfreezeNormals = function() {
        return this._internalMeshDataInfo._areNormalsFrozen = !1,
        this
    }
    ,
    Object.defineProperty(e.prototype, "overridenInstanceCount", {
        set: function(t) {
            this._instanceDataStorage.overridenInstanceCount = t
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._preActivate = function() {
        var t = this._internalMeshDataInfo
          , r = this.getScene().getRenderId();
        return t._preActivateId === r ? this : (t._preActivateId = r,
        this._instanceDataStorage.visibleInstances = null,
        this)
    }
    ,
    e.prototype._preActivateForIntermediateRendering = function(t) {
        return this._instanceDataStorage.visibleInstances && (this._instanceDataStorage.visibleInstances.intermediateDefaultRenderId = t),
        this
    }
    ,
    e.prototype._registerInstanceForRenderId = function(t, r) {
        return this._instanceDataStorage.visibleInstances || (this._instanceDataStorage.visibleInstances = {
            defaultRenderId: r,
            selfDefaultRenderId: this._renderId
        }),
        this._instanceDataStorage.visibleInstances[r] || (this._instanceDataStorage.previousRenderId !== void 0 && this._instanceDataStorage.isFrozen && (this._instanceDataStorage.visibleInstances[this._instanceDataStorage.previousRenderId] = null),
        this._instanceDataStorage.previousRenderId = r,
        this._instanceDataStorage.visibleInstances[r] = new Array),
        this._instanceDataStorage.visibleInstances[r].push(t),
        this
    }
    ,
    e.prototype._afterComputeWorldMatrix = function() {
        i.prototype._afterComputeWorldMatrix.call(this),
        this.hasThinInstances && (this.doNotSyncBoundingInfo || this.thinInstanceRefreshBoundingInfo(!1))
    }
    ,
    e.prototype._postActivate = function() {
        this.edgesShareWithInstances && this.edgesRenderer && this.edgesRenderer.isEnabled && this._renderingGroup && (this._renderingGroup._edgesRenderers.pushNoDuplicate(this.edgesRenderer),
        this.edgesRenderer.customInstances.push(this.getWorldMatrix()))
    }
    ,
    e.prototype.refreshBoundingInfo = function(t, r) {
        if (t === void 0 && (t = !1),
        r === void 0 && (r = !0),
        this.hasBoundingInfo && this.getBoundingInfo().isLocked)
            return this;
        var n = this.geometry ? this.geometry.boundingBias : null;
        return this._refreshBoundingInfo(this._getPositionData(t, r), n),
        this
    }
    ,
    e.prototype._createGlobalSubMesh = function(t) {
        var r = this.getTotalVertices();
        if (!r || !this.getIndices())
            return null;
        if (this.subMeshes && this.subMeshes.length > 0) {
            var n = this.getIndices();
            if (!n)
                return null;
            var o = n.length
              , a = !1;
            if (t)
                a = !0;
            else
                for (var s = 0, l = this.subMeshes; s < l.length; s++) {
                    var u = l[s];
                    if (u.indexStart + u.indexCount > o) {
                        a = !0;
                        break
                    }
                    if (u.verticesStart + u.verticesCount > r) {
                        a = !0;
                        break
                    }
                }
            if (!a)
                return this.subMeshes[0]
        }
        return this.releaseSubMeshes(),
        new SubMesh(0,0,r,0,this.getTotalIndices(),this)
    }
    ,
    e.prototype.subdivide = function(t) {
        if (!(t < 1)) {
            for (var r = this.getTotalIndices(), n = r / t | 0, o = 0; n % 3 !== 0; )
                n++;
            this.releaseSubMeshes();
            for (var a = 0; a < t && !(o >= r); a++)
                SubMesh.CreateFromIndices(0, o, a === t - 1 ? r - o : n, this),
                o += n;
            this.synchronizeInstances()
        }
    }
    ,
    e.prototype.setVerticesData = function(t, r, n, o) {
        if (n === void 0 && (n = !1),
        this._geometry)
            this._geometry.setVerticesData(t, r, n, o);
        else {
            var a = new VertexData;
            a.set(r, t);
            var s = this.getScene();
            new Geometry(Geometry.RandomId(),s,a,n,this)
        }
        return this
    }
    ,
    e.prototype.removeVerticesData = function(t) {
        !this._geometry || this._geometry.removeVerticesData(t)
    }
    ,
    e.prototype.markVerticesDataAsUpdatable = function(t, r) {
        r === void 0 && (r = !0);
        var n = this.getVertexBuffer(t);
        !n || n.isUpdatable() === r || this.setVerticesData(t, this.getVerticesData(t), r)
    }
    ,
    e.prototype.setVerticesBuffer = function(t, r) {
        return r === void 0 && (r = !0),
        this._geometry || (this._geometry = Geometry.CreateGeometryForMesh(this)),
        this._geometry.setVerticesBuffer(t, null, r),
        this
    }
    ,
    e.prototype.updateVerticesData = function(t, r, n, o) {
        return this._geometry ? (o ? (this.makeGeometryUnique(),
        this.updateVerticesData(t, r, n, !1)) : this._geometry.updateVerticesData(t, r, n),
        this) : this
    }
    ,
    e.prototype.updateMeshPositions = function(t, r) {
        r === void 0 && (r = !0);
        var n = this.getVerticesData(VertexBuffer.PositionKind);
        if (!n)
            return this;
        if (t(n),
        this.updateVerticesData(VertexBuffer.PositionKind, n, !1, !1),
        r) {
            var o = this.getIndices()
              , a = this.getVerticesData(VertexBuffer.NormalKind);
            if (!a)
                return this;
            VertexData.ComputeNormals(n, o, a),
            this.updateVerticesData(VertexBuffer.NormalKind, a, !1, !1)
        }
        return this
    }
    ,
    e.prototype.makeGeometryUnique = function() {
        if (!this._geometry)
            return this;
        if (this._geometry.meshes.length === 1)
            return this;
        var t = this._geometry
          , r = this._geometry.copy(Geometry.RandomId());
        return t.releaseForMesh(this, !0),
        r.applyToMesh(this),
        this
    }
    ,
    e.prototype.setIndices = function(t, r, n) {
        if (r === void 0 && (r = null),
        n === void 0 && (n = !1),
        this._geometry)
            this._geometry.setIndices(t, r, n);
        else {
            var o = new VertexData;
            o.indices = t;
            var a = this.getScene();
            new Geometry(Geometry.RandomId(),a,o,n,this)
        }
        return this
    }
    ,
    e.prototype.updateIndices = function(t, r, n) {
        return n === void 0 && (n = !1),
        this._geometry ? (this._geometry.updateIndices(t, r, n),
        this) : this
    }
    ,
    e.prototype.toLeftHanded = function() {
        return this._geometry ? (this._geometry.toLeftHanded(),
        this) : this
    }
    ,
    e.prototype._bind = function(t, r, n) {
        if (!this._geometry)
            return this;
        var o = this.getScene().getEngine();
        this.morphTargetManager && this.morphTargetManager.isUsingTextureForTargets && this.morphTargetManager._bind(r);
        var a;
        if (this._unIndexed)
            a = null;
        else
            switch (n) {
            case Material.PointFillMode:
                a = null;
                break;
            case Material.WireFrameFillMode:
                a = t._getLinesIndexBuffer(this.getIndices(), o);
                break;
            default:
            case Material.TriangleFillMode:
                a = this._geometry.getIndexBuffer();
                break
            }
        return !this._userInstancedBuffersStorage || this.hasThinInstances ? this._geometry._bind(r, a) : this._geometry._bind(r, a, this._userInstancedBuffersStorage.vertexBuffers, this._userInstancedBuffersStorage.vertexArrayObjects),
        this
    }
    ,
    e.prototype._draw = function(t, r, n) {
        if (!this._geometry || !this._geometry.getVertexBuffers() || !this._unIndexed && !this._geometry.getIndexBuffer())
            return this;
        this._internalMeshDataInfo._onBeforeDrawObservable && this._internalMeshDataInfo._onBeforeDrawObservable.notifyObservers(this);
        var o = this.getScene()
          , a = o.getEngine();
        return this._unIndexed || r == Material.PointFillMode ? a.drawArraysType(r, t.verticesStart, t.verticesCount, this.forcedInstanceCount || n) : r == Material.WireFrameFillMode ? a.drawElementsType(r, 0, t._linesIndexCount, this.forcedInstanceCount || n) : a.drawElementsType(r, t.indexStart, t.indexCount, this.forcedInstanceCount || n),
        this
    }
    ,
    e.prototype.registerBeforeRender = function(t) {
        return this.onBeforeRenderObservable.add(t),
        this
    }
    ,
    e.prototype.unregisterBeforeRender = function(t) {
        return this.onBeforeRenderObservable.removeCallback(t),
        this
    }
    ,
    e.prototype.registerAfterRender = function(t) {
        return this.onAfterRenderObservable.add(t),
        this
    }
    ,
    e.prototype.unregisterAfterRender = function(t) {
        return this.onAfterRenderObservable.removeCallback(t),
        this
    }
    ,
    e.prototype._getInstancesRenderList = function(t, r) {
        if (r === void 0 && (r = !1),
        this._instanceDataStorage.isFrozen) {
            if (r)
                return this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.hardwareInstancedRendering[t] = !1,
                this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.renderSelf[t] = !0,
                this._instanceDataStorage.batchCacheReplacementModeInFrozenMode;
            if (this._instanceDataStorage.previousBatch)
                return this._instanceDataStorage.previousBatch
        }
        var n = this.getScene()
          , o = n._isInIntermediateRendering()
          , a = o ? this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate : this._internalAbstractMeshDataInfo._onlyForInstances
          , s = this._instanceDataStorage.batchCache;
        if (s.mustReturn = !1,
        s.renderSelf[t] = r || !a && this.isEnabled() && this.isVisible,
        s.visibleInstances[t] = null,
        this._instanceDataStorage.visibleInstances && !r) {
            var l = this._instanceDataStorage.visibleInstances
              , u = n.getRenderId()
              , c = o ? l.intermediateDefaultRenderId : l.defaultRenderId;
            s.visibleInstances[t] = l[u],
            !s.visibleInstances[t] && c && (s.visibleInstances[t] = l[c])
        }
        return s.hardwareInstancedRendering[t] = !r && this._instanceDataStorage.hardwareInstancedRendering && s.visibleInstances[t] !== null && s.visibleInstances[t] !== void 0,
        this._instanceDataStorage.previousBatch = s,
        s
    }
    ,
    e.prototype._renderWithInstances = function(t, r, n, o, a) {
        var s, l = n.visibleInstances[t._id];
        if (!l)
            return this;
        for (var u = this._instanceDataStorage, c = u.instancesBufferSize, h = u.instancesBuffer, f = u.instancesPreviousBuffer, d = l.length + 1, _ = d * 16 * 4; u.instancesBufferSize < _; )
            u.instancesBufferSize *= 2;
        (!u.instancesData || c != u.instancesBufferSize) && (u.instancesData = new Float32Array(u.instancesBufferSize / 4)),
        (this._scene.needsPreviousWorldMatrices && !u.instancesPreviousData || c != u.instancesBufferSize) && (u.instancesPreviousData = new Float32Array(u.instancesBufferSize / 4));
        var g = 0
          , m = 0
          , v = n.renderSelf[t._id]
          , y = !h || c !== u.instancesBufferSize || this._scene.needsPreviousWorldMatrices && !u.instancesPreviousBuffer;
        if (!this._instanceDataStorage.manualUpdate && (!u.isFrozen || y)) {
            var b = this._effectiveMesh.getWorldMatrix();
            if (v && (this._scene.needsPreviousWorldMatrices && (u.masterMeshPreviousWorldMatrix ? (u.masterMeshPreviousWorldMatrix.copyToArray(u.instancesPreviousData, g),
            u.masterMeshPreviousWorldMatrix.copyFrom(b)) : (u.masterMeshPreviousWorldMatrix = b.clone(),
            u.masterMeshPreviousWorldMatrix.copyToArray(u.instancesPreviousData, g))),
            b.copyToArray(u.instancesData, g),
            g += 16,
            m++),
            l) {
                if (e.INSTANCEDMESH_SORT_TRANSPARENT && this._scene.activeCamera && ((s = t.getMaterial()) === null || s === void 0 ? void 0 : s.needAlphaBlendingForMesh(t.getRenderingMesh()))) {
                    for (var T = this._scene.activeCamera.globalPosition, C = 0; C < l.length; C++) {
                        var A = l[C];
                        A._distanceToCamera = Vector3.Distance(A.getBoundingInfo().boundingSphere.centerWorld, T)
                    }
                    l.sort(function(M, x) {
                        return M._distanceToCamera > x._distanceToCamera ? -1 : M._distanceToCamera < x._distanceToCamera ? 1 : 0
                    })
                }
                for (var S = 0; S < l.length; S++) {
                    var P = l[S]
                      , R = P.getWorldMatrix();
                    R.copyToArray(u.instancesData, g),
                    this._scene.needsPreviousWorldMatrices && (P._previousWorldMatrix ? (P._previousWorldMatrix.copyToArray(u.instancesPreviousData, g),
                    P._previousWorldMatrix.copyFrom(R)) : (P._previousWorldMatrix = R.clone(),
                    P._previousWorldMatrix.copyToArray(u.instancesPreviousData, g))),
                    g += 16,
                    m++
                }
            }
        } else
            m = (v ? 1 : 0) + l.length;
        return y ? (h && h.dispose(),
        f && f.dispose(),
        h = new Buffer(a,u.instancesData,!0,16,!1,!0),
        u.instancesBuffer = h,
        this._userInstancedBuffersStorage || (this._userInstancedBuffersStorage = {
            data: {},
            vertexBuffers: {},
            strides: {},
            sizes: {},
            vertexArrayObjects: this.getEngine().getCaps().vertexArrayObject ? {} : void 0
        }),
        this._userInstancedBuffersStorage.vertexBuffers.world0 = h.createVertexBuffer("world0", 0, 4),
        this._userInstancedBuffersStorage.vertexBuffers.world1 = h.createVertexBuffer("world1", 4, 4),
        this._userInstancedBuffersStorage.vertexBuffers.world2 = h.createVertexBuffer("world2", 8, 4),
        this._userInstancedBuffersStorage.vertexBuffers.world3 = h.createVertexBuffer("world3", 12, 4),
        this._scene.needsPreviousWorldMatrices && (f = new Buffer(a,u.instancesPreviousData,!0,16,!1,!0),
        u.instancesPreviousBuffer = f,
        this._userInstancedBuffersStorage.vertexBuffers.previousWorld0 = f.createVertexBuffer("previousWorld0", 0, 4),
        this._userInstancedBuffersStorage.vertexBuffers.previousWorld1 = f.createVertexBuffer("previousWorld1", 4, 4),
        this._userInstancedBuffersStorage.vertexBuffers.previousWorld2 = f.createVertexBuffer("previousWorld2", 8, 4),
        this._userInstancedBuffersStorage.vertexBuffers.previousWorld3 = f.createVertexBuffer("previousWorld3", 12, 4)),
        this._invalidateInstanceVertexArrayObject()) : this._instanceDataStorage.isFrozen || (h.updateDirectly(u.instancesData, 0, m),
        this._scene.needsPreviousWorldMatrices && (!this._instanceDataStorage.manualUpdate || this._instanceDataStorage.previousManualUpdate) && f.updateDirectly(u.instancesPreviousData, 0, m)),
        this._processInstancedBuffers(l, v),
        this.getScene()._activeIndices.addCount(t.indexCount * m, !1),
        a._currentDrawContext && (a._currentDrawContext.useInstancing = !0),
        this._bind(t, o, r),
        this._draw(t, r, m),
        this._scene.needsPreviousWorldMatrices && !y && this._instanceDataStorage.manualUpdate && !this._instanceDataStorage.isFrozen && !this._instanceDataStorage.previousManualUpdate && f.updateDirectly(u.instancesData, 0, m),
        a.unbindInstanceAttributes(),
        this
    }
    ,
    e.prototype._renderWithThinInstances = function(t, r, n, o) {
        var a, s, l = (s = (a = this._thinInstanceDataStorage) === null || a === void 0 ? void 0 : a.instancesCount) !== null && s !== void 0 ? s : 0;
        this.getScene()._activeIndices.addCount(t.indexCount * l, !1),
        o._currentDrawContext && (o._currentDrawContext.useInstancing = !0),
        this._bind(t, n, r),
        this._draw(t, r, l),
        this._scene.needsPreviousWorldMatrices && !this._thinInstanceDataStorage.previousMatrixData && this._thinInstanceDataStorage.matrixData && (this._thinInstanceDataStorage.previousMatrixBuffer ? this._thinInstanceDataStorage.previousMatrixBuffer.updateDirectly(this._thinInstanceDataStorage.matrixData, 0, l) : this._thinInstanceDataStorage.previousMatrixBuffer = this._thinInstanceCreateMatrixBuffer("previousWorld", this._thinInstanceDataStorage.matrixData, !1)),
        o.unbindInstanceAttributes()
    }
    ,
    e.prototype._processInstancedBuffers = function(t, r) {}
    ,
    e.prototype._processRendering = function(t, r, n, o, a, s, l, u) {
        var c = this.getScene()
          , h = c.getEngine();
        if (s && r.getRenderingMesh().hasThinInstances)
            return this._renderWithThinInstances(r, o, n, h),
            this;
        if (s)
            this._renderWithInstances(r, o, a, n, h);
        else {
            h._currentDrawContext && (h._currentDrawContext.useInstancing = !1);
            var f = 0;
            a.renderSelf[r._id] && (l && l(!1, t._effectiveMesh.getWorldMatrix(), u, t._effectiveMesh),
            f++,
            this._draw(r, o, this._instanceDataStorage.overridenInstanceCount));
            var d = a.visibleInstances[r._id];
            if (d) {
                var _ = d.length;
                f += _;
                for (var g = 0; g < _; g++) {
                    var m = d[g]
                      , v = m.getWorldMatrix();
                    l && l(!0, v, u),
                    this._draw(r, o)
                }
            }
            c._activeIndices.addCount(r.indexCount * f, !1)
        }
        return this
    }
    ,
    e.prototype._rebuild = function(t) {
        if (t === void 0 && (t = !1),
        this._instanceDataStorage.instancesBuffer && (t && this._instanceDataStorage.instancesBuffer.dispose(),
        this._instanceDataStorage.instancesBuffer = null),
        this._userInstancedBuffersStorage) {
            for (var r in this._userInstancedBuffersStorage.vertexBuffers) {
                var n = this._userInstancedBuffersStorage.vertexBuffers[r];
                n && (t && n.dispose(),
                this._userInstancedBuffersStorage.vertexBuffers[r] = null)
            }
            this._userInstancedBuffersStorage.vertexArrayObjects && (this._userInstancedBuffersStorage.vertexArrayObjects = {})
        }
        this._internalMeshDataInfo._effectiveMaterial = null,
        i.prototype._rebuild.call(this, t)
    }
    ,
    e.prototype._freeze = function() {
        if (!!this.subMeshes) {
            for (var t = 0; t < this.subMeshes.length; t++)
                this._getInstancesRenderList(t);
            this._internalMeshDataInfo._effectiveMaterial = null,
            this._instanceDataStorage.isFrozen = !0
        }
    }
    ,
    e.prototype._unFreeze = function() {
        this._instanceDataStorage.isFrozen = !1,
        this._instanceDataStorage.previousBatch = null
    }
    ,
    e.prototype.render = function(t, r, n) {
        var o, a, s, l = this.getScene();
        if (this._internalAbstractMeshDataInfo._isActiveIntermediate ? this._internalAbstractMeshDataInfo._isActiveIntermediate = !1 : this._internalAbstractMeshDataInfo._isActive = !1,
        this._checkOcclusionQuery())
            return this;
        var u = this._getInstancesRenderList(t._id, !!n);
        if (u.mustReturn)
            return this;
        if (!this._geometry || !this._geometry.getVertexBuffers() || !this._unIndexed && !this._geometry.getIndexBuffer())
            return this;
        var c = l.getEngine()
          , h = 0
          , f = null;
        this.ignoreCameraMaxZ && l.activeCamera && !l._isInIntermediateRendering() && (h = l.activeCamera.maxZ,
        f = l.activeCamera,
        l.activeCamera.maxZ = 0,
        l.updateTransformMatrix(!0)),
        this._internalMeshDataInfo._onBeforeRenderObservable && this._internalMeshDataInfo._onBeforeRenderObservable.notifyObservers(this);
        var d = u.hardwareInstancedRendering[t._id] || t.getRenderingMesh().hasThinInstances
          , _ = this._instanceDataStorage
          , g = t.getMaterial();
        if (!g)
            return f && (f.maxZ = h,
            l.updateTransformMatrix(!0)),
            this;
        if (!_.isFrozen || !this._internalMeshDataInfo._effectiveMaterial || this._internalMeshDataInfo._effectiveMaterial !== g) {
            if (g._storeEffectOnSubMeshes) {
                if (!g.isReadyForSubMesh(this, t, d))
                    return f && (f.maxZ = h,
                    l.updateTransformMatrix(!0)),
                    this
            } else if (!g.isReady(this, d))
                return f && (f.maxZ = h,
                l.updateTransformMatrix(!0)),
                this;
            this._internalMeshDataInfo._effectiveMaterial = g
        } else if (g._storeEffectOnSubMeshes && !(!((o = t.effect) === null || o === void 0) && o._wasPreviouslyReady) || !g._storeEffectOnSubMeshes && !(!((a = g.getEffect()) === null || a === void 0) && a._wasPreviouslyReady))
            return f && (f.maxZ = h,
            l.updateTransformMatrix(!0)),
            this;
        r && c.setAlphaMode(this._internalMeshDataInfo._effectiveMaterial.alphaMode);
        var m;
        this._internalMeshDataInfo._effectiveMaterial._storeEffectOnSubMeshes ? m = t._drawWrapper : m = this._internalMeshDataInfo._effectiveMaterial._getDrawWrapper();
        for (var v = (s = m == null ? void 0 : m.effect) !== null && s !== void 0 ? s : null, y = 0, b = l._beforeRenderingMeshStage; y < b.length; y++) {
            var T = b[y];
            T.action(this, t, u, v)
        }
        if (!m || !v)
            return f && (f.maxZ = h,
            l.updateTransformMatrix(!0)),
            this;
        var C = n || this._effectiveMesh, A;
        if (!_.isFrozen && (this._internalMeshDataInfo._effectiveMaterial.backFaceCulling || this.overrideMaterialSideOrientation !== null)) {
            var S = C._getWorldMatrixDeterminant();
            A = this.overrideMaterialSideOrientation,
            A == null && (A = this._internalMeshDataInfo._effectiveMaterial.sideOrientation),
            S < 0 && (A = A === Material.ClockWiseSideOrientation ? Material.CounterClockWiseSideOrientation : Material.ClockWiseSideOrientation),
            _.sideOrientation = A
        } else
            A = _.sideOrientation;
        var P = this._internalMeshDataInfo._effectiveMaterial._preBind(m, A);
        this._internalMeshDataInfo._effectiveMaterial.forceDepthWrite && c.setDepthWrite(!0);
        var R = l.forcePointsCloud ? Material.PointFillMode : l.forceWireframe ? Material.WireFrameFillMode : this._internalMeshDataInfo._effectiveMaterial.fillMode;
        this._internalMeshDataInfo._onBeforeBindObservable && this._internalMeshDataInfo._onBeforeBindObservable.notifyObservers(this),
        d || this._bind(t, v, R);
        var M = this._internalMeshDataInfo._effectiveMaterial
          , x = C.getWorldMatrix();
        M._storeEffectOnSubMeshes ? M.bindForSubMesh(x, this, t) : M.bind(x, this),
        !M.backFaceCulling && M.separateCullingPass && (c.setState(!0, M.zOffset, !1, !P, M.cullBackFaces, M.stencil, M.zOffsetUnits),
        this._processRendering(this, t, v, R, u, d, this._onBeforeDraw, this._internalMeshDataInfo._effectiveMaterial),
        c.setState(!0, M.zOffset, !1, P, M.cullBackFaces, M.stencil, M.zOffsetUnits),
        this._internalMeshDataInfo._onBetweenPassObservable && this._internalMeshDataInfo._onBetweenPassObservable.notifyObservers(t)),
        this._processRendering(this, t, v, R, u, d, this._onBeforeDraw, this._internalMeshDataInfo._effectiveMaterial),
        this._internalMeshDataInfo._effectiveMaterial.unbind();
        for (var I = 0, w = l._afterRenderingMeshStage; I < w.length; I++) {
            var T = w[I];
            T.action(this, t, u, v)
        }
        return this._internalMeshDataInfo._onAfterRenderObservable && this._internalMeshDataInfo._onAfterRenderObservable.notifyObservers(this),
        f && (f.maxZ = h,
        l.updateTransformMatrix(!0)),
        this
    }
    ,
    e.prototype._onBeforeDraw = function(t, r, n) {
        t && n && n.bindOnlyWorldMatrix(r)
    }
    ,
    e.prototype.cleanMatrixWeights = function() {
        this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind) && (this.isVerticesDataPresent(VertexBuffer.MatricesWeightsExtraKind) ? this.normalizeSkinWeightsAndExtra() : this.normalizeSkinFourWeights())
    }
    ,
    e.prototype.normalizeSkinFourWeights = function() {
        for (var t = this.getVerticesData(VertexBuffer.MatricesWeightsKind), r = t.length, n = 0; n < r; n += 4) {
            var o = t[n] + t[n + 1] + t[n + 2] + t[n + 3];
            if (o === 0)
                t[n] = 1;
            else {
                var a = 1 / o;
                t[n] *= a,
                t[n + 1] *= a,
                t[n + 2] *= a,
                t[n + 3] *= a
            }
        }
        this.setVerticesData(VertexBuffer.MatricesWeightsKind, t)
    }
    ,
    e.prototype.normalizeSkinWeightsAndExtra = function() {
        for (var t = this.getVerticesData(VertexBuffer.MatricesWeightsExtraKind), r = this.getVerticesData(VertexBuffer.MatricesWeightsKind), n = r.length, o = 0; o < n; o += 4) {
            var a = r[o] + r[o + 1] + r[o + 2] + r[o + 3];
            if (a += t[o] + t[o + 1] + t[o + 2] + t[o + 3],
            a === 0)
                r[o] = 1;
            else {
                var s = 1 / a;
                r[o] *= s,
                r[o + 1] *= s,
                r[o + 2] *= s,
                r[o + 3] *= s,
                t[o] *= s,
                t[o + 1] *= s,
                t[o + 2] *= s,
                t[o + 3] *= s
            }
        }
        this.setVerticesData(VertexBuffer.MatricesWeightsKind, r),
        this.setVerticesData(VertexBuffer.MatricesWeightsKind, t)
    }
    ,
    e.prototype.validateSkinning = function() {
        var t = this.getVerticesData(VertexBuffer.MatricesWeightsExtraKind)
          , r = this.getVerticesData(VertexBuffer.MatricesWeightsKind);
        if (r === null || this.skeleton == null)
            return {
                skinned: !1,
                valid: !0,
                report: "not skinned"
            };
        for (var n = r.length, o = 0, a = 0, s = 0, l = 0, u = t === null ? 4 : 8, c = new Array, h = 0; h <= u; h++)
            c[h] = 0;
        for (var f = .001, h = 0; h < n; h += 4) {
            for (var d = r[h], _ = d, g = _ === 0 ? 0 : 1, m = 1; m < u; m++) {
                var v = m < 4 ? r[h + m] : t[h + m - 4];
                v > d && o++,
                v !== 0 && g++,
                _ += v,
                d = v
            }
            if (c[g]++,
            g > s && (s = g),
            _ === 0)
                a++;
            else {
                var y = 1 / _
                  , b = 0;
                for (m = 0; m < u; m++)
                    m < 4 ? b += Math.abs(r[h + m] - r[h + m] * y) : b += Math.abs(t[h + m - 4] - t[h + m - 4] * y);
                b > f && l++
            }
        }
        for (var T = this.skeleton.bones.length, C = this.getVerticesData(VertexBuffer.MatricesIndicesKind), A = this.getVerticesData(VertexBuffer.MatricesIndicesExtraKind), S = 0, h = 0; h < n; h += 4)
            for (var m = 0; m < u; m++) {
                var P = m < 4 ? C[h + m] : A[h + m - 4];
                (P >= T || P < 0) && S++
            }
        var R = "Number of Weights = " + n / 4 + `
Maximum influences = ` + s + `
Missing Weights = ` + a + `
Not Sorted = ` + o + `
Not Normalized = ` + l + `
WeightCounts = [` + c + `]
Number of bones = ` + T + `
Bad Bone Indices = ` + S;
        return {
            skinned: !0,
            valid: a === 0 && l === 0 && S === 0,
            report: R
        }
    }
    ,
    e.prototype._checkDelayState = function() {
        var t = this.getScene();
        return this._geometry ? this._geometry.load(t) : this.delayLoadState === 4 && (this.delayLoadState = 2,
        this._queueLoad(t)),
        this
    }
    ,
    e.prototype._queueLoad = function(t) {
        var r = this;
        t._addPendingData(this);
        var n = this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1;
        return Tools.LoadFile(this.delayLoadingFile, function(o) {
            o instanceof ArrayBuffer ? r._delayLoadingFunction(o, r) : r._delayLoadingFunction(JSON.parse(o), r),
            r.instances.forEach(function(a) {
                a.refreshBoundingInfo(),
                a._syncSubMeshes()
            }),
            r.delayLoadState = 1,
            t._removePendingData(r)
        }, function() {}, t.offlineProvider, n),
        this
    }
    ,
    e.prototype.isInFrustum = function(t) {
        return this.delayLoadState === 2 || !i.prototype.isInFrustum.call(this, t) ? !1 : (this._checkDelayState(),
        !0)
    }
    ,
    e.prototype.setMaterialById = function(t) {
        var r = this.getScene().materials, n;
        for (n = r.length - 1; n > -1; n--)
            if (r[n].id === t)
                return this.material = r[n],
                this;
        var o = this.getScene().multiMaterials;
        for (n = o.length - 1; n > -1; n--)
            if (o[n].id === t)
                return this.material = o[n],
                this;
        return this
    }
    ,
    e.prototype.getAnimatables = function() {
        var t = new Array;
        return this.material && t.push(this.material),
        this.skeleton && t.push(this.skeleton),
        t
    }
    ,
    e.prototype.bakeTransformIntoVertices = function(t) {
        if (!this.isVerticesDataPresent(VertexBuffer.PositionKind))
            return this;
        var r = this.subMeshes.splice(0);
        this._resetPointsArrayCache();
        var n = this.getVerticesData(VertexBuffer.PositionKind), o = new Array, a;
        for (a = 0; a < n.length; a += 3)
            Vector3.TransformCoordinates(Vector3.FromArray(n, a), t).toArray(o, a);
        if (this.setVerticesData(VertexBuffer.PositionKind, o, this.getVertexBuffer(VertexBuffer.PositionKind).isUpdatable()),
        this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
            for (n = this.getVerticesData(VertexBuffer.NormalKind),
            o = [],
            a = 0; a < n.length; a += 3)
                Vector3.TransformNormal(Vector3.FromArray(n, a), t).normalize().toArray(o, a);
            this.setVerticesData(VertexBuffer.NormalKind, o, this.getVertexBuffer(VertexBuffer.NormalKind).isUpdatable())
        }
        return t.determinant() < 0 && this.flipFaces(),
        this.releaseSubMeshes(),
        this.subMeshes = r,
        this
    }
    ,
    e.prototype.bakeCurrentTransformIntoVertices = function(t) {
        return t === void 0 && (t = !0),
        this.bakeTransformIntoVertices(this.computeWorldMatrix(!0)),
        this.resetLocalMatrix(t),
        this
    }
    ,
    Object.defineProperty(e.prototype, "_positions", {
        get: function() {
            return this._internalAbstractMeshDataInfo._positions ? this._internalAbstractMeshDataInfo._positions : this._geometry ? this._geometry._positions : null
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._resetPointsArrayCache = function() {
        return this._geometry && this._geometry._resetPointsArrayCache(),
        this
    }
    ,
    e.prototype._generatePointsArray = function() {
        return this._geometry ? this._geometry._generatePointsArray() : !1
    }
    ,
    e.prototype.clone = function(t, r, n, o) {
        return t === void 0 && (t = ""),
        r === void 0 && (r = null),
        o === void 0 && (o = !0),
        new e(t,this.getScene(),r,this,n,o)
    }
    ,
    e.prototype.dispose = function(t, r) {
        r === void 0 && (r = !1),
        this.morphTargetManager = null,
        this._geometry && this._geometry.releaseForMesh(this, !0);
        var n = this._internalMeshDataInfo;
        if (n._onBeforeDrawObservable && n._onBeforeDrawObservable.clear(),
        n._onBeforeBindObservable && n._onBeforeBindObservable.clear(),
        n._onBeforeRenderObservable && n._onBeforeRenderObservable.clear(),
        n._onAfterRenderObservable && n._onAfterRenderObservable.clear(),
        n._onBetweenPassObservable && n._onBetweenPassObservable.clear(),
        this._scene.useClonedMeshMap) {
            if (n.meshMap)
                for (var o in n.meshMap) {
                    var a = n.meshMap[o];
                    a && (a._internalMeshDataInfo._source = null,
                    n.meshMap[o] = void 0)
                }
            n._source && n._source._internalMeshDataInfo.meshMap && (n._source._internalMeshDataInfo.meshMap[this.uniqueId] = void 0)
        } else
            for (var s = this.getScene().meshes, l = 0, u = s; l < u.length; l++) {
                var c = u[l]
                  , a = c;
                a._internalMeshDataInfo && a._internalMeshDataInfo._source && a._internalMeshDataInfo._source === this && (a._internalMeshDataInfo._source = null)
            }
        n._source = null,
        this._disposeInstanceSpecificData(),
        this._disposeThinInstanceSpecificData(),
        this._internalMeshDataInfo._checkReadinessObserver && this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver),
        i.prototype.dispose.call(this, t, r)
    }
    ,
    e.prototype._disposeInstanceSpecificData = function() {}
    ,
    e.prototype._disposeThinInstanceSpecificData = function() {}
    ,
    e.prototype._invalidateInstanceVertexArrayObject = function() {}
    ,
    e.prototype.applyDisplacementMap = function(t, r, n, o, a, s, l) {
        var u = this;
        l === void 0 && (l = !1);
        var c = this.getScene()
          , h = function(f) {
            var d = f.width
              , _ = f.height
              , g = u.getEngine().createCanvas(d, _)
              , m = g.getContext("2d");
            m.drawImage(f, 0, 0);
            var v = m.getImageData(0, 0, d, _).data;
            u.applyDisplacementMapFromBuffer(v, d, _, r, n, a, s, l),
            o && o(u)
        };
        return Tools.LoadImage(t, h, function() {}, c.offlineProvider),
        this
    }
    ,
    e.prototype.applyDisplacementMapFromBuffer = function(t, r, n, o, a, s, l, u) {
        if (u === void 0 && (u = !1),
        !this.isVerticesDataPresent(VertexBuffer.PositionKind) || !this.isVerticesDataPresent(VertexBuffer.NormalKind) || !this.isVerticesDataPresent(VertexBuffer.UVKind))
            return Logger$2.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing"),
            this;
        var c = this.getVerticesData(VertexBuffer.PositionKind, !0, !0)
          , h = this.getVerticesData(VertexBuffer.NormalKind)
          , f = this.getVerticesData(VertexBuffer.UVKind)
          , d = Vector3.Zero()
          , _ = Vector3.Zero()
          , g = Vector2.Zero();
        s = s || Vector2.Zero(),
        l = l || new Vector2(1,1);
        for (var m = 0; m < c.length; m += 3) {
            Vector3.FromArrayToRef(c, m, d),
            Vector3.FromArrayToRef(h, m, _),
            Vector2.FromArrayToRef(f, m / 3 * 2, g);
            var v = Math.abs(g.x * l.x + s.x % 1) * (r - 1) % r | 0
              , y = Math.abs(g.y * l.y + s.y % 1) * (n - 1) % n | 0
              , b = (v + y * r) * 4
              , T = t[b] / 255
              , C = t[b + 1] / 255
              , A = t[b + 2] / 255
              , S = T * .3 + C * .59 + A * .11;
            _.normalize(),
            _.scaleInPlace(o + (a - o) * S),
            d = d.add(_),
            d.toArray(c, m)
        }
        return VertexData.ComputeNormals(c, this.getIndices(), h),
        u ? (this.setVerticesData(VertexBuffer.PositionKind, c),
        this.setVerticesData(VertexBuffer.NormalKind, h),
        this.setVerticesData(VertexBuffer.UVKind, f)) : (this.updateVerticesData(VertexBuffer.PositionKind, c),
        this.updateVerticesData(VertexBuffer.NormalKind, h)),
        this
    }
    ,
    e.prototype.convertToFlatShadedMesh = function() {
        var t = this.getVerticesDataKinds(), r = {}, n = {}, o = {}, a = !1, s, l;
        for (s = 0; s < t.length; s++) {
            l = t[s];
            var u = this.getVertexBuffer(l);
            if (l === VertexBuffer.NormalKind) {
                a = u.isUpdatable(),
                t.splice(s, 1),
                s--;
                continue
            }
            r[l] = u,
            n[l] = this.getVerticesData(l),
            o[l] = []
        }
        var c = this.subMeshes.slice(0), h = this.getIndices(), f = this.getTotalIndices(), d;
        for (d = 0; d < f; d++) {
            var _ = h[d];
            for (s = 0; s < t.length; s++) {
                l = t[s];
                for (var g = r[l].getStrideSize(), m = 0; m < g; m++)
                    o[l].push(n[l][_ * g + m])
            }
        }
        var v = [], y = o[VertexBuffer.PositionKind], b = this.getScene().useRightHandedSystem, T;
        for (b ? T = this.overrideMaterialSideOrientation === 1 : T = this.overrideMaterialSideOrientation === 0,
        d = 0; d < f; d += 3) {
            h[d] = d,
            h[d + 1] = d + 1,
            h[d + 2] = d + 2;
            var C = Vector3.FromArray(y, d * 3)
              , A = Vector3.FromArray(y, (d + 1) * 3)
              , S = Vector3.FromArray(y, (d + 2) * 3)
              , P = C.subtract(A)
              , R = S.subtract(A)
              , M = Vector3.Normalize(Vector3.Cross(P, R));
            T && M.scaleInPlace(-1);
            for (var x = 0; x < 3; x++)
                v.push(M.x),
                v.push(M.y),
                v.push(M.z)
        }
        for (this.setIndices(h),
        this.setVerticesData(VertexBuffer.NormalKind, v, a),
        s = 0; s < t.length; s++)
            l = t[s],
            this.setVerticesData(l, o[l], r[l].isUpdatable());
        this.releaseSubMeshes();
        for (var I = 0; I < c.length; I++) {
            var w = c[I];
            SubMesh.AddToMesh(w.materialIndex, w.indexStart, w.indexCount, w.indexStart, w.indexCount, this)
        }
        return this.synchronizeInstances(),
        this
    }
    ,
    e.prototype.convertToUnIndexedMesh = function() {
        var t = this.getVerticesDataKinds(), r = {}, n = {}, o = {}, a, s;
        for (a = 0; a < t.length; a++) {
            s = t[a];
            var l = this.getVertexBuffer(s);
            r[s] = l,
            n[s] = r[s].getData(),
            o[s] = []
        }
        var u = this.subMeshes.slice(0), c = this.getIndices(), h = this.getTotalIndices(), f;
        for (f = 0; f < h; f++) {
            var d = c[f];
            for (a = 0; a < t.length; a++) {
                s = t[a];
                for (var _ = r[s].getStrideSize(), g = 0; g < _; g++)
                    o[s].push(n[s][d * _ + g])
            }
        }
        for (f = 0; f < h; f += 3)
            c[f] = f,
            c[f + 1] = f + 1,
            c[f + 2] = f + 2;
        for (this.setIndices(c),
        a = 0; a < t.length; a++)
            s = t[a],
            this.setVerticesData(s, o[s], r[s].isUpdatable());
        this.releaseSubMeshes();
        for (var m = 0; m < u.length; m++) {
            var v = u[m];
            SubMesh.AddToMesh(v.materialIndex, v.indexStart, v.indexCount, v.indexStart, v.indexCount, this)
        }
        return this._unIndexed = !0,
        this.synchronizeInstances(),
        this
    }
    ,
    e.prototype.flipFaces = function(t) {
        t === void 0 && (t = !1);
        var r = VertexData.ExtractFromMesh(this), n;
        if (t && this.isVerticesDataPresent(VertexBuffer.NormalKind) && r.normals)
            for (n = 0; n < r.normals.length; n++)
                r.normals[n] *= -1;
        if (r.indices) {
            var o;
            for (n = 0; n < r.indices.length; n += 3)
                o = r.indices[n + 1],
                r.indices[n + 1] = r.indices[n + 2],
                r.indices[n + 2] = o
        }
        return r.applyToMesh(this, this.isVertexBufferUpdatable(VertexBuffer.PositionKind)),
        this
    }
    ,
    e.prototype.increaseVertices = function(t) {
        var r = VertexData.ExtractFromMesh(this)
          , n = r.uvs && !Array.isArray(r.uvs) && Array.from ? Array.from(r.uvs) : r.uvs
          , o = r.indices && !Array.isArray(r.indices) && Array.from ? Array.from(r.indices) : r.indices
          , a = r.positions && !Array.isArray(r.positions) && Array.from ? Array.from(r.positions) : r.positions
          , s = r.normals && !Array.isArray(r.normals) && Array.from ? Array.from(r.normals) : r.normals;
        if (!o || !a || !s || !n)
            Logger$2.Warn("VertexData contains null entries");
        else {
            r.indices = o,
            r.positions = a,
            r.normals = s,
            r.uvs = n;
            for (var l = t + 1, u = new Array, c = 0; c < l + 1; c++)
                u[c] = new Array;
            for (var h, f, d = new Vector3(0,0,0), _ = new Vector3(0,0,0), g = new Vector2(0,0), m = new Array, v = new Array, y = new Array, b, T = a.length, C = n.length, c = 0; c < o.length; c += 3) {
                v[0] = o[c],
                v[1] = o[c + 1],
                v[2] = o[c + 2];
                for (var A = 0; A < 3; A++)
                    if (h = v[A],
                    f = v[(A + 1) % 3],
                    y[h] === void 0 && y[f] === void 0 ? (y[h] = new Array,
                    y[f] = new Array) : (y[h] === void 0 && (y[h] = new Array),
                    y[f] === void 0 && (y[f] = new Array)),
                    y[h][f] === void 0 && y[f][h] === void 0) {
                        y[h][f] = [],
                        d.x = (a[3 * f] - a[3 * h]) / l,
                        d.y = (a[3 * f + 1] - a[3 * h + 1]) / l,
                        d.z = (a[3 * f + 2] - a[3 * h + 2]) / l,
                        _.x = (s[3 * f] - s[3 * h]) / l,
                        _.y = (s[3 * f + 1] - s[3 * h + 1]) / l,
                        _.z = (s[3 * f + 2] - s[3 * h + 2]) / l,
                        g.x = (n[2 * f] - n[2 * h]) / l,
                        g.y = (n[2 * f + 1] - n[2 * h + 1]) / l,
                        y[h][f].push(h);
                        for (var S = 1; S < l; S++)
                            y[h][f].push(a.length / 3),
                            a[T] = a[3 * h] + S * d.x,
                            s[T++] = s[3 * h] + S * _.x,
                            a[T] = a[3 * h + 1] + S * d.y,
                            s[T++] = s[3 * h + 1] + S * _.y,
                            a[T] = a[3 * h + 2] + S * d.z,
                            s[T++] = s[3 * h + 2] + S * _.z,
                            n[C++] = n[2 * h] + S * g.x,
                            n[C++] = n[2 * h + 1] + S * g.y;
                        y[h][f].push(f),
                        y[f][h] = new Array,
                        b = y[h][f].length;
                        for (var P = 0; P < b; P++)
                            y[f][h][P] = y[h][f][b - 1 - P]
                    }
                u[0][0] = o[c],
                u[1][0] = y[o[c]][o[c + 1]][1],
                u[1][1] = y[o[c]][o[c + 2]][1];
                for (var S = 2; S < l; S++) {
                    u[S][0] = y[o[c]][o[c + 1]][S],
                    u[S][S] = y[o[c]][o[c + 2]][S],
                    d.x = (a[3 * u[S][S]] - a[3 * u[S][0]]) / S,
                    d.y = (a[3 * u[S][S] + 1] - a[3 * u[S][0] + 1]) / S,
                    d.z = (a[3 * u[S][S] + 2] - a[3 * u[S][0] + 2]) / S,
                    _.x = (s[3 * u[S][S]] - s[3 * u[S][0]]) / S,
                    _.y = (s[3 * u[S][S] + 1] - s[3 * u[S][0] + 1]) / S,
                    _.z = (s[3 * u[S][S] + 2] - s[3 * u[S][0] + 2]) / S,
                    g.x = (n[2 * u[S][S]] - n[2 * u[S][0]]) / S,
                    g.y = (n[2 * u[S][S] + 1] - n[2 * u[S][0] + 1]) / S;
                    for (var A = 1; A < S; A++)
                        u[S][A] = a.length / 3,
                        a[T] = a[3 * u[S][0]] + A * d.x,
                        s[T++] = s[3 * u[S][0]] + A * _.x,
                        a[T] = a[3 * u[S][0] + 1] + A * d.y,
                        s[T++] = s[3 * u[S][0] + 1] + A * _.y,
                        a[T] = a[3 * u[S][0] + 2] + A * d.z,
                        s[T++] = s[3 * u[S][0] + 2] + A * _.z,
                        n[C++] = n[2 * u[S][0]] + A * g.x,
                        n[C++] = n[2 * u[S][0] + 1] + A * g.y
                }
                u[l] = y[o[c + 1]][o[c + 2]],
                m.push(u[0][0], u[1][0], u[1][1]);
                for (var S = 1; S < l; S++) {
                    for (var A = 0; A < S; A++)
                        m.push(u[S][A], u[S + 1][A], u[S + 1][A + 1]),
                        m.push(u[S][A], u[S + 1][A + 1], u[S][A + 1]);
                    m.push(u[S][A], u[S + 1][A], u[S + 1][A + 1])
                }
            }
            r.indices = m,
            r.applyToMesh(this, this.isVertexBufferUpdatable(VertexBuffer.PositionKind))
        }
    }
    ,
    e.prototype.forceSharedVertices = function() {
        var t = VertexData.ExtractFromMesh(this)
          , r = t.uvs
          , n = t.indices
          , o = t.positions
          , a = t.colors;
        if (n === void 0 || o === void 0 || n === null || o === null)
            Logger$2.Warn("VertexData contains empty entries");
        else {
            for (var s = new Array, l = new Array, u = new Array, c = new Array, h = new Array, f = 0, d = {}, _, g, m = 0; m < n.length; m += 3) {
                g = [n[m], n[m + 1], n[m + 2]],
                h = new Array;
                for (var v = 0; v < 3; v++) {
                    h[v] = "";
                    for (var y = 0; y < 3; y++)
                        Math.abs(o[3 * g[v] + y]) < 1e-8 && (o[3 * g[v] + y] = 0),
                        h[v] += o[3 * g[v] + y] + "|"
                }
                if (!(h[0] == h[1] || h[0] == h[2] || h[1] == h[2]))
                    for (var v = 0; v < 3; v++) {
                        if (_ = d[h[v]],
                        _ === void 0) {
                            d[h[v]] = f,
                            _ = f++;
                            for (var y = 0; y < 3; y++)
                                s.push(o[3 * g[v] + y]);
                            if (a != null)
                                for (var y = 0; y < 4; y++)
                                    c.push(a[4 * g[v] + y]);
                            if (r != null)
                                for (var y = 0; y < 2; y++)
                                    u.push(r[2 * g[v] + y])
                        }
                        l.push(_)
                    }
            }
            var b = new Array;
            VertexData.ComputeNormals(s, l, b),
            t.positions = s,
            t.indices = l,
            t.normals = b,
            r != null && (t.uvs = u),
            a != null && (t.colors = c),
            t.applyToMesh(this, this.isVertexBufferUpdatable(VertexBuffer.PositionKind))
        }
    }
    ,
    e._instancedMeshFactory = function(t, r) {
        throw _WarnImport("InstancedMesh")
    }
    ,
    e._PhysicsImpostorParser = function(t, r, n) {
        throw _WarnImport("PhysicsImpostor")
    }
    ,
    e.prototype.createInstance = function(t) {
        return e._instancedMeshFactory(t, this)
    }
    ,
    e.prototype.synchronizeInstances = function() {
        for (var t = 0; t < this.instances.length; t++) {
            var r = this.instances[t];
            r._syncSubMeshes()
        }
        return this
    }
    ,
    e.prototype.optimizeIndices = function(t) {
        var r = this
          , n = this.getIndices()
          , o = this.getVerticesData(VertexBuffer.PositionKind);
        if (!o || !n)
            return this;
        for (var a = new Array, s = 0; s < o.length; s = s + 3)
            a.push(Vector3.FromArray(o, s));
        var l = new Array;
        return AsyncLoop.SyncAsyncForLoop(a.length, 40, function(u) {
            for (var c = a.length - 1 - u, h = a[c], f = 0; f < c; ++f) {
                var d = a[f];
                if (h.equals(d)) {
                    l[c] = f;
                    break
                }
            }
        }, function() {
            for (var u = 0; u < n.length; ++u)
                n[u] = l[n[u]] || n[u];
            var c = r.subMeshes.slice(0);
            r.setIndices(n),
            r.subMeshes = c,
            t && t(r)
        }),
        this
    }
    ,
    e.prototype.serialize = function(t) {
        t.name = this.name,
        t.id = this.id,
        t.uniqueId = this.uniqueId,
        t.type = this.getClassName(),
        Tags && Tags.HasTags(this) && (t.tags = Tags.GetTags(this)),
        t.position = this.position.asArray(),
        this.rotationQuaternion ? t.rotationQuaternion = this.rotationQuaternion.asArray() : this.rotation && (t.rotation = this.rotation.asArray()),
        t.scaling = this.scaling.asArray(),
        this._postMultiplyPivotMatrix ? t.pivotMatrix = this.getPivotMatrix().asArray() : t.localMatrix = this.getPivotMatrix().asArray(),
        t.isEnabled = this.isEnabled(!1),
        t.isVisible = this.isVisible,
        t.infiniteDistance = this.infiniteDistance,
        t.pickable = this.isPickable,
        t.receiveShadows = this.receiveShadows,
        t.billboardMode = this.billboardMode,
        t.visibility = this.visibility,
        t.checkCollisions = this.checkCollisions,
        t.isBlocker = this.isBlocker,
        t.overrideMaterialSideOrientation = this.overrideMaterialSideOrientation,
        this.parent && (t.parentId = this.parent.uniqueId),
        t.isUnIndexed = this.isUnIndexed;
        var r = this._geometry;
        if (r && this.subMeshes) {
            t.geometryUniqueId = r.uniqueId,
            t.geometryId = r.id,
            t.subMeshes = [];
            for (var n = 0; n < this.subMeshes.length; n++) {
                var o = this.subMeshes[n];
                t.subMeshes.push({
                    materialIndex: o.materialIndex,
                    verticesStart: o.verticesStart,
                    verticesCount: o.verticesCount,
                    indexStart: o.indexStart,
                    indexCount: o.indexCount
                })
            }
        }
        if (this.material ? this.material.doNotSerialize || (t.materialId = this.material.id) : (this.material = null,
        t.materialId = this._scene.defaultMaterial.id),
        this.morphTargetManager && (t.morphTargetManagerId = this.morphTargetManager.uniqueId),
        this.skeleton && (t.skeletonId = this.skeleton.id,
        t.numBoneInfluencers = this.numBoneInfluencers),
        this.getScene()._getComponent(SceneComponentConstants.NAME_PHYSICSENGINE)) {
            var a = this.getPhysicsImpostor();
            a && (t.physicsMass = a.getParam("mass"),
            t.physicsFriction = a.getParam("friction"),
            t.physicsRestitution = a.getParam("mass"),
            t.physicsImpostor = a.type)
        }
        this.metadata && (t.metadata = this.metadata),
        t.instances = [];
        for (var s = 0; s < this.instances.length; s++) {
            var l = this.instances[s];
            if (!l.doNotSerialize) {
                var u = {
                    name: l.name,
                    id: l.id,
                    isEnabled: l.isEnabled(!1),
                    isVisible: l.isVisible,
                    isPickable: l.isPickable,
                    checkCollisions: l.checkCollisions,
                    position: l.position.asArray(),
                    scaling: l.scaling.asArray()
                };
                if (l.parent && (u.parentId = l.parent.uniqueId),
                l.rotationQuaternion ? u.rotationQuaternion = l.rotationQuaternion.asArray() : l.rotation && (u.rotation = l.rotation.asArray()),
                this.getScene()._getComponent(SceneComponentConstants.NAME_PHYSICSENGINE)) {
                    var a = l.getPhysicsImpostor();
                    a && (u.physicsMass = a.getParam("mass"),
                    u.physicsFriction = a.getParam("friction"),
                    u.physicsRestitution = a.getParam("mass"),
                    u.physicsImpostor = a.type)
                }
                l.metadata && (u.metadata = l.metadata),
                t.instances.push(u),
                SerializationHelper.AppendSerializedAnimations(l, u),
                u.ranges = l.serializeAnimationRanges()
            }
        }
        if (this._thinInstanceDataStorage.instancesCount && this._thinInstanceDataStorage.matrixData && (t.thinInstances = {
            instancesCount: this._thinInstanceDataStorage.instancesCount,
            matrixData: Tools.SliceToArray(this._thinInstanceDataStorage.matrixData),
            matrixBufferSize: this._thinInstanceDataStorage.matrixBufferSize,
            enablePicking: this.thinInstanceEnablePicking
        },
        this._userThinInstanceBuffersStorage)) {
            var c = {
                data: {},
                sizes: {},
                strides: {}
            };
            for (var h in this._userThinInstanceBuffersStorage.data)
                c.data[h] = Tools.SliceToArray(this._userThinInstanceBuffersStorage.data[h]),
                c.sizes[h] = this._userThinInstanceBuffersStorage.sizes[h],
                c.strides[h] = this._userThinInstanceBuffersStorage.strides[h];
            t.thinInstances.userThinInstance = c
        }
        SerializationHelper.AppendSerializedAnimations(this, t),
        t.ranges = this.serializeAnimationRanges(),
        t.layerMask = this.layerMask,
        t.alphaIndex = this.alphaIndex,
        t.hasVertexAlpha = this.hasVertexAlpha,
        t.overlayAlpha = this.overlayAlpha,
        t.overlayColor = this.overlayColor.asArray(),
        t.renderOverlay = this.renderOverlay,
        t.applyFog = this.applyFog,
        this.actionManager && (t.actions = this.actionManager.serialize(this.name))
    }
    ,
    e.prototype._syncGeometryWithMorphTargetManager = function() {
        if (!!this.geometry) {
            this._markSubMeshesAsAttributesDirty();
            var t = this._internalAbstractMeshDataInfo._morphTargetManager;
            if (t && t.vertexCount) {
                if (t.vertexCount !== this.getTotalVertices()) {
                    Logger$2.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count."),
                    this.morphTargetManager = null;
                    return
                }
                if (t.isUsingTextureForTargets)
                    return;
                for (var r = 0; r < t.numInfluencers; r++) {
                    var n = t.getActiveTarget(r)
                      , o = n.getPositions();
                    if (!o) {
                        Logger$2.Error("Invalid morph target. Target must have positions.");
                        return
                    }
                    this.geometry.setVerticesData(VertexBuffer.PositionKind + r, o, !1, 3);
                    var a = n.getNormals();
                    a && this.geometry.setVerticesData(VertexBuffer.NormalKind + r, a, !1, 3);
                    var s = n.getTangents();
                    s && this.geometry.setVerticesData(VertexBuffer.TangentKind + r, s, !1, 3);
                    var l = n.getUVs();
                    l && this.geometry.setVerticesData(VertexBuffer.UVKind + "_" + r, l, !1, 2)
                }
            } else
                for (var r = 0; this.geometry.isVerticesDataPresent(VertexBuffer.PositionKind + r); )
                    this.geometry.removeVerticesData(VertexBuffer.PositionKind + r),
                    this.geometry.isVerticesDataPresent(VertexBuffer.NormalKind + r) && this.geometry.removeVerticesData(VertexBuffer.NormalKind + r),
                    this.geometry.isVerticesDataPresent(VertexBuffer.TangentKind + r) && this.geometry.removeVerticesData(VertexBuffer.TangentKind + r),
                    this.geometry.isVerticesDataPresent(VertexBuffer.UVKind + r) && this.geometry.removeVerticesData(VertexBuffer.UVKind + "_" + r),
                    r++
        }
    }
    ,
    e.Parse = function(t, r, n) {
        var o;
        if (t.type && t.type === "LinesMesh" ? o = e._LinesMeshParser(t, r) : t.type && t.type === "GroundMesh" ? o = e._GroundMeshParser(t, r) : o = new e(t.name,r),
        o.id = t.id,
        Tags && Tags.AddTagsTo(o, t.tags),
        o.position = Vector3.FromArray(t.position),
        t.metadata !== void 0 && (o.metadata = t.metadata),
        t.rotationQuaternion ? o.rotationQuaternion = Quaternion.FromArray(t.rotationQuaternion) : t.rotation && (o.rotation = Vector3.FromArray(t.rotation)),
        o.scaling = Vector3.FromArray(t.scaling),
        t.localMatrix ? o.setPreTransformMatrix(Matrix.FromArray(t.localMatrix)) : t.pivotMatrix && o.setPivotMatrix(Matrix.FromArray(t.pivotMatrix)),
        o.setEnabled(t.isEnabled),
        o.isVisible = t.isVisible,
        o.infiniteDistance = t.infiniteDistance,
        o.showBoundingBox = t.showBoundingBox,
        o.showSubMeshesBoundingBox = t.showSubMeshesBoundingBox,
        t.applyFog !== void 0 && (o.applyFog = t.applyFog),
        t.pickable !== void 0 && (o.isPickable = t.pickable),
        t.alphaIndex !== void 0 && (o.alphaIndex = t.alphaIndex),
        o.receiveShadows = t.receiveShadows,
        o.billboardMode = t.billboardMode,
        t.visibility !== void 0 && (o.visibility = t.visibility),
        o.checkCollisions = t.checkCollisions,
        o.overrideMaterialSideOrientation = t.overrideMaterialSideOrientation,
        t.isBlocker !== void 0 && (o.isBlocker = t.isBlocker),
        o._shouldGenerateFlatShading = t.useFlatShading,
        t.freezeWorldMatrix && (o._waitingData.freezeWorldMatrix = t.freezeWorldMatrix),
        t.parentId && (o._waitingParentId = t.parentId),
        t.actions !== void 0 && (o._waitingData.actions = t.actions),
        t.overlayAlpha !== void 0 && (o.overlayAlpha = t.overlayAlpha),
        t.overlayColor !== void 0 && (o.overlayColor = Color3.FromArray(t.overlayColor)),
        t.renderOverlay !== void 0 && (o.renderOverlay = t.renderOverlay),
        o.isUnIndexed = !!t.isUnIndexed,
        o.hasVertexAlpha = t.hasVertexAlpha,
        t.delayLoadingFile ? (o.delayLoadState = 4,
        o.delayLoadingFile = n + t.delayLoadingFile,
        o.buildBoundingInfo(Vector3.FromArray(t.boundingBoxMinimum), Vector3.FromArray(t.boundingBoxMaximum)),
        t._binaryInfo && (o._binaryInfo = t._binaryInfo),
        o._delayInfo = [],
        t.hasUVs && o._delayInfo.push(VertexBuffer.UVKind),
        t.hasUVs2 && o._delayInfo.push(VertexBuffer.UV2Kind),
        t.hasUVs3 && o._delayInfo.push(VertexBuffer.UV3Kind),
        t.hasUVs4 && o._delayInfo.push(VertexBuffer.UV4Kind),
        t.hasUVs5 && o._delayInfo.push(VertexBuffer.UV5Kind),
        t.hasUVs6 && o._delayInfo.push(VertexBuffer.UV6Kind),
        t.hasColors && o._delayInfo.push(VertexBuffer.ColorKind),
        t.hasMatricesIndices && o._delayInfo.push(VertexBuffer.MatricesIndicesKind),
        t.hasMatricesWeights && o._delayInfo.push(VertexBuffer.MatricesWeightsKind),
        o._delayLoadingFunction = Geometry._ImportGeometry,
        SceneLoaderFlags.ForceFullSceneLoadingForIncremental && o._checkDelayState()) : Geometry._ImportGeometry(t, o),
        t.materialId ? o.setMaterialById(t.materialId) : o.material = null,
        t.morphTargetManagerId > -1 && (o.morphTargetManager = r.getMorphTargetManagerById(t.morphTargetManagerId)),
        t.skeletonId !== void 0 && t.skeletonId !== null && (o.skeleton = r.getLastSkeletonById(t.skeletonId),
        t.numBoneInfluencers && (o.numBoneInfluencers = t.numBoneInfluencers)),
        t.animations) {
            for (var a = 0; a < t.animations.length; a++) {
                var s = t.animations[a]
                  , l = GetClass("BABYLON.Animation");
                l && o.animations.push(l.Parse(s))
            }
            Node$2.ParseAnimationRanges(o, t, r)
        }
        if (t.autoAnimate && r.beginAnimation(o, t.autoAnimateFrom, t.autoAnimateTo, t.autoAnimateLoop, t.autoAnimateSpeed || 1),
        t.layerMask && !isNaN(t.layerMask) ? o.layerMask = Math.abs(parseInt(t.layerMask)) : o.layerMask = 268435455,
        t.physicsImpostor && e._PhysicsImpostorParser(r, o, t),
        t.lodMeshIds && (o._waitingData.lods = {
            ids: t.lodMeshIds,
            distances: t.lodDistances ? t.lodDistances : null,
            coverages: t.lodCoverages ? t.lodCoverages : null
        }),
        t.instances)
            for (var u = 0; u < t.instances.length; u++) {
                var c = t.instances[u]
                  , h = o.createInstance(c.name);
                if (c.id && (h.id = c.id),
                Tags && (c.tags ? Tags.AddTagsTo(h, c.tags) : Tags.AddTagsTo(h, t.tags)),
                h.position = Vector3.FromArray(c.position),
                c.metadata !== void 0 && (h.metadata = c.metadata),
                c.parentId && (h._waitingParentId = c.parentId),
                c.isEnabled !== void 0 && c.isEnabled !== null && h.setEnabled(c.isEnabled),
                c.isVisible !== void 0 && c.isVisible !== null && (h.isVisible = c.isVisible),
                c.isPickable !== void 0 && c.isPickable !== null && (h.isPickable = c.isPickable),
                c.rotationQuaternion ? h.rotationQuaternion = Quaternion.FromArray(c.rotationQuaternion) : c.rotation && (h.rotation = Vector3.FromArray(c.rotation)),
                h.scaling = Vector3.FromArray(c.scaling),
                c.checkCollisions != null && c.checkCollisions != null && (h.checkCollisions = c.checkCollisions),
                c.pickable != null && c.pickable != null && (h.isPickable = c.pickable),
                c.showBoundingBox != null && c.showBoundingBox != null && (h.showBoundingBox = c.showBoundingBox),
                c.showSubMeshesBoundingBox != null && c.showSubMeshesBoundingBox != null && (h.showSubMeshesBoundingBox = c.showSubMeshesBoundingBox),
                c.alphaIndex != null && c.showSubMeshesBoundingBox != null && (h.alphaIndex = c.alphaIndex),
                c.physicsImpostor && e._PhysicsImpostorParser(r, h, c),
                c.animations) {
                    for (a = 0; a < c.animations.length; a++) {
                        s = c.animations[a];
                        var l = GetClass("BABYLON.Animation");
                        l && h.animations.push(l.Parse(s))
                    }
                    Node$2.ParseAnimationRanges(h, c, r),
                    c.autoAnimate && r.beginAnimation(h, c.autoAnimateFrom, c.autoAnimateTo, c.autoAnimateLoop, c.autoAnimateSpeed || 1)
                }
            }
        if (t.thinInstances) {
            var f = t.thinInstances;
            if (o.thinInstanceEnablePicking = !!f.enablePicking,
            f.matrixData ? (o.thinInstanceSetBuffer("matrix", new Float32Array(f.matrixData), 16, !1),
            o._thinInstanceDataStorage.matrixBufferSize = f.matrixBufferSize,
            o._thinInstanceDataStorage.instancesCount = f.instancesCount) : o._thinInstanceDataStorage.matrixBufferSize = f.matrixBufferSize,
            t.thinInstances.userThinInstance) {
                var d = t.thinInstances.userThinInstance;
                for (var _ in d.data)
                    o.thinInstanceSetBuffer(_, new Float32Array(d.data[_]), d.strides[_], !1),
                    o._userThinInstanceBuffersStorage.sizes[_] = d.sizes[_]
            }
        }
        return o
    }
    ,
    e.prototype.setPositionsForCPUSkinning = function() {
        var t = this._internalMeshDataInfo;
        if (!t._sourcePositions) {
            var r = this.getVerticesData(VertexBuffer.PositionKind);
            if (!r)
                return t._sourcePositions;
            t._sourcePositions = new Float32Array(r),
            this.isVertexBufferUpdatable(VertexBuffer.PositionKind) || this.setVerticesData(VertexBuffer.PositionKind, r, !0)
        }
        return t._sourcePositions
    }
    ,
    e.prototype.setNormalsForCPUSkinning = function() {
        var t = this._internalMeshDataInfo;
        if (!t._sourceNormals) {
            var r = this.getVerticesData(VertexBuffer.NormalKind);
            if (!r)
                return t._sourceNormals;
            t._sourceNormals = new Float32Array(r),
            this.isVertexBufferUpdatable(VertexBuffer.NormalKind) || this.setVerticesData(VertexBuffer.NormalKind, r, !0)
        }
        return t._sourceNormals
    }
    ,
    e.prototype.applySkeleton = function(t) {
        if (!this.geometry)
            return this;
        if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId())
            return this;
        if (this.geometry._softwareSkinningFrameId = this.getScene().getFrameId(),
        !this.isVerticesDataPresent(VertexBuffer.PositionKind))
            return this;
        if (!this.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind))
            return this;
        if (!this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind))
            return this;
        var r = this.isVerticesDataPresent(VertexBuffer.NormalKind)
          , n = this._internalMeshDataInfo;
        if (!n._sourcePositions) {
            var o = this.subMeshes.slice();
            this.setPositionsForCPUSkinning(),
            this.subMeshes = o
        }
        r && !n._sourceNormals && this.setNormalsForCPUSkinning();
        var a = this.getVerticesData(VertexBuffer.PositionKind);
        if (!a)
            return this;
        a instanceof Float32Array || (a = new Float32Array(a));
        var s = this.getVerticesData(VertexBuffer.NormalKind);
        if (r) {
            if (!s)
                return this;
            s instanceof Float32Array || (s = new Float32Array(s))
        }
        var l = this.getVerticesData(VertexBuffer.MatricesIndicesKind)
          , u = this.getVerticesData(VertexBuffer.MatricesWeightsKind);
        if (!u || !l)
            return this;
        for (var c = this.numBoneInfluencers > 4, h = c ? this.getVerticesData(VertexBuffer.MatricesIndicesExtraKind) : null, f = c ? this.getVerticesData(VertexBuffer.MatricesWeightsExtraKind) : null, d = t.getTransformMatrices(this), _ = Vector3.Zero(), g = new Matrix, m = new Matrix, v = 0, y, b = 0; b < a.length; b += 3,
        v += 4) {
            var T;
            for (y = 0; y < 4; y++)
                T = u[v + y],
                T > 0 && (Matrix.FromFloat32ArrayToRefScaled(d, Math.floor(l[v + y] * 16), T, m),
                g.addToSelf(m));
            if (c)
                for (y = 0; y < 4; y++)
                    T = f[v + y],
                    T > 0 && (Matrix.FromFloat32ArrayToRefScaled(d, Math.floor(h[v + y] * 16), T, m),
                    g.addToSelf(m));
            Vector3.TransformCoordinatesFromFloatsToRef(n._sourcePositions[b], n._sourcePositions[b + 1], n._sourcePositions[b + 2], g, _),
            _.toArray(a, b),
            r && (Vector3.TransformNormalFromFloatsToRef(n._sourceNormals[b], n._sourceNormals[b + 1], n._sourceNormals[b + 2], g, _),
            _.toArray(s, b)),
            g.reset()
        }
        return this.updateVerticesData(VertexBuffer.PositionKind, a),
        r && this.updateVerticesData(VertexBuffer.NormalKind, s),
        this
    }
    ,
    e.MinMax = function(t) {
        var r = null
          , n = null;
        return t.forEach(function(o) {
            var a = o.getBoundingInfo()
              , s = a.boundingBox;
            !r || !n ? (r = s.minimumWorld,
            n = s.maximumWorld) : (r.minimizeInPlace(s.minimumWorld),
            n.maximizeInPlace(s.maximumWorld))
        }),
        !r || !n ? {
            min: Vector3.Zero(),
            max: Vector3.Zero()
        } : {
            min: r,
            max: n
        }
    }
    ,
    e.Center = function(t) {
        var r = t instanceof Array ? e.MinMax(t) : t;
        return Vector3.Center(r.min, r.max)
    }
    ,
    e.MergeMeshes = function(t, r, n, o, a, s) {
        return r === void 0 && (r = !0),
        runCoroutineSync(e._MergeMeshesCoroutine(t, r, n, o, a, s, !1))
    }
    ,
    e.MergeMeshesAsync = function(t, r, n, o, a, s) {
        return r === void 0 && (r = !0),
        runCoroutineAsync(e._MergeMeshesCoroutine(t, r, n, o, a, s, !0), createYieldingScheduler())
    }
    ,
    e._MergeMeshesCoroutine = function(t, r, n, o, a, s, l) {
        var u, c, h, f, d, _, g, m, v, y, b, T, C, A, S, P, R, M, x, I, w, O, D, F;
        return r === void 0 && (r = !0),
        __generator(this, function(V) {
            switch (V.label) {
            case 0:
                if (t = t.filter(Boolean),
                t.length === 0)
                    return [2, null];
                if (!n) {
                    for (c = 0,
                    u = 0; u < t.length; u++)
                        if (c += t[u].getTotalVertices(),
                        c >= 65536)
                            return Logger$2.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"),
                            [2, null]
                }
                for (s && (h = null,
                a = !1),
                _ = new Array,
                g = new Array,
                m = new Array,
                u = 0; u < t.length; u++) {
                    if (v = t[u],
                    v.isAnInstance)
                        return Logger$2.Warn("Cannot merge instance meshes."),
                        [2, null];
                    if (a && m.push(v.getTotalIndices()),
                    s)
                        if (v.material)
                            if (y = v.material,
                            y instanceof MultiMaterial) {
                                for (d = 0; d < y.subMaterials.length; d++)
                                    _.indexOf(y.subMaterials[d]) < 0 && _.push(y.subMaterials[d]);
                                for (f = 0; f < v.subMeshes.length; f++)
                                    g.push(_.indexOf(y.subMaterials[v.subMeshes[f].materialIndex])),
                                    m.push(v.subMeshes[f].indexCount)
                            } else
                                for (_.indexOf(y) < 0 && _.push(y),
                                f = 0; f < v.subMeshes.length; f++)
                                    g.push(_.indexOf(y)),
                                    m.push(v.subMeshes[f].indexCount);
                        else
                            for (f = 0; f < v.subMeshes.length; f++)
                                g.push(0),
                                m.push(v.subMeshes[f].indexCount)
                }
                return b = t[0],
                T = function(N) {
                    var L = N.computeWorldMatrix(!0)
                      , k = VertexData.ExtractFromMesh(N, !0, !0);
                    return k.transform(L),
                    k
                }
                ,
                C = T(b),
                l ? [4] : [3, 2];
            case 1:
                V.sent(),
                V.label = 2;
            case 2:
                A = new Array(t.length - 1),
                S = 1,
                V.label = 3;
            case 3:
                return S < t.length ? (A[S - 1] = T(t[S]),
                l ? [4] : [3, 5]) : [3, 6];
            case 4:
                V.sent(),
                V.label = 5;
            case 5:
                return S++,
                [3, 3];
            case 6:
                P = C._mergeCoroutine(A, n, l),
                R = P.next(),
                V.label = 7;
            case 7:
                return R.done ? [3, 10] : l ? [4] : [3, 9];
            case 8:
                V.sent(),
                V.label = 9;
            case 9:
                return R = P.next(),
                [3, 7];
            case 10:
                M = R.value,
                o || (o = new e(b.name + "_merged",b.getScene())),
                x = M._applyToCoroutine(o, void 0, l),
                I = x.next(),
                V.label = 11;
            case 11:
                return I.done ? [3, 14] : l ? [4] : [3, 13];
            case 12:
                V.sent(),
                V.label = 13;
            case 13:
                return I = x.next(),
                [3, 11];
            case 14:
                if (o.checkCollisions = b.checkCollisions,
                o.overrideMaterialSideOrientation = b.overrideMaterialSideOrientation,
                r)
                    for (u = 0; u < t.length; u++)
                        t[u].dispose();
                if (a || s) {
                    for (o.releaseSubMeshes(),
                    u = 0,
                    w = 0; u < m.length; )
                        SubMesh.CreateFromIndices(0, w, m[u], o, void 0, !1),
                        w += m[u],
                        u++;
                    for (O = 0,
                    D = o.subMeshes; O < D.length; O++)
                        F = D[O],
                        F.refreshBoundingInfo();
                    o.computeWorldMatrix(!0)
                }
                if (s) {
                    for (h = new MultiMaterial(b.name + "_merged",b.getScene()),
                    h.subMaterials = _,
                    f = 0; f < o.subMeshes.length; f++)
                        o.subMeshes[f].materialIndex = g[f];
                    o.material = h
                } else
                    o.material = b.material;
                return [2, o]
            }
        })
    }
    ,
    e.prototype.addInstance = function(t) {
        t._indexInSourceMeshInstanceArray = this.instances.length,
        this.instances.push(t)
    }
    ,
    e.prototype.removeInstance = function(t) {
        var r = t._indexInSourceMeshInstanceArray;
        if (r != -1) {
            if (r !== this.instances.length - 1) {
                var n = this.instances[this.instances.length - 1];
                this.instances[r] = n,
                n._indexInSourceMeshInstanceArray = r
            }
            t._indexInSourceMeshInstanceArray = -1,
            this.instances.pop()
        }
    }
    ,
    e.FRONTSIDE = VertexData.FRONTSIDE,
    e.BACKSIDE = VertexData.BACKSIDE,
    e.DOUBLESIDE = VertexData.DOUBLESIDE,
    e.DEFAULTSIDE = VertexData.DEFAULTSIDE,
    e.NO_CAP = 0,
    e.CAP_START = 1,
    e.CAP_END = 2,
    e.CAP_ALL = 3,
    e.NO_FLIP = 0,
    e.FLIP_TILE = 1,
    e.ROTATE_TILE = 2,
    e.FLIP_ROW = 3,
    e.ROTATE_ROW = 4,
    e.FLIP_N_ROTATE_TILE = 5,
    e.FLIP_N_ROTATE_ROW = 6,
    e.CENTER = 0,
    e.LEFT = 1,
    e.RIGHT = 2,
    e.TOP = 3,
    e.BOTTOM = 4,
    e.INSTANCEDMESH_SORT_TRANSPARENT = !1,
    e._GroundMeshParser = function(t, r) {
        throw _WarnImport("GroundMesh")
    }
    ,
    e._LinesMeshParser = function(t, r) {
        throw _WarnImport("LinesMesh")
    }
    ,
    e
}(AbstractMesh);
RegisterClass("BABYLON.Mesh", Mesh);
_injectLTSMesh(Mesh);
var AutoRotationBehavior = function() {
    function i() {
        this._zoomStopsAnimation = !1,
        this._idleRotationSpeed = .05,
        this._idleRotationWaitTime = 2e3,
        this._idleRotationSpinupTime = 2e3,
        this._isPointerDown = !1,
        this._lastFrameTime = null,
        this._lastInteractionTime = -1 / 0,
        this._cameraRotationSpeed = 0,
        this._lastFrameRadius = 0
    }
    return Object.defineProperty(i.prototype, "name", {
        get: function() {
            return "AutoRotation"
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "zoomStopsAnimation", {
        get: function() {
            return this._zoomStopsAnimation
        },
        set: function(e) {
            this._zoomStopsAnimation = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "idleRotationSpeed", {
        get: function() {
            return this._idleRotationSpeed
        },
        set: function(e) {
            this._idleRotationSpeed = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "idleRotationWaitTime", {
        get: function() {
            return this._idleRotationWaitTime
        },
        set: function(e) {
            this._idleRotationWaitTime = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "idleRotationSpinupTime", {
        get: function() {
            return this._idleRotationSpinupTime
        },
        set: function(e) {
            this._idleRotationSpinupTime = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "rotationInProgress", {
        get: function() {
            return Math.abs(this._cameraRotationSpeed) > 0
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.init = function() {}
    ,
    i.prototype.attach = function(e) {
        var t = this;
        this._attachedCamera = e;
        var r = this._attachedCamera.getScene();
        this._onPrePointerObservableObserver = r.onPrePointerObservable.add(function(n) {
            if (n.type === PointerEventTypes.POINTERDOWN) {
                t._isPointerDown = !0;
                return
            }
            n.type === PointerEventTypes.POINTERUP && (t._isPointerDown = !1)
        }),
        this._onAfterCheckInputsObserver = e.onAfterCheckInputsObservable.add(function() {
            var n = PrecisionDate.Now
              , o = 0;
            t._lastFrameTime != null && (o = n - t._lastFrameTime),
            t._lastFrameTime = n,
            t._applyUserInteraction();
            var a = n - t._lastInteractionTime - t._idleRotationWaitTime
              , s = Math.max(Math.min(a / t._idleRotationSpinupTime, 1), 0);
            t._cameraRotationSpeed = t._idleRotationSpeed * s,
            t._attachedCamera && (t._attachedCamera.alpha -= t._cameraRotationSpeed * (o / 1e3))
        })
    }
    ,
    i.prototype.detach = function() {
        if (!!this._attachedCamera) {
            var e = this._attachedCamera.getScene();
            this._onPrePointerObservableObserver && e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),
            this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),
            this._attachedCamera = null
        }
    }
    ,
    i.prototype.resetLastInteractionTime = function(e) {
        this._lastInteractionTime = e != null ? e : PrecisionDate.Now
    }
    ,
    i.prototype._userIsZooming = function() {
        return this._attachedCamera ? this._attachedCamera.inertialRadiusOffset !== 0 : !1
    }
    ,
    i.prototype._shouldAnimationStopForInteraction = function() {
        if (!this._attachedCamera)
            return !1;
        var e = !1;
        return this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0 && (e = !0),
        this._lastFrameRadius = this._attachedCamera.radius,
        this._zoomStopsAnimation ? e : this._userIsZooming()
    }
    ,
    i.prototype._applyUserInteraction = function() {
        this._userIsMoving() && !this._shouldAnimationStopForInteraction() && (this._lastInteractionTime = PrecisionDate.Now)
    }
    ,
    i.prototype._userIsMoving = function() {
        return this._attachedCamera ? this._attachedCamera.inertialAlphaOffset !== 0 || this._attachedCamera.inertialBetaOffset !== 0 || this._attachedCamera.inertialRadiusOffset !== 0 || this._attachedCamera.inertialPanningX !== 0 || this._attachedCamera.inertialPanningY !== 0 || this._isPointerDown : !1
    }
    ,
    i
}(), Orientation;
(function(i) {
    i[i.CW = 0] = "CW",
    i[i.CCW = 1] = "CCW"
}
)(Orientation || (Orientation = {}));
var BezierCurve = function() {
    function i() {}
    return i.Interpolate = function(e, t, r, n, o) {
        for (var a = 1 - 3 * n + 3 * t, s = 3 * n - 6 * t, l = 3 * t, u = e, c = 0; c < 5; c++) {
            var h = u * u
              , f = h * u
              , d = a * f + s * h + l * u
              , _ = 1 / (3 * a * h + 2 * s * u + l);
            u -= (d - e) * _,
            u = Math.min(1, Math.max(0, u))
        }
        return 3 * Math.pow(1 - u, 2) * u * r + 3 * (1 - u) * Math.pow(u, 2) * o + Math.pow(u, 3)
    }
    ,
    i
}()
  , Angle = function() {
    function i(e) {
        this._radians = e,
        this._radians < 0 && (this._radians += 2 * Math.PI)
    }
    return i.prototype.degrees = function() {
        return this._radians * 180 / Math.PI
    }
    ,
    i.prototype.radians = function() {
        return this._radians
    }
    ,
    i.BetweenTwoPoints = function(e, t) {
        var r = t.subtract(e)
          , n = Math.atan2(r.y, r.x);
        return new i(n)
    }
    ,
    i.FromRadians = function(e) {
        return new i(e)
    }
    ,
    i.FromDegrees = function(e) {
        return new i(e * Math.PI / 180)
    }
    ,
    i
}()
  , Arc2 = function() {
    function i(e, t, r) {
        this.startPoint = e,
        this.midPoint = t,
        this.endPoint = r;
        var n = Math.pow(t.x, 2) + Math.pow(t.y, 2)
          , o = (Math.pow(e.x, 2) + Math.pow(e.y, 2) - n) / 2
          , a = (n - Math.pow(r.x, 2) - Math.pow(r.y, 2)) / 2
          , s = (e.x - t.x) * (t.y - r.y) - (t.x - r.x) * (e.y - t.y);
        this.centerPoint = new Vector2((o * (t.y - r.y) - a * (e.y - t.y)) / s,((e.x - t.x) * a - (t.x - r.x) * o) / s),
        this.radius = this.centerPoint.subtract(this.startPoint).length(),
        this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
        var l = this.startAngle.degrees()
          , u = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees()
          , c = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
        u - l > 180 && (u -= 360),
        u - l < -180 && (u += 360),
        c - u > 180 && (c -= 360),
        c - u < -180 && (c += 360),
        this.orientation = u - l < 0 ? Orientation.CW : Orientation.CCW,
        this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? l - c : c - l)
    }
    return i
}()
  , Path2 = function() {
    function i(e, t) {
        this._points = new Array,
        this._length = 0,
        this.closed = !1,
        this._points.push(new Vector2(e,t))
    }
    return i.prototype.addLineTo = function(e, t) {
        if (this.closed)
            return this;
        var r = new Vector2(e,t)
          , n = this._points[this._points.length - 1];
        return this._points.push(r),
        this._length += r.subtract(n).length(),
        this
    }
    ,
    i.prototype.addArcTo = function(e, t, r, n, o) {
        if (o === void 0 && (o = 36),
        this.closed)
            return this;
        var a = this._points[this._points.length - 1]
          , s = new Vector2(e,t)
          , l = new Vector2(r,n)
          , u = new Arc2(a,s,l)
          , c = u.angle.radians() / o;
        u.orientation === Orientation.CW && (c *= -1);
        for (var h = u.startAngle.radians() + c, f = 0; f < o; f++) {
            var d = Math.cos(h) * u.radius + u.centerPoint.x
              , _ = Math.sin(h) * u.radius + u.centerPoint.y;
            this.addLineTo(d, _),
            h += c
        }
        return this
    }
    ,
    i.prototype.close = function() {
        return this.closed = !0,
        this
    }
    ,
    i.prototype.length = function() {
        var e = this._length;
        if (this.closed) {
            var t = this._points[this._points.length - 1]
              , r = this._points[0];
            e += r.subtract(t).length()
        }
        return e
    }
    ,
    i.prototype.getPoints = function() {
        return this._points
    }
    ,
    i.prototype.getPointAtLengthPosition = function(e) {
        if (e < 0 || e > 1)
            return Vector2.Zero();
        for (var t = e * this.length(), r = 0, n = 0; n < this._points.length; n++) {
            var o = (n + 1) % this._points.length
              , a = this._points[n]
              , s = this._points[o]
              , l = s.subtract(a)
              , u = l.length() + r;
            if (t >= r && t <= u) {
                var c = l.normalize()
                  , h = t - r;
                return new Vector2(a.x + c.x * h,a.y + c.y * h)
            }
            r = u
        }
        return Vector2.Zero()
    }
    ,
    i.StartingAt = function(e, t) {
        return new i(e,t)
    }
    ,
    i
}()
  , Path3D = function() {
    function i(e, t, r, n) {
        t === void 0 && (t = null),
        n === void 0 && (n = !1),
        this.path = e,
        this._curve = new Array,
        this._distances = new Array,
        this._tangents = new Array,
        this._normals = new Array,
        this._binormals = new Array,
        this._pointAtData = {
            id: 0,
            point: Vector3.Zero(),
            previousPointArrayIndex: 0,
            position: 0,
            subPosition: 0,
            interpolateReady: !1,
            interpolationMatrix: Matrix.Identity()
        };
        for (var o = 0; o < e.length; o++)
            this._curve[o] = e[o].clone();
        this._raw = r || !1,
        this._alignTangentsWithPath = n,
        this._compute(t, n)
    }
    return i.prototype.getCurve = function() {
        return this._curve
    }
    ,
    i.prototype.getPoints = function() {
        return this._curve
    }
    ,
    i.prototype.length = function() {
        return this._distances[this._distances.length - 1]
    }
    ,
    i.prototype.getTangents = function() {
        return this._tangents
    }
    ,
    i.prototype.getNormals = function() {
        return this._normals
    }
    ,
    i.prototype.getBinormals = function() {
        return this._binormals
    }
    ,
    i.prototype.getDistances = function() {
        return this._distances
    }
    ,
    i.prototype.getPointAt = function(e) {
        return this._updatePointAtData(e).point
    }
    ,
    i.prototype.getTangentAt = function(e, t) {
        return t === void 0 && (t = !1),
        this._updatePointAtData(e, t),
        t ? Vector3.TransformCoordinates(Vector3.Forward(), this._pointAtData.interpolationMatrix) : this._tangents[this._pointAtData.previousPointArrayIndex]
    }
    ,
    i.prototype.getNormalAt = function(e, t) {
        return t === void 0 && (t = !1),
        this._updatePointAtData(e, t),
        t ? Vector3.TransformCoordinates(Vector3.Right(), this._pointAtData.interpolationMatrix) : this._normals[this._pointAtData.previousPointArrayIndex]
    }
    ,
    i.prototype.getBinormalAt = function(e, t) {
        return t === void 0 && (t = !1),
        this._updatePointAtData(e, t),
        t ? Vector3.TransformCoordinates(Vector3.UpReadOnly, this._pointAtData.interpolationMatrix) : this._binormals[this._pointAtData.previousPointArrayIndex]
    }
    ,
    i.prototype.getDistanceAt = function(e) {
        return this.length() * e
    }
    ,
    i.prototype.getPreviousPointIndexAt = function(e) {
        return this._updatePointAtData(e),
        this._pointAtData.previousPointArrayIndex
    }
    ,
    i.prototype.getSubPositionAt = function(e) {
        return this._updatePointAtData(e),
        this._pointAtData.subPosition
    }
    ,
    i.prototype.getClosestPositionTo = function(e) {
        for (var t = Number.MAX_VALUE, r = 0, n = 0; n < this._curve.length - 1; n++) {
            var o = this._curve[n + 0]
              , a = this._curve[n + 1].subtract(o).normalize()
              , s = this._distances[n + 1] - this._distances[n + 0]
              , l = Math.min(Math.max(Vector3.Dot(a, e.subtract(o).normalize()), 0) * Vector3.Distance(o, e) / s, 1)
              , u = Vector3.Distance(o.add(a.scale(l * s)), e);
            u < t && (t = u,
            r = (this._distances[n + 0] + s * l) / this.length())
        }
        return r
    }
    ,
    i.prototype.slice = function(e, t) {
        if (e === void 0 && (e = 0),
        t === void 0 && (t = 1),
        e < 0 && (e = 1 - e * -1 % 1),
        t < 0 && (t = 1 - t * -1 % 1),
        e > t) {
            var r = e;
            e = t,
            t = r
        }
        var n = this.getCurve()
          , o = this.getPointAt(e)
          , a = this.getPreviousPointIndexAt(e)
          , s = this.getPointAt(t)
          , l = this.getPreviousPointIndexAt(t) + 1
          , u = [];
        return e !== 0 && (a++,
        u.push(o)),
        u.push.apply(u, n.slice(a, l)),
        (t !== 1 || e === 1) && u.push(s),
        new i(u,this.getNormalAt(e),this._raw,this._alignTangentsWithPath)
    }
    ,
    i.prototype.update = function(e, t, r) {
        t === void 0 && (t = null),
        r === void 0 && (r = !1);
        for (var n = 0; n < e.length; n++)
            this._curve[n].x = e[n].x,
            this._curve[n].y = e[n].y,
            this._curve[n].z = e[n].z;
        return this._compute(t, r),
        this
    }
    ,
    i.prototype._compute = function(e, t) {
        t === void 0 && (t = !1);
        var r = this._curve.length;
        if (!(r < 2)) {
            this._tangents[0] = this._getFirstNonNullVector(0),
            this._raw || this._tangents[0].normalize(),
            this._tangents[r - 1] = this._curve[r - 1].subtract(this._curve[r - 2]),
            this._raw || this._tangents[r - 1].normalize();
            var n = this._tangents[0]
              , o = this._normalVector(n, e);
            this._normals[0] = o,
            this._raw || this._normals[0].normalize(),
            this._binormals[0] = Vector3.Cross(n, this._normals[0]),
            this._raw || this._binormals[0].normalize(),
            this._distances[0] = 0;
            for (var a, s, l, u, c, h = 1; h < r; h++)
                a = this._getLastNonNullVector(h),
                h < r - 1 && (s = this._getFirstNonNullVector(h),
                this._tangents[h] = t ? s : a.add(s),
                this._tangents[h].normalize()),
                this._distances[h] = this._distances[h - 1] + this._curve[h].subtract(this._curve[h - 1]).length(),
                l = this._tangents[h],
                c = this._binormals[h - 1],
                this._normals[h] = Vector3.Cross(c, l),
                this._raw || (this._normals[h].length() === 0 ? (u = this._normals[h - 1],
                this._normals[h] = u.clone()) : this._normals[h].normalize()),
                this._binormals[h] = Vector3.Cross(l, this._normals[h]),
                this._raw || this._binormals[h].normalize();
            this._pointAtData.id = NaN
        }
    }
    ,
    i.prototype._getFirstNonNullVector = function(e) {
        for (var t = 1, r = this._curve[e + t].subtract(this._curve[e]); r.length() === 0 && e + t + 1 < this._curve.length; )
            t++,
            r = this._curve[e + t].subtract(this._curve[e]);
        return r
    }
    ,
    i.prototype._getLastNonNullVector = function(e) {
        for (var t = 1, r = this._curve[e].subtract(this._curve[e - t]); r.length() === 0 && e > t + 1; )
            t++,
            r = this._curve[e].subtract(this._curve[e - t]);
        return r
    }
    ,
    i.prototype._normalVector = function(e, t) {
        var r, n = e.length();
        if (n === 0 && (n = 1),
        t == null) {
            var o;
            Scalar.WithinEpsilon(Math.abs(e.y) / n, 1, Epsilon) ? Scalar.WithinEpsilon(Math.abs(e.x) / n, 1, Epsilon) ? Scalar.WithinEpsilon(Math.abs(e.z) / n, 1, Epsilon) ? o = Vector3.Zero() : o = new Vector3(0,0,1) : o = new Vector3(1,0,0) : o = new Vector3(0,-1,0),
            r = Vector3.Cross(e, o)
        } else
            r = Vector3.Cross(e, t),
            Vector3.CrossToRef(r, e, r);
        return r.normalize(),
        r
    }
    ,
    i.prototype._updatePointAtData = function(e, t) {
        if (t === void 0 && (t = !1),
        this._pointAtData.id === e)
            return this._pointAtData.interpolateReady || this._updateInterpolationMatrix(),
            this._pointAtData;
        this._pointAtData.id = e;
        var r = this.getPoints();
        if (e <= 0)
            return this._setPointAtData(0, 0, r[0], 0, t);
        if (e >= 1)
            return this._setPointAtData(1, 1, r[r.length - 1], r.length - 1, t);
        for (var n = r[0], o, a = 0, s = e * this.length(), l = 1; l < r.length; l++) {
            o = r[l];
            var u = Vector3.Distance(n, o);
            if (a += u,
            a === s)
                return this._setPointAtData(e, 1, o, l, t);
            if (a > s) {
                var c = a - s
                  , h = c / u
                  , f = n.subtract(o)
                  , d = o.add(f.scaleInPlace(h));
                return this._setPointAtData(e, 1 - h, d, l - 1, t)
            }
            n = o
        }
        return this._pointAtData
    }
    ,
    i.prototype._setPointAtData = function(e, t, r, n, o) {
        return this._pointAtData.point = r,
        this._pointAtData.position = e,
        this._pointAtData.subPosition = t,
        this._pointAtData.previousPointArrayIndex = n,
        this._pointAtData.interpolateReady = o,
        o && this._updateInterpolationMatrix(),
        this._pointAtData
    }
    ,
    i.prototype._updateInterpolationMatrix = function() {
        this._pointAtData.interpolationMatrix = Matrix.Identity();
        var e = this._pointAtData.previousPointArrayIndex;
        if (e !== this._tangents.length - 1) {
            var t = e + 1
              , r = this._tangents[e].clone()
              , n = this._normals[e].clone()
              , o = this._binormals[e].clone()
              , a = this._tangents[t].clone()
              , s = this._normals[t].clone()
              , l = this._binormals[t].clone()
              , u = Quaternion.RotationQuaternionFromAxis(n, o, r)
              , c = Quaternion.RotationQuaternionFromAxis(s, l, a)
              , h = Quaternion.Slerp(u, c, this._pointAtData.subPosition);
            h.toRotationMatrix(this._pointAtData.interpolationMatrix)
        }
    }
    ,
    i
}()
  , Curve3 = function() {
    function i(e) {
        this._length = 0,
        this._points = e,
        this._length = this._computeLength(e)
    }
    return i.CreateQuadraticBezier = function(e, t, r, n) {
        n = n > 2 ? n : 3;
        for (var o = new Array, a = function(l, u, c, h) {
            var f = (1 - l) * (1 - l) * u + 2 * l * (1 - l) * c + l * l * h;
            return f
        }, s = 0; s <= n; s++)
            o.push(new Vector3(a(s / n, e.x, t.x, r.x),a(s / n, e.y, t.y, r.y),a(s / n, e.z, t.z, r.z)));
        return new i(o)
    }
    ,
    i.CreateCubicBezier = function(e, t, r, n, o) {
        o = o > 3 ? o : 4;
        for (var a = new Array, s = function(u, c, h, f, d) {
            var _ = (1 - u) * (1 - u) * (1 - u) * c + 3 * u * (1 - u) * (1 - u) * h + 3 * u * u * (1 - u) * f + u * u * u * d;
            return _
        }, l = 0; l <= o; l++)
            a.push(new Vector3(s(l / o, e.x, t.x, r.x, n.x),s(l / o, e.y, t.y, r.y, n.y),s(l / o, e.z, t.z, r.z, n.z)));
        return new i(a)
    }
    ,
    i.CreateHermiteSpline = function(e, t, r, n, o) {
        for (var a = new Array, s = 1 / o, l = 0; l <= o; l++)
            a.push(Vector3.Hermite(e, t, r, n, l * s));
        return new i(a)
    }
    ,
    i.CreateCatmullRomSpline = function(e, t, r) {
        var n = new Array
          , o = 1 / t
          , a = 0;
        if (r) {
            for (var s = e.length, l = 0; l < s; l++) {
                a = 0;
                for (var u = 0; u < t; u++)
                    n.push(Vector3.CatmullRom(e[l % s], e[(l + 1) % s], e[(l + 2) % s], e[(l + 3) % s], a)),
                    a += o
            }
            n.push(n[0])
        } else {
            var c = new Array;
            c.push(e[0].clone()),
            Array.prototype.push.apply(c, e),
            c.push(e[e.length - 1].clone());
            for (var l = 0; l < c.length - 3; l++) {
                a = 0;
                for (var u = 0; u < t; u++)
                    n.push(Vector3.CatmullRom(c[l], c[l + 1], c[l + 2], c[l + 3], a)),
                    a += o
            }
            l--,
            n.push(Vector3.CatmullRom(c[l], c[l + 1], c[l + 2], c[l + 3], a))
        }
        return new i(n)
    }
    ,
    i.prototype.getPoints = function() {
        return this._points
    }
    ,
    i.prototype.length = function() {
        return this._length
    }
    ,
    i.prototype.continue = function(e) {
        for (var t = this._points[this._points.length - 1], r = this._points.slice(), n = e.getPoints(), o = 1; o < n.length; o++)
            r.push(n[o].subtract(n[0]).add(t));
        var a = new i(r);
        return a
    }
    ,
    i.prototype._computeLength = function(e) {
        for (var t = 0, r = 1; r < e.length; r++)
            t += e[r].subtract(e[r - 1]).length();
        return t
    }
    ,
    i
}()
  , EasingFunction = function() {
    function i() {
        this._easingMode = i.EASINGMODE_EASEIN
    }
    return i.prototype.setEasingMode = function(e) {
        var t = Math.min(Math.max(e, 0), 2);
        this._easingMode = t
    }
    ,
    i.prototype.getEasingMode = function() {
        return this._easingMode
    }
    ,
    i.prototype.easeInCore = function(e) {
        throw new Error("You must implement this method")
    }
    ,
    i.prototype.ease = function(e) {
        switch (this._easingMode) {
        case i.EASINGMODE_EASEIN:
            return this.easeInCore(e);
        case i.EASINGMODE_EASEOUT:
            return 1 - this.easeInCore(1 - e)
        }
        return e >= .5 ? (1 - this.easeInCore((1 - e) * 2)) * .5 + .5 : this.easeInCore(e * 2) * .5
    }
    ,
    i.EASINGMODE_EASEIN = 0,
    i.EASINGMODE_EASEOUT = 1,
    i.EASINGMODE_EASEINOUT = 2,
    i
}()
  , CircleEase = function(i) {
    __extends(e, i);
    function e() {
        return i !== null && i.apply(this, arguments) || this
    }
    return e.prototype.easeInCore = function(t) {
        return t = Math.max(0, Math.min(1, t)),
        1 - Math.sqrt(1 - t * t)
    }
    ,
    e
}(EasingFunction)
  , BackEase = function(i) {
    __extends(e, i);
    function e(t) {
        t === void 0 && (t = 1);
        var r = i.call(this) || this;
        return r.amplitude = t,
        r
    }
    return e.prototype.easeInCore = function(t) {
        var r = Math.max(0, this.amplitude);
        return Math.pow(t, 3) - t * r * Math.sin(3.141592653589793 * t)
    }
    ,
    e
}(EasingFunction);
(function(i) {
    __extends(e, i);
    function e(t, r) {
        t === void 0 && (t = 3),
        r === void 0 && (r = 2);
        var n = i.call(this) || this;
        return n.bounces = t,
        n.bounciness = r,
        n
    }
    return e.prototype.easeInCore = function(t) {
        var r = Math.max(0, this.bounces)
          , n = this.bounciness;
        n <= 1 && (n = 1.001);
        var o = Math.pow(n, r)
          , a = 1 - n
          , s = (1 - o) / a + o * .5
          , l = t * s
          , u = Math.log(-l * (1 - n) + 1) / Math.log(n)
          , c = Math.floor(u)
          , h = c + 1
          , f = (1 - Math.pow(n, c)) / (a * s)
          , d = (1 - Math.pow(n, h)) / (a * s)
          , _ = (f + d) * .5
          , g = t - _
          , m = _ - f;
        return -Math.pow(1 / n, r - c) / (m * m) * (g - m) * (g + m)
    }
    ,
    e
}
)(EasingFunction);
(function(i) {
    __extends(e, i);
    function e() {
        return i !== null && i.apply(this, arguments) || this
    }
    return e.prototype.easeInCore = function(t) {
        return t * t * t
    }
    ,
    e
}
)(EasingFunction);
(function(i) {
    __extends(e, i);
    function e(t, r) {
        t === void 0 && (t = 3),
        r === void 0 && (r = 3);
        var n = i.call(this) || this;
        return n.oscillations = t,
        n.springiness = r,
        n
    }
    return e.prototype.easeInCore = function(t) {
        var r, n = Math.max(0, this.oscillations), o = Math.max(0, this.springiness);
        return o == 0 ? r = t : r = (Math.exp(o * t) - 1) / (Math.exp(o) - 1),
        r * Math.sin((6.283185307179586 * n + 1.5707963267948966) * t)
    }
    ,
    e
}
)(EasingFunction);
var ExponentialEase = function(i) {
    __extends(e, i);
    function e(t) {
        t === void 0 && (t = 2);
        var r = i.call(this) || this;
        return r.exponent = t,
        r
    }
    return e.prototype.easeInCore = function(t) {
        return this.exponent <= 0 ? t : (Math.exp(this.exponent * t) - 1) / (Math.exp(this.exponent) - 1)
    }
    ,
    e
}(EasingFunction);
(function(i) {
    __extends(e, i);
    function e(t) {
        t === void 0 && (t = 2);
        var r = i.call(this) || this;
        return r.power = t,
        r
    }
    return e.prototype.easeInCore = function(t) {
        var r = Math.max(0, this.power);
        return Math.pow(t, r)
    }
    ,
    e
}
)(EasingFunction);
(function(i) {
    __extends(e, i);
    function e() {
        return i !== null && i.apply(this, arguments) || this
    }
    return e.prototype.easeInCore = function(t) {
        return t * t
    }
    ,
    e
}
)(EasingFunction);
(function(i) {
    __extends(e, i);
    function e() {
        return i !== null && i.apply(this, arguments) || this
    }
    return e.prototype.easeInCore = function(t) {
        return t * t * t * t
    }
    ,
    e
}
)(EasingFunction);
(function(i) {
    __extends(e, i);
    function e() {
        return i !== null && i.apply(this, arguments) || this
    }
    return e.prototype.easeInCore = function(t) {
        return t * t * t * t * t
    }
    ,
    e
}
)(EasingFunction);
var SineEase = function(i) {
    __extends(e, i);
    function e() {
        return i !== null && i.apply(this, arguments) || this
    }
    return e.prototype.easeInCore = function(t) {
        return 1 - Math.sin(1.5707963267948966 * (1 - t))
    }
    ,
    e
}(EasingFunction);
(function(i) {
    __extends(e, i);
    function e(t, r, n, o) {
        t === void 0 && (t = 0),
        r === void 0 && (r = 0),
        n === void 0 && (n = 1),
        o === void 0 && (o = 1);
        var a = i.call(this) || this;
        return a.x1 = t,
        a.y1 = r,
        a.x2 = n,
        a.y2 = o,
        a
    }
    return e.prototype.easeInCore = function(t) {
        return BezierCurve.Interpolate(t, this.x1, this.y1, this.x2, this.y2)
    }
    ,
    e
}
)(EasingFunction);
var BouncingBehavior = function() {
    function i() {
        this.transitionDuration = 450,
        this.lowerRadiusTransitionRange = 2,
        this.upperRadiusTransitionRange = -2,
        this._autoTransitionRange = !1,
        this._radiusIsAnimating = !1,
        this._radiusBounceTransition = null,
        this._animatables = new Array
    }
    return Object.defineProperty(i.prototype, "name", {
        get: function() {
            return "Bouncing"
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "autoTransitionRange", {
        get: function() {
            return this._autoTransitionRange
        },
        set: function(e) {
            var t = this;
            if (this._autoTransitionRange !== e) {
                this._autoTransitionRange = e;
                var r = this._attachedCamera;
                !r || (e ? this._onMeshTargetChangedObserver = r.onMeshTargetChangedObservable.add(function(n) {
                    if (!!n) {
                        n.computeWorldMatrix(!0);
                        var o = n.getBoundingInfo().diagonalLength;
                        t.lowerRadiusTransitionRange = o * .05,
                        t.upperRadiusTransitionRange = o * .05
                    }
                }) : this._onMeshTargetChangedObserver && r.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver))
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.init = function() {}
    ,
    i.prototype.attach = function(e) {
        var t = this;
        this._attachedCamera = e,
        this._onAfterCheckInputsObserver = e.onAfterCheckInputsObservable.add(function() {
            !t._attachedCamera || (t._isRadiusAtLimit(t._attachedCamera.lowerRadiusLimit) && t._applyBoundRadiusAnimation(t.lowerRadiusTransitionRange),
            t._isRadiusAtLimit(t._attachedCamera.upperRadiusLimit) && t._applyBoundRadiusAnimation(t.upperRadiusTransitionRange))
        })
    }
    ,
    i.prototype.detach = function() {
        !this._attachedCamera || (this._onAfterCheckInputsObserver && this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),
        this._onMeshTargetChangedObserver && this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),
        this._attachedCamera = null)
    }
    ,
    i.prototype._isRadiusAtLimit = function(e) {
        return this._attachedCamera ? this._attachedCamera.radius === e && !this._radiusIsAnimating : !1
    }
    ,
    i.prototype._applyBoundRadiusAnimation = function(e) {
        var t = this;
        if (!!this._attachedCamera) {
            this._radiusBounceTransition || (i.EasingFunction.setEasingMode(i.EasingMode),
            this._radiusBounceTransition = Animation.CreateAnimation("radius", Animation.ANIMATIONTYPE_FLOAT, 60, i.EasingFunction)),
            this._cachedWheelPrecision = this._attachedCamera.wheelPrecision,
            this._attachedCamera.wheelPrecision = 1 / 0,
            this._attachedCamera.inertialRadiusOffset = 0,
            this.stopAllAnimations(),
            this._radiusIsAnimating = !0;
            var r = Animation.TransitionTo("radius", this._attachedCamera.radius + e, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function() {
                return t._clearAnimationLocks()
            });
            r && this._animatables.push(r)
        }
    }
    ,
    i.prototype._clearAnimationLocks = function() {
        this._radiusIsAnimating = !1,
        this._attachedCamera && (this._attachedCamera.wheelPrecision = this._cachedWheelPrecision)
    }
    ,
    i.prototype.stopAllAnimations = function() {
        for (this._attachedCamera && (this._attachedCamera.animations = []); this._animatables.length; )
            this._animatables[0].onAnimationEnd = null,
            this._animatables[0].stop(),
            this._animatables.shift()
    }
    ,
    i.EasingFunction = new BackEase(.3),
    i.EasingMode = EasingFunction.EASINGMODE_EASEOUT,
    i
}()
  , FramingBehavior = function() {
    function i() {
        this.onTargetFramingAnimationEndObservable = new Observable,
        this._mode = i.FitFrustumSidesMode,
        this._radiusScale = 1,
        this._positionScale = .5,
        this._defaultElevation = .3,
        this._elevationReturnTime = 1500,
        this._elevationReturnWaitTime = 1e3,
        this._zoomStopsAnimation = !1,
        this._framingTime = 1500,
        this.autoCorrectCameraLimitsAndSensibility = !0,
        this._isPointerDown = !1,
        this._lastInteractionTime = -1 / 0,
        this._animatables = new Array,
        this._betaIsAnimating = !1
    }
    return Object.defineProperty(i.prototype, "name", {
        get: function() {
            return "Framing"
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "mode", {
        get: function() {
            return this._mode
        },
        set: function(e) {
            this._mode = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "radiusScale", {
        get: function() {
            return this._radiusScale
        },
        set: function(e) {
            this._radiusScale = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "positionScale", {
        get: function() {
            return this._positionScale
        },
        set: function(e) {
            this._positionScale = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "defaultElevation", {
        get: function() {
            return this._defaultElevation
        },
        set: function(e) {
            this._defaultElevation = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "elevationReturnTime", {
        get: function() {
            return this._elevationReturnTime
        },
        set: function(e) {
            this._elevationReturnTime = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "elevationReturnWaitTime", {
        get: function() {
            return this._elevationReturnWaitTime
        },
        set: function(e) {
            this._elevationReturnWaitTime = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "zoomStopsAnimation", {
        get: function() {
            return this._zoomStopsAnimation
        },
        set: function(e) {
            this._zoomStopsAnimation = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "framingTime", {
        get: function() {
            return this._framingTime
        },
        set: function(e) {
            this._framingTime = e
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.init = function() {}
    ,
    i.prototype.attach = function(e) {
        var t = this;
        this._attachedCamera = e;
        var r = this._attachedCamera.getScene();
        i.EasingFunction.setEasingMode(i.EasingMode),
        this._onPrePointerObservableObserver = r.onPrePointerObservable.add(function(n) {
            if (n.type === PointerEventTypes.POINTERDOWN) {
                t._isPointerDown = !0;
                return
            }
            n.type === PointerEventTypes.POINTERUP && (t._isPointerDown = !1)
        }),
        this._onMeshTargetChangedObserver = e.onMeshTargetChangedObservable.add(function(n) {
            n && t.zoomOnMesh(n, void 0, function() {
                t.onTargetFramingAnimationEndObservable.notifyObservers()
            })
        }),
        this._onAfterCheckInputsObserver = e.onAfterCheckInputsObservable.add(function() {
            t._applyUserInteraction(),
            t._maintainCameraAboveGround()
        })
    }
    ,
    i.prototype.detach = function() {
        if (!!this._attachedCamera) {
            var e = this._attachedCamera.getScene();
            this._onPrePointerObservableObserver && e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),
            this._onAfterCheckInputsObserver && this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),
            this._onMeshTargetChangedObserver && this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),
            this._attachedCamera = null
        }
    }
    ,
    i.prototype.zoomOnMesh = function(e, t, r) {
        t === void 0 && (t = !1),
        r === void 0 && (r = null),
        e.computeWorldMatrix(!0);
        var n = e.getBoundingInfo().boundingBox;
        this.zoomOnBoundingInfo(n.minimumWorld, n.maximumWorld, t, r)
    }
    ,
    i.prototype.zoomOnMeshHierarchy = function(e, t, r) {
        t === void 0 && (t = !1),
        r === void 0 && (r = null),
        e.computeWorldMatrix(!0);
        var n = e.getHierarchyBoundingVectors(!0);
        this.zoomOnBoundingInfo(n.min, n.max, t, r)
    }
    ,
    i.prototype.zoomOnMeshesHierarchy = function(e, t, r) {
        t === void 0 && (t = !1),
        r === void 0 && (r = null);
        for (var n = new Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE), o = new Vector3(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE), a = 0; a < e.length; a++) {
            var s = e[a].getHierarchyBoundingVectors(!0);
            Vector3.CheckExtends(s.min, n, o),
            Vector3.CheckExtends(s.max, n, o)
        }
        this.zoomOnBoundingInfo(n, o, t, r)
    }
    ,
    i.prototype.zoomOnBoundingInfo = function(e, t, r, n) {
        var o = this;
        r === void 0 && (r = !1),
        n === void 0 && (n = null);
        var a;
        if (!!this._attachedCamera) {
            var s = e.y
              , l = t.y
              , u = s + (l - s) * this._positionScale
              , c = t.subtract(e).scale(.5);
            if (r)
                a = new Vector3(0,u,0);
            else {
                var h = e.add(c);
                a = new Vector3(h.x,u,h.z)
            }
            this._vectorTransition || (this._vectorTransition = Animation.CreateAnimation("target", Animation.ANIMATIONTYPE_VECTOR3, 60, i.EasingFunction)),
            this._betaIsAnimating = !0;
            var f = Animation.TransitionTo("target", a, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
            f && this._animatables.push(f);
            var d = 0;
            if (this._mode === i.FitFrustumSidesMode) {
                var _ = this._calculateLowerRadiusFromModelBoundingSphere(e, t);
                this.autoCorrectCameraLimitsAndSensibility && (this._attachedCamera.lowerRadiusLimit = c.length() + this._attachedCamera.minZ),
                d = _
            } else
                this._mode === i.IgnoreBoundsSizeMode && (d = this._calculateLowerRadiusFromModelBoundingSphere(e, t),
                this.autoCorrectCameraLimitsAndSensibility && this._attachedCamera.lowerRadiusLimit === null && (this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ));
            if (this.autoCorrectCameraLimitsAndSensibility) {
                var g = t.subtract(e).length();
                this._attachedCamera.panningSensibility = 5e3 / g,
                this._attachedCamera.wheelPrecision = 100 / d
            }
            this._radiusTransition || (this._radiusTransition = Animation.CreateAnimation("radius", Animation.ANIMATIONTYPE_FLOAT, 60, i.EasingFunction)),
            f = Animation.TransitionTo("radius", d, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function() {
                o.stopAllAnimations(),
                n && n(),
                o._attachedCamera && o._attachedCamera.useInputToRestoreState && o._attachedCamera.storeState()
            }),
            f && this._animatables.push(f)
        }
    }
    ,
    i.prototype._calculateLowerRadiusFromModelBoundingSphere = function(e, t) {
        var r = t.subtract(e)
          , n = r.length()
          , o = this._getFrustumSlope()
          , a = n * .5
          , s = a * this._radiusScale
          , l = s * Math.sqrt(1 + 1 / (o.x * o.x))
          , u = s * Math.sqrt(1 + 1 / (o.y * o.y))
          , c = Math.max(l, u)
          , h = this._attachedCamera;
        return h ? (h.lowerRadiusLimit && this._mode === i.IgnoreBoundsSizeMode && (c = c < h.lowerRadiusLimit ? h.lowerRadiusLimit : c),
        h.upperRadiusLimit && (c = c > h.upperRadiusLimit ? h.upperRadiusLimit : c),
        c) : 0
    }
    ,
    i.prototype._maintainCameraAboveGround = function() {
        var e = this;
        if (!(this._elevationReturnTime < 0)) {
            var t = PrecisionDate.Now - this._lastInteractionTime
              , r = Math.PI * .5 - this._defaultElevation
              , n = Math.PI * .5;
            if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > n && t >= this._elevationReturnWaitTime) {
                this._betaIsAnimating = !0,
                this.stopAllAnimations(),
                this._betaTransition || (this._betaTransition = Animation.CreateAnimation("beta", Animation.ANIMATIONTYPE_FLOAT, 60, i.EasingFunction));
                var o = Animation.TransitionTo("beta", r, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function() {
                    e._clearAnimationLocks(),
                    e.stopAllAnimations()
                });
                o && this._animatables.push(o)
            }
        }
    }
    ,
    i.prototype._getFrustumSlope = function() {
        var e = this._attachedCamera;
        if (!e)
            return Vector2.Zero();
        var t = e.getScene().getEngine()
          , r = t.getAspectRatio(e)
          , n = Math.tan(e.fov / 2)
          , o = n * r;
        return new Vector2(o,n)
    }
    ,
    i.prototype._clearAnimationLocks = function() {
        this._betaIsAnimating = !1
    }
    ,
    i.prototype._applyUserInteraction = function() {
        this.isUserIsMoving && (this._lastInteractionTime = PrecisionDate.Now,
        this.stopAllAnimations(),
        this._clearAnimationLocks())
    }
    ,
    i.prototype.stopAllAnimations = function() {
        for (this._attachedCamera && (this._attachedCamera.animations = []); this._animatables.length; )
            this._animatables[0] && (this._animatables[0].onAnimationEnd = null,
            this._animatables[0].stop()),
            this._animatables.shift()
    }
    ,
    Object.defineProperty(i.prototype, "isUserIsMoving", {
        get: function() {
            return this._attachedCamera ? this._attachedCamera.inertialAlphaOffset !== 0 || this._attachedCamera.inertialBetaOffset !== 0 || this._attachedCamera.inertialRadiusOffset !== 0 || this._attachedCamera.inertialPanningX !== 0 || this._attachedCamera.inertialPanningY !== 0 || this._isPointerDown : !1
        },
        enumerable: !1,
        configurable: !0
    }),
    i.EasingFunction = new ExponentialEase,
    i.EasingMode = EasingFunction.EASINGMODE_EASEINOUT,
    i.IgnoreBoundsSizeMode = 0,
    i.FitFrustumSidesMode = 1,
    i
}()
  , TargetCamera = function(i) {
    __extends(e, i);
    function e(t, r, n, o) {
        o === void 0 && (o = !0);
        var a = i.call(this, t, r, n, o) || this;
        return a._tmpUpVector = Vector3.Zero(),
        a._tmpTargetVector = Vector3.Zero(),
        a.cameraDirection = new Vector3(0,0,0),
        a.cameraRotation = new Vector2(0,0),
        a.ignoreParentScaling = !1,
        a.updateUpVectorFromRotation = !1,
        a._tmpQuaternion = new Quaternion,
        a.rotation = new Vector3(0,0,0),
        a.speed = 2,
        a.noRotationConstraint = !1,
        a.invertRotation = !1,
        a.inverseRotationSpeed = .2,
        a.lockedTarget = null,
        a._currentTarget = Vector3.Zero(),
        a._initialFocalDistance = 1,
        a._viewMatrix = Matrix.Zero(),
        a._camMatrix = Matrix.Zero(),
        a._cameraTransformMatrix = Matrix.Zero(),
        a._cameraRotationMatrix = Matrix.Zero(),
        a._referencePoint = new Vector3(0,0,1),
        a._transformedReferencePoint = Vector3.Zero(),
        a._defaultUp = Vector3.Up(),
        a._cachedRotationZ = 0,
        a._cachedQuaternionRotationZ = 0,
        a
    }
    return e.prototype.getFrontPosition = function(t) {
        this.getWorldMatrix();
        var r = this.getTarget().subtract(this.position);
        return r.normalize(),
        r.scaleInPlace(t),
        this.globalPosition.add(r)
    }
    ,
    e.prototype._getLockedTargetPosition = function() {
        return this.lockedTarget ? (this.lockedTarget.absolutePosition && this.lockedTarget.computeWorldMatrix(),
        this.lockedTarget.absolutePosition || this.lockedTarget) : null
    }
    ,
    e.prototype.storeState = function() {
        return this._storedPosition = this.position.clone(),
        this._storedRotation = this.rotation.clone(),
        this.rotationQuaternion && (this._storedRotationQuaternion = this.rotationQuaternion.clone()),
        i.prototype.storeState.call(this)
    }
    ,
    e.prototype._restoreStateValues = function() {
        return i.prototype._restoreStateValues.call(this) ? (this.position = this._storedPosition.clone(),
        this.rotation = this._storedRotation.clone(),
        this.rotationQuaternion && (this.rotationQuaternion = this._storedRotationQuaternion.clone()),
        this.cameraDirection.copyFromFloats(0, 0, 0),
        this.cameraRotation.copyFromFloats(0, 0),
        !0) : !1
    }
    ,
    e.prototype._initCache = function() {
        i.prototype._initCache.call(this),
        this._cache.lockedTarget = new Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),
        this._cache.rotation = new Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),
        this._cache.rotationQuaternion = new Quaternion(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)
    }
    ,
    e.prototype._updateCache = function(t) {
        t || i.prototype._updateCache.call(this);
        var r = this._getLockedTargetPosition();
        r ? this._cache.lockedTarget ? this._cache.lockedTarget.copyFrom(r) : this._cache.lockedTarget = r.clone() : this._cache.lockedTarget = null,
        this._cache.rotation.copyFrom(this.rotation),
        this.rotationQuaternion && this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion)
    }
    ,
    e.prototype._isSynchronizedViewMatrix = function() {
        if (!i.prototype._isSynchronizedViewMatrix.call(this))
            return !1;
        var t = this._getLockedTargetPosition();
        return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(t) : !t) && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation))
    }
    ,
    e.prototype._computeLocalCameraSpeed = function() {
        var t = this.getEngine();
        return this.speed * Math.sqrt(t.getDeltaTime() / (t.getFps() * 100))
    }
    ,
    e.prototype.setTarget = function(t) {
        this.upVector.normalize(),
        this._initialFocalDistance = t.subtract(this.position).length(),
        this.position.z === t.z && (this.position.z += Epsilon),
        this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance),
        Matrix.LookAtLHToRef(this.position, t, this._defaultUp, this._camMatrix),
        this._camMatrix.invert(),
        this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
        var r = t.subtract(this.position);
        r.x >= 0 ? this.rotation.y = -Math.atan(r.z / r.x) + Math.PI / 2 : this.rotation.y = -Math.atan(r.z / r.x) - Math.PI / 2,
        this.rotation.z = 0,
        isNaN(this.rotation.x) && (this.rotation.x = 0),
        isNaN(this.rotation.y) && (this.rotation.y = 0),
        isNaN(this.rotation.z) && (this.rotation.z = 0),
        this.rotationQuaternion && Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion)
    }
    ,
    Object.defineProperty(e.prototype, "target", {
        get: function() {
            return this.getTarget()
        },
        set: function(t) {
            this.setTarget(t)
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getTarget = function() {
        return this._currentTarget
    }
    ,
    e.prototype._decideIfNeedsToMove = function() {
        return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0
    }
    ,
    e.prototype._updatePosition = function() {
        if (this.parent) {
            this.parent.getWorldMatrix().invertToRef(TmpVectors.Matrix[0]),
            Vector3.TransformNormalToRef(this.cameraDirection, TmpVectors.Matrix[0], TmpVectors.Vector3[0]),
            this.position.addInPlace(TmpVectors.Vector3[0]);
            return
        }
        this.position.addInPlace(this.cameraDirection)
    }
    ,
    e.prototype._checkInputs = function() {
        var t = this.invertRotation ? -this.inverseRotationSpeed : 1
          , r = this._decideIfNeedsToMove()
          , n = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
        if (r && this._updatePosition(),
        n) {
            if (this.rotationQuaternion && this.rotationQuaternion.toEulerAnglesToRef(this.rotation),
            this.rotation.x += this.cameraRotation.x * t,
            this.rotation.y += this.cameraRotation.y * t,
            !this.noRotationConstraint) {
                var o = 1.570796;
                this.rotation.x > o && (this.rotation.x = o),
                this.rotation.x < -o && (this.rotation.x = -o)
            }
            if (this.rotationQuaternion) {
                var a = this.rotation.lengthSquared();
                a && Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion)
            }
        }
        r && (Math.abs(this.cameraDirection.x) < this.speed * Epsilon && (this.cameraDirection.x = 0),
        Math.abs(this.cameraDirection.y) < this.speed * Epsilon && (this.cameraDirection.y = 0),
        Math.abs(this.cameraDirection.z) < this.speed * Epsilon && (this.cameraDirection.z = 0),
        this.cameraDirection.scaleInPlace(this.inertia)),
        n && (Math.abs(this.cameraRotation.x) < this.speed * Epsilon && (this.cameraRotation.x = 0),
        Math.abs(this.cameraRotation.y) < this.speed * Epsilon && (this.cameraRotation.y = 0),
        this.cameraRotation.scaleInPlace(this.inertia)),
        i.prototype._checkInputs.call(this)
    }
    ,
    e.prototype._updateCameraRotationMatrix = function() {
        this.rotationQuaternion ? this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix) : Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix)
    }
    ,
    e.prototype._rotateUpVectorWithCameraRotationMatrix = function() {
        return Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector),
        this
    }
    ,
    e.prototype._getViewMatrix = function() {
        return this.lockedTarget && this.setTarget(this._getLockedTargetPosition()),
        this._updateCameraRotationMatrix(),
        this.rotationQuaternion && this._cachedQuaternionRotationZ != this.rotationQuaternion.z ? (this._rotateUpVectorWithCameraRotationMatrix(),
        this._cachedQuaternionRotationZ = this.rotationQuaternion.z) : this._cachedRotationZ !== this.rotation.z && (this._rotateUpVectorWithCameraRotationMatrix(),
        this._cachedRotationZ = this.rotation.z),
        Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint),
        this.position.addToRef(this._transformedReferencePoint, this._currentTarget),
        this.updateUpVectorFromRotation && (this.rotationQuaternion ? Axis.Y.rotateByQuaternionToRef(this.rotationQuaternion, this.upVector) : (Quaternion.FromEulerVectorToRef(this.rotation, this._tmpQuaternion),
        Axis.Y.rotateByQuaternionToRef(this._tmpQuaternion, this.upVector))),
        this._computeViewMatrix(this.position, this._currentTarget, this.upVector),
        this._viewMatrix
    }
    ,
    e.prototype._computeViewMatrix = function(t, r, n) {
        if (this.ignoreParentScaling) {
            if (this.parent) {
                var o = this.parent.getWorldMatrix();
                Vector3.TransformCoordinatesToRef(t, o, this._globalPosition),
                Vector3.TransformCoordinatesToRef(r, o, this._tmpTargetVector),
                Vector3.TransformNormalToRef(n, o, this._tmpUpVector),
                this._markSyncedWithParent()
            } else
                this._globalPosition.copyFrom(t),
                this._tmpTargetVector.copyFrom(r),
                this._tmpUpVector.copyFrom(n);
            this.getScene().useRightHandedSystem ? Matrix.LookAtRHToRef(this._globalPosition, this._tmpTargetVector, this._tmpUpVector, this._viewMatrix) : Matrix.LookAtLHToRef(this._globalPosition, this._tmpTargetVector, this._tmpUpVector, this._viewMatrix);
            return
        }
        if (this.getScene().useRightHandedSystem ? Matrix.LookAtRHToRef(t, r, n, this._viewMatrix) : Matrix.LookAtLHToRef(t, r, n, this._viewMatrix),
        this.parent) {
            var o = this.parent.getWorldMatrix();
            this._viewMatrix.invert(),
            this._viewMatrix.multiplyToRef(o, this._viewMatrix),
            this._viewMatrix.getTranslationToRef(this._globalPosition),
            this._viewMatrix.invert(),
            this._markSyncedWithParent()
        } else
            this._globalPosition.copyFrom(t)
    }
    ,
    e.prototype.createRigCamera = function(t, r) {
        if (this.cameraRigMode !== Camera$1.RIG_MODE_NONE) {
            var n = new e(t,this.position.clone(),this.getScene());
            return n.isRigCamera = !0,
            n.rigParent = this,
            (this.cameraRigMode === Camera$1.RIG_MODE_VR || this.cameraRigMode === Camera$1.RIG_MODE_WEBVR) && (this.rotationQuaternion || (this.rotationQuaternion = new Quaternion),
            n._cameraRigParams = {},
            n.rotationQuaternion = new Quaternion),
            n
        }
        return null
    }
    ,
    e.prototype._updateRigCameras = function() {
        var t = this._rigCameras[0]
          , r = this._rigCameras[1];
        switch (this.computeWorldMatrix(),
        this.cameraRigMode) {
        case Camera$1.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
        case Camera$1.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
        case Camera$1.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
        case Camera$1.RIG_MODE_STEREOSCOPIC_OVERUNDER:
        case Camera$1.RIG_MODE_STEREOSCOPIC_INTERLACED:
            var n = this.cameraRigMode === Camera$1.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED ? 1 : -1
              , o = this.cameraRigMode === Camera$1.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED ? -1 : 1;
            this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle * n, t),
            this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle * o, r);
            break;
        case Camera$1.RIG_MODE_VR:
            t.rotationQuaternion ? (t.rotationQuaternion.copyFrom(this.rotationQuaternion),
            r.rotationQuaternion.copyFrom(this.rotationQuaternion)) : (t.rotation.copyFrom(this.rotation),
            r.rotation.copyFrom(this.rotation)),
            t.position.copyFrom(this.position),
            r.position.copyFrom(this.position);
            break
        }
        i.prototype._updateRigCameras.call(this)
    }
    ,
    e.prototype._getRigCamPositionAndTarget = function(t, r) {
        var n = this.getTarget();
        n.subtractToRef(this.position, e._TargetFocalPoint),
        e._TargetFocalPoint.normalize().scaleInPlace(this._initialFocalDistance);
        var o = e._TargetFocalPoint.addInPlace(this.position);
        Matrix.TranslationToRef(-o.x, -o.y, -o.z, e._TargetTransformMatrix),
        e._TargetTransformMatrix.multiplyToRef(Matrix.RotationAxis(r.upVector, t), e._RigCamTransformMatrix),
        Matrix.TranslationToRef(o.x, o.y, o.z, e._TargetTransformMatrix),
        e._RigCamTransformMatrix.multiplyToRef(e._TargetTransformMatrix, e._RigCamTransformMatrix),
        Vector3.TransformCoordinatesToRef(this.position, e._RigCamTransformMatrix, r.position),
        r.setTarget(o)
    }
    ,
    e.prototype.getClassName = function() {
        return "TargetCamera"
    }
    ,
    e._RigCamTransformMatrix = new Matrix,
    e._TargetTransformMatrix = new Matrix,
    e._TargetFocalPoint = new Vector3,
    __decorate([serializeAsVector3()], e.prototype, "rotation", void 0),
    __decorate([serialize()], e.prototype, "speed", void 0),
    __decorate([serializeAsMeshReference("lockedTargetId")], e.prototype, "lockedTarget", void 0),
    e
}(Camera$1)
  , CameraInputTypes = {}
  , CameraInputsManager = function() {
    function i(e) {
        this.attachedToElement = !1,
        this.attached = {},
        this.camera = e,
        this.checkInputs = function() {}
    }
    return i.prototype.add = function(e) {
        var t = e.getSimpleName();
        if (this.attached[t]) {
            Logger$2.Warn("camera input of type " + t + " already exists on camera");
            return
        }
        this.attached[t] = e,
        e.camera = this.camera,
        e.checkInputs && (this.checkInputs = this._addCheckInputs(e.checkInputs.bind(e))),
        this.attachedToElement && e.attachControl()
    }
    ,
    i.prototype.remove = function(e) {
        for (var t in this.attached) {
            var r = this.attached[t];
            r === e && (r.detachControl(),
            r.camera = null,
            delete this.attached[t],
            this.rebuildInputCheck())
        }
    }
    ,
    i.prototype.removeByType = function(e) {
        for (var t in this.attached) {
            var r = this.attached[t];
            r.getClassName() === e && (r.detachControl(),
            r.camera = null,
            delete this.attached[t],
            this.rebuildInputCheck())
        }
    }
    ,
    i.prototype._addCheckInputs = function(e) {
        var t = this.checkInputs;
        return function() {
            t(),
            e()
        }
    }
    ,
    i.prototype.attachInput = function(e) {
        this.attachedToElement && e.attachControl(this.noPreventDefault)
    }
    ,
    i.prototype.attachElement = function(e) {
        if (e === void 0 && (e = !1),
        !this.attachedToElement) {
            e = Camera$1.ForceAttachControlToAlwaysPreventDefault ? !1 : e,
            this.attachedToElement = !0,
            this.noPreventDefault = e;
            for (var t in this.attached)
                this.attached[t].attachControl(e)
        }
    }
    ,
    i.prototype.detachElement = function(e) {
        e === void 0 && (e = !1);
        for (var t in this.attached)
            this.attached[t].detachControl(),
            e && (this.attached[t].camera = null);
        this.attachedToElement = !1
    }
    ,
    i.prototype.rebuildInputCheck = function() {
        this.checkInputs = function() {}
        ;
        for (var e in this.attached) {
            var t = this.attached[e];
            t.checkInputs && (this.checkInputs = this._addCheckInputs(t.checkInputs.bind(t)))
        }
    }
    ,
    i.prototype.clear = function() {
        this.attachedToElement && this.detachElement(!0),
        this.attached = {},
        this.attachedToElement = !1,
        this.checkInputs = function() {}
    }
    ,
    i.prototype.serialize = function(e) {
        var t = {};
        for (var r in this.attached) {
            var n = this.attached[r]
              , o = SerializationHelper.Serialize(n);
            t[n.getClassName()] = o
        }
        e.inputsmgr = t
    }
    ,
    i.prototype.parse = function(e) {
        var t = e.inputsmgr;
        if (t) {
            this.clear();
            for (var r in t) {
                var n = CameraInputTypes[r];
                if (n) {
                    var o = t[r]
                      , a = SerializationHelper.Parse(function() {
                        return new n
                    }, o, null);
                    this.add(a)
                }
            }
        } else
            for (var r in this.attached) {
                var n = CameraInputTypes[this.attached[r].getClassName()];
                if (n) {
                    var a = SerializationHelper.Parse(function() {
                        return new n
                    }, e, null);
                    this.remove(this.attached[r]),
                    this.add(a)
                }
            }
    }
    ,
    i
}()
  , BaseCameraPointersInput = function() {
    function i() {
        this._currentActiveButton = -1,
        this.buttons = [0, 1, 2]
    }
    return i.prototype.attachControl = function(e) {
        var t = this;
        e = Tools.BackCompatCameraNoPreventDefault(arguments);
        var r = this.camera.getEngine()
          , n = r.getInputElement()
          , o = 0
          , a = null;
        this.pointA = null,
        this.pointB = null,
        this._altKey = !1,
        this._ctrlKey = !1,
        this._metaKey = !1,
        this._shiftKey = !1,
        this._buttonsPressed = 0,
        this._pointerInput = function(l, u) {
            var c = l.event
              , h = c.pointerType === "touch";
            if (!r.isInVRExclusivePointerMode && !(l.type !== PointerEventTypes.POINTERMOVE && t.buttons.indexOf(c.button) === -1)) {
                var f = c.srcElement || c.target;
                if (t._altKey = c.altKey,
                t._ctrlKey = c.ctrlKey,
                t._metaKey = c.metaKey,
                t._shiftKey = c.shiftKey,
                t._buttonsPressed = c.buttons,
                r.isPointerLock) {
                    var d = c.movementX || c.mozMovementX || c.webkitMovementX || c.msMovementX || 0
                      , _ = c.movementY || c.mozMovementY || c.webkitMovementY || c.msMovementY || 0;
                    t.onTouch(null, d, _),
                    t.pointA = null,
                    t.pointB = null
                } else if (l.type === PointerEventTypes.POINTERDOWN && (t._currentActiveButton === -1 || h)) {
                    try {
                        f == null || f.setPointerCapture(c.pointerId)
                    } catch {}
                    t.pointA === null ? t.pointA = {
                        x: c.clientX,
                        y: c.clientY,
                        pointerId: c.pointerId,
                        type: c.pointerType
                    } : t.pointB === null && (t.pointB = {
                        x: c.clientX,
                        y: c.clientY,
                        pointerId: c.pointerId,
                        type: c.pointerType
                    }),
                    t._currentActiveButton === -1 && !h && (t._currentActiveButton = c.button),
                    t.onButtonDown(c),
                    e || (c.preventDefault(),
                    n && n.focus())
                } else if (l.type === PointerEventTypes.POINTERDOUBLETAP)
                    t.onDoubleTap(c.pointerType);
                else if (l.type === PointerEventTypes.POINTERUP && (t._currentActiveButton === c.button || h)) {
                    try {
                        f == null || f.releasePointerCapture(c.pointerId)
                    } catch {}
                    h || (t.pointB = null),
                    r._badOS ? t.pointA = t.pointB = null : t.pointB && t.pointA && t.pointA.pointerId == c.pointerId ? (t.pointA = t.pointB,
                    t.pointB = null) : t.pointA && t.pointB && t.pointB.pointerId == c.pointerId ? t.pointB = null : t.pointA = t.pointB = null,
                    (o !== 0 || a) && (t.onMultiTouch(t.pointA, t.pointB, o, 0, a, null),
                    o = 0,
                    a = null),
                    t._currentActiveButton = -1,
                    t.onButtonUp(c),
                    e || c.preventDefault()
                } else if (l.type === PointerEventTypes.POINTERMOVE) {
                    if (e || c.preventDefault(),
                    t.pointA && t.pointB === null) {
                        var d = c.clientX - t.pointA.x
                          , _ = c.clientY - t.pointA.y;
                        t.onTouch(t.pointA, d, _),
                        t.pointA.x = c.clientX,
                        t.pointA.y = c.clientY
                    } else if (t.pointA && t.pointB) {
                        var g = t.pointA.pointerId === c.pointerId ? t.pointA : t.pointB;
                        g.x = c.clientX,
                        g.y = c.clientY;
                        var m = t.pointA.x - t.pointB.x
                          , v = t.pointA.y - t.pointB.y
                          , y = m * m + v * v
                          , b = {
                            x: (t.pointA.x + t.pointB.x) / 2,
                            y: (t.pointA.y + t.pointB.y) / 2,
                            pointerId: c.pointerId,
                            type: l.type
                        };
                        t.onMultiTouch(t.pointA, t.pointB, o, y, a, b),
                        a = b,
                        o = y
                    }
                }
            }
        }
        ,
        this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, PointerEventTypes.POINTERDOWN | PointerEventTypes.POINTERUP | PointerEventTypes.POINTERMOVE | PointerEventTypes.POINTERDOUBLETAP),
        this._onLostFocus = function() {
            t.pointA = t.pointB = null,
            o = 0,
            a = null,
            t.onLostFocus()
        }
        ,
        n && n.addEventListener("contextmenu", this.onContextMenu.bind(this), !1);
        var s = this.camera.getScene().getEngine().getHostWindow();
        s && Tools.RegisterTopRootEvents(s, [{
            name: "blur",
            handler: this._onLostFocus
        }])
    }
    ,
    i.prototype.detachControl = function(e) {
        if (this._onLostFocus) {
            var t = this.camera.getScene().getEngine().getHostWindow();
            t && Tools.UnregisterTopRootEvents(t, [{
                name: "blur",
                handler: this._onLostFocus
            }])
        }
        if (this._observer) {
            if (this.camera.getScene().onPointerObservable.remove(this._observer),
            this._observer = null,
            this.onContextMenu) {
                var r = this.camera.getScene().getEngine().getInputElement();
                r && r.removeEventListener("contextmenu", this.onContextMenu)
            }
            this._onLostFocus = null
        }
        this._altKey = !1,
        this._ctrlKey = !1,
        this._metaKey = !1,
        this._shiftKey = !1,
        this._buttonsPressed = 0
    }
    ,
    i.prototype.getClassName = function() {
        return "BaseCameraPointersInput"
    }
    ,
    i.prototype.getSimpleName = function() {
        return "pointers"
    }
    ,
    i.prototype.onDoubleTap = function(e) {}
    ,
    i.prototype.onTouch = function(e, t, r) {}
    ,
    i.prototype.onMultiTouch = function(e, t, r, n, o, a) {}
    ,
    i.prototype.onContextMenu = function(e) {
        e.preventDefault()
    }
    ,
    i.prototype.onButtonDown = function(e) {}
    ,
    i.prototype.onButtonUp = function(e) {}
    ,
    i.prototype.onLostFocus = function() {}
    ,
    __decorate([serialize()], i.prototype, "buttons", void 0),
    i
}()
  , ArcRotateCameraPointersInput = function(i) {
    __extends(e, i);
    function e() {
        var t = i !== null && i.apply(this, arguments) || this;
        return t.buttons = [0, 1, 2],
        t.angularSensibilityX = 1e3,
        t.angularSensibilityY = 1e3,
        t.pinchPrecision = 12,
        t.pinchDeltaPercentage = 0,
        t.useNaturalPinchZoom = !1,
        t.pinchZoom = !0,
        t.panningSensibility = 1e3,
        t.multiTouchPanning = !0,
        t.multiTouchPanAndZoom = !0,
        t.pinchInwards = !0,
        t._isPanClick = !1,
        t._twoFingerActivityCount = 0,
        t._isPinching = !1,
        t
    }
    return e.prototype.getClassName = function() {
        return "ArcRotateCameraPointersInput"
    }
    ,
    e.prototype._computeMultiTouchPanning = function(t, r) {
        if (this.panningSensibility !== 0 && t && r) {
            var n = r.x - t.x
              , o = r.y - t.y;
            this.camera.inertialPanningX += -n / this.panningSensibility,
            this.camera.inertialPanningY += o / this.panningSensibility
        }
    }
    ,
    e.prototype._computePinchZoom = function(t, r) {
        var n = this.camera.radius || e.MinimumRadiusForPinch;
        this.useNaturalPinchZoom ? this.camera.radius = n * Math.sqrt(t) / Math.sqrt(r) : this.pinchDeltaPercentage ? this.camera.inertialRadiusOffset += (r - t) * .001 * n * this.pinchDeltaPercentage : this.camera.inertialRadiusOffset += (r - t) / (this.pinchPrecision * (this.pinchInwards ? 1 : -1) * (this.angularSensibilityX + this.angularSensibilityY) / 2)
    }
    ,
    e.prototype.onTouch = function(t, r, n) {
        this.panningSensibility !== 0 && (this._ctrlKey && this.camera._useCtrlForPanning || this._isPanClick) ? (this.camera.inertialPanningX += -r / this.panningSensibility,
        this.camera.inertialPanningY += n / this.panningSensibility) : (this.camera.inertialAlphaOffset -= r / this.angularSensibilityX,
        this.camera.inertialBetaOffset -= n / this.angularSensibilityY)
    }
    ,
    e.prototype.onDoubleTap = function(t) {
        this.camera.useInputToRestoreState && this.camera.restoreState()
    }
    ,
    e.prototype.onMultiTouch = function(t, r, n, o, a, s) {
        n === 0 && a === null || o === 0 && s === null || (this.multiTouchPanAndZoom ? (this._computePinchZoom(n, o),
        this._computeMultiTouchPanning(a, s)) : this.multiTouchPanning && this.pinchZoom ? (this._twoFingerActivityCount++,
        this._isPinching || this._twoFingerActivityCount < 20 && Math.abs(Math.sqrt(o) - Math.sqrt(n)) > this.camera.pinchToPanMaxDistance ? (this._computePinchZoom(n, o),
        this._isPinching = !0) : this._computeMultiTouchPanning(a, s)) : this.multiTouchPanning ? this._computeMultiTouchPanning(a, s) : this.pinchZoom && this._computePinchZoom(n, o))
    }
    ,
    e.prototype.onButtonDown = function(t) {
        this._isPanClick = t.button === this.camera._panningMouseButton
    }
    ,
    e.prototype.onButtonUp = function(t) {
        this._twoFingerActivityCount = 0,
        this._isPinching = !1
    }
    ,
    e.prototype.onLostFocus = function() {
        this._isPanClick = !1,
        this._twoFingerActivityCount = 0,
        this._isPinching = !1
    }
    ,
    e.MinimumRadiusForPinch = .001,
    __decorate([serialize()], e.prototype, "buttons", void 0),
    __decorate([serialize()], e.prototype, "angularSensibilityX", void 0),
    __decorate([serialize()], e.prototype, "angularSensibilityY", void 0),
    __decorate([serialize()], e.prototype, "pinchPrecision", void 0),
    __decorate([serialize()], e.prototype, "pinchDeltaPercentage", void 0),
    __decorate([serialize()], e.prototype, "useNaturalPinchZoom", void 0),
    __decorate([serialize()], e.prototype, "pinchZoom", void 0),
    __decorate([serialize()], e.prototype, "panningSensibility", void 0),
    __decorate([serialize()], e.prototype, "multiTouchPanning", void 0),
    __decorate([serialize()], e.prototype, "multiTouchPanAndZoom", void 0),
    e
}(BaseCameraPointersInput);
CameraInputTypes.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
var ArcRotateCameraKeyboardMoveInput = function() {
    function i() {
        this.keysUp = [38],
        this.keysDown = [40],
        this.keysLeft = [37],
        this.keysRight = [39],
        this.keysReset = [220],
        this.panningSensibility = 50,
        this.zoomingSensibility = 25,
        this.useAltToZoom = !0,
        this.angularSpeed = .01,
        this._keys = new Array
    }
    return i.prototype.attachControl = function(e) {
        var t = this;
        e = Tools.BackCompatCameraNoPreventDefault(arguments),
        !this._onCanvasBlurObserver && (this._scene = this.camera.getScene(),
        this._engine = this._scene.getEngine(),
        this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function() {
            t._keys = []
        }),
        this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function(r) {
            var n = r.event;
            if (!n.metaKey) {
                if (r.type === KeyboardEventTypes.KEYDOWN) {
                    if (t._ctrlPressed = n.ctrlKey,
                    t._altPressed = n.altKey,
                    t.keysUp.indexOf(n.keyCode) !== -1 || t.keysDown.indexOf(n.keyCode) !== -1 || t.keysLeft.indexOf(n.keyCode) !== -1 || t.keysRight.indexOf(n.keyCode) !== -1 || t.keysReset.indexOf(n.keyCode) !== -1) {
                        var o = t._keys.indexOf(n.keyCode);
                        o === -1 && t._keys.push(n.keyCode),
                        n.preventDefault && (e || n.preventDefault())
                    }
                } else if (t.keysUp.indexOf(n.keyCode) !== -1 || t.keysDown.indexOf(n.keyCode) !== -1 || t.keysLeft.indexOf(n.keyCode) !== -1 || t.keysRight.indexOf(n.keyCode) !== -1 || t.keysReset.indexOf(n.keyCode) !== -1) {
                    var o = t._keys.indexOf(n.keyCode);
                    o >= 0 && t._keys.splice(o, 1),
                    n.preventDefault && (e || n.preventDefault())
                }
            }
        }))
    }
    ,
    i.prototype.detachControl = function(e) {
        this._scene && (this._onKeyboardObserver && this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),
        this._onCanvasBlurObserver && this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),
        this._onKeyboardObserver = null,
        this._onCanvasBlurObserver = null),
        this._keys = []
    }
    ,
    i.prototype.checkInputs = function() {
        if (this._onKeyboardObserver)
            for (var e = this.camera, t = 0; t < this._keys.length; t++) {
                var r = this._keys[t];
                this.keysLeft.indexOf(r) !== -1 ? this._ctrlPressed && this.camera._useCtrlForPanning ? e.inertialPanningX -= 1 / this.panningSensibility : e.inertialAlphaOffset -= this.angularSpeed : this.keysUp.indexOf(r) !== -1 ? this._ctrlPressed && this.camera._useCtrlForPanning ? e.inertialPanningY += 1 / this.panningSensibility : this._altPressed && this.useAltToZoom ? e.inertialRadiusOffset += 1 / this.zoomingSensibility : e.inertialBetaOffset -= this.angularSpeed : this.keysRight.indexOf(r) !== -1 ? this._ctrlPressed && this.camera._useCtrlForPanning ? e.inertialPanningX += 1 / this.panningSensibility : e.inertialAlphaOffset += this.angularSpeed : this.keysDown.indexOf(r) !== -1 ? this._ctrlPressed && this.camera._useCtrlForPanning ? e.inertialPanningY -= 1 / this.panningSensibility : this._altPressed && this.useAltToZoom ? e.inertialRadiusOffset -= 1 / this.zoomingSensibility : e.inertialBetaOffset += this.angularSpeed : this.keysReset.indexOf(r) !== -1 && e.useInputToRestoreState && e.restoreState()
            }
    }
    ,
    i.prototype.getClassName = function() {
        return "ArcRotateCameraKeyboardMoveInput"
    }
    ,
    i.prototype.getSimpleName = function() {
        return "keyboard"
    }
    ,
    __decorate([serialize()], i.prototype, "keysUp", void 0),
    __decorate([serialize()], i.prototype, "keysDown", void 0),
    __decorate([serialize()], i.prototype, "keysLeft", void 0),
    __decorate([serialize()], i.prototype, "keysRight", void 0),
    __decorate([serialize()], i.prototype, "keysReset", void 0),
    __decorate([serialize()], i.prototype, "panningSensibility", void 0),
    __decorate([serialize()], i.prototype, "zoomingSensibility", void 0),
    __decorate([serialize()], i.prototype, "useAltToZoom", void 0),
    __decorate([serialize()], i.prototype, "angularSpeed", void 0),
    i
}();
CameraInputTypes.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
var ffMultiplier = 40
  , ArcRotateCameraMouseWheelInput = function() {
    function i() {
        this.wheelPrecision = 3,
        this.zoomToMouseLocation = !1,
        this.wheelDeltaPercentage = 0,
        this.customComputeDeltaFromMouseWheel = null,
        this._inertialPanning = Vector3.Zero()
    }
    return i.prototype.computeDeltaFromMouseWheelLegacyEvent = function(e, t) {
        var r = 0
          , n = e * .01 * this.wheelDeltaPercentage * t;
        return e > 0 ? r = n / (1 + this.wheelDeltaPercentage) : r = n * (1 + this.wheelDeltaPercentage),
        r
    }
    ,
    i.prototype.attachControl = function(e) {
        var t = this;
        e = Tools.BackCompatCameraNoPreventDefault(arguments),
        this._wheel = function(r, n) {
            if (r.type === PointerEventTypes.POINTERWHEEL) {
                var o = r.event
                  , a = 0
                  , s = o
                  , l = 0
                  , u = o.deltaMode === EventConstants.DOM_DELTA_LINE ? ffMultiplier : 1;
                if (o.deltaY !== void 0 ? l = -(o.deltaY * u) : o.wheelDeltaY !== void 0 ? l = -(o.wheelDeltaY * u) : l = s.wheelDelta,
                t.customComputeDeltaFromMouseWheel)
                    a = t.customComputeDeltaFromMouseWheel(l, t, o);
                else if (t.wheelDeltaPercentage) {
                    if (a = t.computeDeltaFromMouseWheelLegacyEvent(l, t.camera.radius),
                    a > 0) {
                        for (var c = t.camera.radius, h = t.camera.inertialRadiusOffset + a, f = 0; f < 20 && Math.abs(h) > .001; f++)
                            c -= h,
                            h *= t.camera.inertia;
                        c = Scalar.Clamp(c, 0, Number.MAX_VALUE),
                        a = t.computeDeltaFromMouseWheelLegacyEvent(l, c)
                    }
                } else
                    a = l / (t.wheelPrecision * 40);
                a && (t.zoomToMouseLocation && t._hitPlane ? t._zoomToMouse(a) : t.camera.inertialRadiusOffset += a),
                o.preventDefault && (e || o.preventDefault())
            }
        }
        ,
        this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, PointerEventTypes.POINTERWHEEL),
        this.zoomToMouseLocation && this._inertialPanning.setAll(0)
    }
    ,
    i.prototype.detachControl = function(e) {
        this._observer && (this.camera.getScene().onPointerObservable.remove(this._observer),
        this._observer = null,
        this._wheel = null)
    }
    ,
    i.prototype.checkInputs = function() {
        if (!!this.zoomToMouseLocation) {
            var e = this.camera
              , t = 0 + e.inertialAlphaOffset + e.inertialBetaOffset + e.inertialRadiusOffset;
            t && (this._updateHitPlane(),
            e.target.addInPlace(this._inertialPanning),
            this._inertialPanning.scaleInPlace(e.inertia),
            this._zeroIfClose(this._inertialPanning))
        }
    }
    ,
    i.prototype.getClassName = function() {
        return "ArcRotateCameraMouseWheelInput"
    }
    ,
    i.prototype.getSimpleName = function() {
        return "mousewheel"
    }
    ,
    i.prototype._updateHitPlane = function() {
        var e = this.camera
          , t = e.target.subtract(e.position);
        this._hitPlane = Plane.FromPositionAndNormal(Vector3.Zero(), t)
    }
    ,
    i.prototype._getPosition = function() {
        var e, t = this.camera, r = t.getScene(), n = r.createPickingRay(r.pointerX, r.pointerY, Matrix.Identity(), t, !1), o = 0;
        return this._hitPlane && (o = (e = n.intersectsPlane(this._hitPlane)) !== null && e !== void 0 ? e : 0),
        n.origin.addInPlace(n.direction.scaleInPlace(o))
    }
    ,
    i.prototype._zoomToMouse = function(e) {
        var t, r, n = this.camera, o = 1 - n.inertia;
        if (n.lowerRadiusLimit) {
            var a = (t = n.lowerRadiusLimit) !== null && t !== void 0 ? t : 0;
            n.radius - (n.inertialRadiusOffset + e) / o < a && (e = (n.radius - a) * o - n.inertialRadiusOffset)
        }
        if (n.upperRadiusLimit) {
            var s = (r = n.upperRadiusLimit) !== null && r !== void 0 ? r : 0;
            n.radius - (n.inertialRadiusOffset + e) / o > s && (e = (n.radius - s) * o - n.inertialRadiusOffset)
        }
        var l = e / o
          , u = l / n.radius
          , c = this._getPosition()
          , h = c.subtract(n.target)
          , f = h.scale(u);
        f.scaleInPlace(o),
        this._inertialPanning.addInPlace(f),
        n.inertialRadiusOffset += e
    }
    ,
    i.prototype._zeroIfClose = function(e) {
        Math.abs(e.x) < Epsilon && (e.x = 0),
        Math.abs(e.y) < Epsilon && (e.y = 0),
        Math.abs(e.z) < Epsilon && (e.z = 0)
    }
    ,
    __decorate([serialize()], i.prototype, "wheelPrecision", void 0),
    __decorate([serialize()], i.prototype, "zoomToMouseLocation", void 0),
    __decorate([serialize()], i.prototype, "wheelDeltaPercentage", void 0),
    i
}();
CameraInputTypes.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
var ArcRotateCameraInputsManager = function(i) {
    __extends(e, i);
    function e(t) {
        return i.call(this, t) || this
    }
    return e.prototype.addMouseWheel = function() {
        return this.add(new ArcRotateCameraMouseWheelInput),
        this
    }
    ,
    e.prototype.addPointers = function() {
        return this.add(new ArcRotateCameraPointersInput),
        this
    }
    ,
    e.prototype.addKeyboard = function() {
        return this.add(new ArcRotateCameraKeyboardMoveInput),
        this
    }
    ,
    e
}(CameraInputsManager);
Node$2.AddNodeConstructor("ArcRotateCamera", function(i, e) {
    return function() {
        return new ArcRotateCamera(i,0,0,1,Vector3.Zero(),e)
    }
});
var ArcRotateCamera = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a, s, l) {
        l === void 0 && (l = !0);
        var u = i.call(this, t, Vector3.Zero(), s, l) || this;
        return u.inertialAlphaOffset = 0,
        u.inertialBetaOffset = 0,
        u.inertialRadiusOffset = 0,
        u.lowerAlphaLimit = null,
        u.upperAlphaLimit = null,
        u.lowerBetaLimit = .01,
        u.upperBetaLimit = Math.PI - .01,
        u.lowerRadiusLimit = null,
        u.upperRadiusLimit = null,
        u.inertialPanningX = 0,
        u.inertialPanningY = 0,
        u.pinchToPanMaxDistance = 20,
        u.panningDistanceLimit = null,
        u.panningOriginTarget = Vector3.Zero(),
        u.panningInertia = .9,
        u.zoomOnFactor = 1,
        u.targetScreenOffset = Vector2.Zero(),
        u.allowUpsideDown = !0,
        u.useInputToRestoreState = !0,
        u._viewMatrix = new Matrix,
        u.panningAxis = new Vector3(1,1,0),
        u._transformedDirection = new Vector3,
        u.mapPanning = !1,
        u.onMeshTargetChangedObservable = new Observable,
        u.checkCollisions = !1,
        u.collisionRadius = new Vector3(.5,.5,.5),
        u._previousPosition = Vector3.Zero(),
        u._collisionVelocity = Vector3.Zero(),
        u._newPosition = Vector3.Zero(),
        u._computationVector = Vector3.Zero(),
        u._onCollisionPositionChange = function(c, h, f) {
            f === void 0 && (f = null),
            f ? (u.setPosition(h),
            u.onCollide && u.onCollide(f)) : u._previousPosition.copyFrom(u._position);
            var d = Math.cos(u.alpha)
              , _ = Math.sin(u.alpha)
              , g = Math.cos(u.beta)
              , m = Math.sin(u.beta);
            m === 0 && (m = 1e-4);
            var v = u._getTargetPosition();
            u._computationVector.copyFromFloats(u.radius * d * m, u.radius * g, u.radius * _ * m),
            v.addToRef(u._computationVector, u._newPosition),
            u._position.copyFrom(u._newPosition);
            var y = u.upVector;
            u.allowUpsideDown && u.beta < 0 && (y = y.clone(),
            y = y.negate()),
            u._computeViewMatrix(u._position, v, y),
            u._viewMatrix.addAtIndex(12, u.targetScreenOffset.x),
            u._viewMatrix.addAtIndex(13, u.targetScreenOffset.y),
            u._collisionTriggered = !1
        }
        ,
        u._target = Vector3.Zero(),
        a && u.setTarget(a),
        u.alpha = r,
        u.beta = n,
        u.radius = o,
        u.getViewMatrix(),
        u.inputs = new ArcRotateCameraInputsManager(u),
        u.inputs.addKeyboard().addMouseWheel().addPointers(),
        u
    }
    return Object.defineProperty(e.prototype, "target", {
        get: function() {
            return this._target
        },
        set: function(t) {
            this.setTarget(t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "targetHost", {
        get: function() {
            return this._targetHost
        },
        set: function(t) {
            t && this.setTarget(t)
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getTarget = function() {
        return this.target
    }
    ,
    Object.defineProperty(e.prototype, "position", {
        get: function() {
            return this._position
        },
        set: function(t) {
            this.setPosition(t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "upVector", {
        get: function() {
            return this._upVector
        },
        set: function(t) {
            this._upToYMatrix || (this._YToUpMatrix = new Matrix,
            this._upToYMatrix = new Matrix,
            this._upVector = Vector3.Zero()),
            t.normalize(),
            this._upVector.copyFrom(t),
            this.setMatUp()
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.setMatUp = function() {
        Matrix.RotationAlignToRef(Vector3.UpReadOnly, this._upVector, this._YToUpMatrix),
        Matrix.RotationAlignToRef(this._upVector, Vector3.UpReadOnly, this._upToYMatrix)
    }
    ,
    Object.defineProperty(e.prototype, "angularSensibilityX", {
        get: function() {
            var t = this.inputs.attached.pointers;
            return t ? t.angularSensibilityX : 0
        },
        set: function(t) {
            var r = this.inputs.attached.pointers;
            r && (r.angularSensibilityX = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "angularSensibilityY", {
        get: function() {
            var t = this.inputs.attached.pointers;
            return t ? t.angularSensibilityY : 0
        },
        set: function(t) {
            var r = this.inputs.attached.pointers;
            r && (r.angularSensibilityY = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "pinchPrecision", {
        get: function() {
            var t = this.inputs.attached.pointers;
            return t ? t.pinchPrecision : 0
        },
        set: function(t) {
            var r = this.inputs.attached.pointers;
            r && (r.pinchPrecision = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "pinchDeltaPercentage", {
        get: function() {
            var t = this.inputs.attached.pointers;
            return t ? t.pinchDeltaPercentage : 0
        },
        set: function(t) {
            var r = this.inputs.attached.pointers;
            r && (r.pinchDeltaPercentage = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "useNaturalPinchZoom", {
        get: function() {
            var t = this.inputs.attached.pointers;
            return t ? t.useNaturalPinchZoom : !1
        },
        set: function(t) {
            var r = this.inputs.attached.pointers;
            r && (r.useNaturalPinchZoom = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "panningSensibility", {
        get: function() {
            var t = this.inputs.attached.pointers;
            return t ? t.panningSensibility : 0
        },
        set: function(t) {
            var r = this.inputs.attached.pointers;
            r && (r.panningSensibility = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "keysUp", {
        get: function() {
            var t = this.inputs.attached.keyboard;
            return t ? t.keysUp : []
        },
        set: function(t) {
            var r = this.inputs.attached.keyboard;
            r && (r.keysUp = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "keysDown", {
        get: function() {
            var t = this.inputs.attached.keyboard;
            return t ? t.keysDown : []
        },
        set: function(t) {
            var r = this.inputs.attached.keyboard;
            r && (r.keysDown = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "keysLeft", {
        get: function() {
            var t = this.inputs.attached.keyboard;
            return t ? t.keysLeft : []
        },
        set: function(t) {
            var r = this.inputs.attached.keyboard;
            r && (r.keysLeft = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "keysRight", {
        get: function() {
            var t = this.inputs.attached.keyboard;
            return t ? t.keysRight : []
        },
        set: function(t) {
            var r = this.inputs.attached.keyboard;
            r && (r.keysRight = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "wheelPrecision", {
        get: function() {
            var t = this.inputs.attached.mousewheel;
            return t ? t.wheelPrecision : 0
        },
        set: function(t) {
            var r = this.inputs.attached.mousewheel;
            r && (r.wheelPrecision = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "zoomToMouseLocation", {
        get: function() {
            var t = this.inputs.attached.mousewheel;
            return t ? t.zoomToMouseLocation : !1
        },
        set: function(t) {
            var r = this.inputs.attached.mousewheel;
            r && (r.zoomToMouseLocation = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "wheelDeltaPercentage", {
        get: function() {
            var t = this.inputs.attached.mousewheel;
            return t ? t.wheelDeltaPercentage : 0
        },
        set: function(t) {
            var r = this.inputs.attached.mousewheel;
            r && (r.wheelDeltaPercentage = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "bouncingBehavior", {
        get: function() {
            return this._bouncingBehavior
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "useBouncingBehavior", {
        get: function() {
            return this._bouncingBehavior != null
        },
        set: function(t) {
            t !== this.useBouncingBehavior && (t ? (this._bouncingBehavior = new BouncingBehavior,
            this.addBehavior(this._bouncingBehavior)) : this._bouncingBehavior && (this.removeBehavior(this._bouncingBehavior),
            this._bouncingBehavior = null))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "framingBehavior", {
        get: function() {
            return this._framingBehavior
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "useFramingBehavior", {
        get: function() {
            return this._framingBehavior != null
        },
        set: function(t) {
            t !== this.useFramingBehavior && (t ? (this._framingBehavior = new FramingBehavior,
            this.addBehavior(this._framingBehavior)) : this._framingBehavior && (this.removeBehavior(this._framingBehavior),
            this._framingBehavior = null))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "autoRotationBehavior", {
        get: function() {
            return this._autoRotationBehavior
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "useAutoRotationBehavior", {
        get: function() {
            return this._autoRotationBehavior != null
        },
        set: function(t) {
            t !== this.useAutoRotationBehavior && (t ? (this._autoRotationBehavior = new AutoRotationBehavior,
            this.addBehavior(this._autoRotationBehavior)) : this._autoRotationBehavior && (this.removeBehavior(this._autoRotationBehavior),
            this._autoRotationBehavior = null))
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._initCache = function() {
        i.prototype._initCache.call(this),
        this._cache._target = new Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),
        this._cache.alpha = void 0,
        this._cache.beta = void 0,
        this._cache.radius = void 0,
        this._cache.targetScreenOffset = Vector2.Zero()
    }
    ,
    e.prototype._updateCache = function(t) {
        t || i.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)
    }
    ,
    e.prototype._getTargetPosition = function() {
        if (this._targetHost && this._targetHost.getAbsolutePosition) {
            var t = this._targetHost.getAbsolutePosition();
            this._targetBoundingCenter ? t.addToRef(this._targetBoundingCenter, this._target) : this._target.copyFrom(t)
        }
        var r = this._getLockedTargetPosition();
        return r || this._target
    }
    ,
    e.prototype.storeState = function() {
        return this._storedAlpha = this.alpha,
        this._storedBeta = this.beta,
        this._storedRadius = this.radius,
        this._storedTarget = this._getTargetPosition().clone(),
        this._storedTargetScreenOffset = this.targetScreenOffset.clone(),
        i.prototype.storeState.call(this)
    }
    ,
    e.prototype._restoreStateValues = function() {
        return i.prototype._restoreStateValues.call(this) ? (this.setTarget(this._storedTarget.clone()),
        this.alpha = this._storedAlpha,
        this.beta = this._storedBeta,
        this.radius = this._storedRadius,
        this.targetScreenOffset = this._storedTargetScreenOffset.clone(),
        this.inertialAlphaOffset = 0,
        this.inertialBetaOffset = 0,
        this.inertialRadiusOffset = 0,
        this.inertialPanningX = 0,
        this.inertialPanningY = 0,
        !0) : !1
    }
    ,
    e.prototype._isSynchronizedViewMatrix = function() {
        return i.prototype._isSynchronizedViewMatrix.call(this) ? 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) : !1
    }
    ,
    e.prototype.attachControl = function(t, r, n, o) {
        var a = this;
        n === void 0 && (n = !0),
        o === void 0 && (o = 2),
        r = Tools.BackCompatCameraNoPreventDefault(arguments),
        this._useCtrlForPanning = n,
        this._panningMouseButton = o,
        typeof arguments[0] == "boolean" && (arguments.length > 1 && (this._useCtrlForPanning = arguments[1]),
        arguments.length > 2 && (this._panningMouseButton = arguments[2])),
        this.inputs.attachElement(r),
        this._reset = function() {
            a.inertialAlphaOffset = 0,
            a.inertialBetaOffset = 0,
            a.inertialRadiusOffset = 0,
            a.inertialPanningX = 0,
            a.inertialPanningY = 0
        }
    }
    ,
    e.prototype.detachControl = function(t) {
        this.inputs.detachElement(),
        this._reset && this._reset()
    }
    ,
    e.prototype._checkInputs = function() {
        if (!this._collisionTriggered) {
            if (this.inputs.checkInputs(),
            this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
                var t = this.inertialAlphaOffset;
                this.beta <= 0 && (t *= -1),
                this.getScene().useRightHandedSystem && (t *= -1),
                this.parent && this.parent._getWorldMatrixDeterminant() < 0 && (t *= -1),
                this.alpha += t,
                this.beta += this.inertialBetaOffset,
                this.radius -= this.inertialRadiusOffset,
                this.inertialAlphaOffset *= this.inertia,
                this.inertialBetaOffset *= this.inertia,
                this.inertialRadiusOffset *= this.inertia,
                Math.abs(this.inertialAlphaOffset) < Epsilon && (this.inertialAlphaOffset = 0),
                Math.abs(this.inertialBetaOffset) < Epsilon && (this.inertialBetaOffset = 0),
                Math.abs(this.inertialRadiusOffset) < this.speed * Epsilon && (this.inertialRadiusOffset = 0)
            }
            if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
                var r = new Vector3(this.inertialPanningX,this.inertialPanningY,this.inertialPanningY);
                if (this._viewMatrix.invertToRef(this._cameraTransformMatrix),
                r.multiplyInPlace(this.panningAxis),
                Vector3.TransformNormalToRef(r, this._cameraTransformMatrix, this._transformedDirection),
                this.mapPanning && (this._transformedDirection.y = 0),
                !this._targetHost)
                    if (this.panningDistanceLimit) {
                        this._transformedDirection.addInPlace(this._target);
                        var n = Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
                        n <= this.panningDistanceLimit * this.panningDistanceLimit && this._target.copyFrom(this._transformedDirection)
                    } else
                        this._target.addInPlace(this._transformedDirection);
                this.inertialPanningX *= this.panningInertia,
                this.inertialPanningY *= this.panningInertia,
                Math.abs(this.inertialPanningX) < this.speed * Epsilon && (this.inertialPanningX = 0),
                Math.abs(this.inertialPanningY) < this.speed * Epsilon && (this.inertialPanningY = 0)
            }
            this._checkLimits(),
            i.prototype._checkInputs.call(this)
        }
    }
    ,
    e.prototype._checkLimits = function() {
        this.lowerBetaLimit === null || this.lowerBetaLimit === void 0 ? this.allowUpsideDown && this.beta > Math.PI && (this.beta = this.beta - 2 * Math.PI) : this.beta < this.lowerBetaLimit && (this.beta = this.lowerBetaLimit),
        this.upperBetaLimit === null || this.upperBetaLimit === void 0 ? this.allowUpsideDown && this.beta < -Math.PI && (this.beta = this.beta + 2 * Math.PI) : this.beta > this.upperBetaLimit && (this.beta = this.upperBetaLimit),
        this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit && (this.alpha = this.lowerAlphaLimit),
        this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit && (this.alpha = this.upperAlphaLimit),
        this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit && (this.radius = this.lowerRadiusLimit,
        this.inertialRadiusOffset = 0),
        this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit && (this.radius = this.upperRadiusLimit,
        this.inertialRadiusOffset = 0)
    }
    ,
    e.prototype.rebuildAnglesAndRadius = function() {
        this._position.subtractToRef(this._getTargetPosition(), this._computationVector),
        (this._upVector.x !== 0 || this._upVector.y !== 1 || this._upVector.z !== 0) && Vector3.TransformCoordinatesToRef(this._computationVector, this._upToYMatrix, this._computationVector),
        this.radius = this._computationVector.length(),
        this.radius === 0 && (this.radius = 1e-4);
        var t = this.alpha;
        this._computationVector.x === 0 && this._computationVector.z === 0 ? this.alpha = Math.PI / 2 : this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2))),
        this._computationVector.z < 0 && (this.alpha = 2 * Math.PI - this.alpha);
        var r = Math.round((t - this.alpha) / (2 * Math.PI));
        this.alpha += r * 2 * Math.PI,
        this.beta = Math.acos(this._computationVector.y / this.radius),
        this._checkLimits()
    }
    ,
    e.prototype.setPosition = function(t) {
        this._position.equals(t) || (this._position.copyFrom(t),
        this.rebuildAnglesAndRadius())
    }
    ,
    e.prototype.setTarget = function(t, r, n) {
        if (r === void 0 && (r = !1),
        n === void 0 && (n = !1),
        t.getBoundingInfo)
            r ? this._targetBoundingCenter = t.getBoundingInfo().boundingBox.centerWorld.clone() : this._targetBoundingCenter = null,
            t.computeWorldMatrix(),
            this._targetHost = t,
            this._target = this._getTargetPosition(),
            this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
        else {
            var o = t
              , a = this._getTargetPosition();
            if (a && !n && a.equals(o))
                return;
            this._targetHost = null,
            this._target = o,
            this._targetBoundingCenter = null,
            this.onMeshTargetChangedObservable.notifyObservers(null)
        }
        this.rebuildAnglesAndRadius()
    }
    ,
    e.prototype._getViewMatrix = function() {
        var t = Math.cos(this.alpha)
          , r = Math.sin(this.alpha)
          , n = Math.cos(this.beta)
          , o = Math.sin(this.beta);
        o === 0 && (o = 1e-4),
        this.radius === 0 && (this.radius = 1e-4);
        var a = this._getTargetPosition();
        if (this._computationVector.copyFromFloats(this.radius * t * o, this.radius * n, this.radius * r * o),
        (this._upVector.x !== 0 || this._upVector.y !== 1 || this._upVector.z !== 0) && Vector3.TransformCoordinatesToRef(this._computationVector, this._YToUpMatrix, this._computationVector),
        a.addToRef(this._computationVector, this._newPosition),
        this.getScene().collisionsEnabled && this.checkCollisions) {
            var s = this.getScene().collisionCoordinator;
            this._collider || (this._collider = s.createCollider()),
            this._collider._radius = this.collisionRadius,
            this._newPosition.subtractToRef(this._position, this._collisionVelocity),
            this._collisionTriggered = !0,
            s.getNewPosition(this._position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId)
        } else {
            this._position.copyFrom(this._newPosition);
            var l = this.upVector;
            this.allowUpsideDown && o < 0 && (l = l.negate()),
            this._computeViewMatrix(this._position, a, l),
            this._viewMatrix.addAtIndex(12, this.targetScreenOffset.x),
            this._viewMatrix.addAtIndex(13, this.targetScreenOffset.y)
        }
        return this._currentTarget = a,
        this._viewMatrix
    }
    ,
    e.prototype.zoomOn = function(t, r) {
        r === void 0 && (r = !1),
        t = t || this.getScene().meshes;
        var n = Mesh.MinMax(t)
          , o = Vector3.Distance(n.min, n.max);
        this.radius = o * this.zoomOnFactor,
        this.focusOn({
            min: n.min,
            max: n.max,
            distance: o
        }, r)
    }
    ,
    e.prototype.focusOn = function(t, r) {
        r === void 0 && (r = !1);
        var n, o;
        if (t.min === void 0) {
            var a = t || this.getScene().meshes;
            n = Mesh.MinMax(a),
            o = Vector3.Distance(n.min, n.max)
        } else {
            var s = t;
            n = s,
            o = s.distance
        }
        this._target = Mesh.Center(n),
        r || (this.maxZ = o * 2)
    }
    ,
    e.prototype.createRigCamera = function(t, r) {
        var n = 0;
        switch (this.cameraRigMode) {
        case Camera$1.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
        case Camera$1.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
        case Camera$1.RIG_MODE_STEREOSCOPIC_OVERUNDER:
        case Camera$1.RIG_MODE_STEREOSCOPIC_INTERLACED:
        case Camera$1.RIG_MODE_VR:
            n = this._cameraRigParams.stereoHalfAngle * (r === 0 ? 1 : -1);
            break;
        case Camera$1.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
            n = this._cameraRigParams.stereoHalfAngle * (r === 0 ? -1 : 1);
            break
        }
        var o = new e(t,this.alpha + n,this.beta,this.radius,this._target,this.getScene());
        return o._cameraRigParams = {},
        o.isRigCamera = !0,
        o.rigParent = this,
        o.upVector = this.upVector,
        o
    }
    ,
    e.prototype._updateRigCameras = function() {
        var t = this._rigCameras[0]
          , r = this._rigCameras[1];
        switch (t.beta = r.beta = this.beta,
        this.cameraRigMode) {
        case Camera$1.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
        case Camera$1.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
        case Camera$1.RIG_MODE_STEREOSCOPIC_OVERUNDER:
        case Camera$1.RIG_MODE_STEREOSCOPIC_INTERLACED:
        case Camera$1.RIG_MODE_VR:
            t.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle,
            r.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
            break;
        case Camera$1.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
            t.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle,
            r.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
            break
        }
        i.prototype._updateRigCameras.call(this)
    }
    ,
    e.prototype.dispose = function() {
        this.inputs.clear(),
        i.prototype.dispose.call(this)
    }
    ,
    e.prototype.getClassName = function() {
        return "ArcRotateCamera"
    }
    ,
    __decorate([serialize()], e.prototype, "alpha", void 0),
    __decorate([serialize()], e.prototype, "beta", void 0),
    __decorate([serialize()], e.prototype, "radius", void 0),
    __decorate([serializeAsVector3("target")], e.prototype, "_target", void 0),
    __decorate([serializeAsMeshReference("targetHost")], e.prototype, "_targetHost", void 0),
    __decorate([serialize()], e.prototype, "inertialAlphaOffset", void 0),
    __decorate([serialize()], e.prototype, "inertialBetaOffset", void 0),
    __decorate([serialize()], e.prototype, "inertialRadiusOffset", void 0),
    __decorate([serialize()], e.prototype, "lowerAlphaLimit", void 0),
    __decorate([serialize()], e.prototype, "upperAlphaLimit", void 0),
    __decorate([serialize()], e.prototype, "lowerBetaLimit", void 0),
    __decorate([serialize()], e.prototype, "upperBetaLimit", void 0),
    __decorate([serialize()], e.prototype, "lowerRadiusLimit", void 0),
    __decorate([serialize()], e.prototype, "upperRadiusLimit", void 0),
    __decorate([serialize()], e.prototype, "inertialPanningX", void 0),
    __decorate([serialize()], e.prototype, "inertialPanningY", void 0),
    __decorate([serialize()], e.prototype, "pinchToPanMaxDistance", void 0),
    __decorate([serialize()], e.prototype, "panningDistanceLimit", void 0),
    __decorate([serializeAsVector3()], e.prototype, "panningOriginTarget", void 0),
    __decorate([serialize()], e.prototype, "panningInertia", void 0),
    __decorate([serialize()], e.prototype, "zoomToMouseLocation", null),
    __decorate([serialize()], e.prototype, "zoomOnFactor", void 0),
    __decorate([serialize()], e.prototype, "targetScreenOffset", void 0),
    __decorate([serialize()], e.prototype, "allowUpsideDown", void 0),
    __decorate([serialize()], e.prototype, "useInputToRestoreState", void 0),
    e
}(TargetCamera)
  , FreeCameraKeyboardMoveInput = function() {
    function i() {
        this.keysUp = [38],
        this.keysUpward = [33],
        this.keysDown = [40],
        this.keysDownward = [34],
        this.keysLeft = [37],
        this.keysRight = [39],
        this.rotationSpeed = .5,
        this.keysRotateLeft = [],
        this.keysRotateRight = [],
        this._keys = new Array
    }
    return i.prototype.attachControl = function(e) {
        var t = this;
        e = Tools.BackCompatCameraNoPreventDefault(arguments),
        !this._onCanvasBlurObserver && (this._scene = this.camera.getScene(),
        this._engine = this._scene.getEngine(),
        this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function() {
            t._keys = []
        }),
        this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function(r) {
            var n = r.event;
            if (!n.metaKey) {
                if (r.type === KeyboardEventTypes.KEYDOWN) {
                    if (t.keysUp.indexOf(n.keyCode) !== -1 || t.keysDown.indexOf(n.keyCode) !== -1 || t.keysLeft.indexOf(n.keyCode) !== -1 || t.keysRight.indexOf(n.keyCode) !== -1 || t.keysUpward.indexOf(n.keyCode) !== -1 || t.keysDownward.indexOf(n.keyCode) !== -1 || t.keysRotateLeft.indexOf(n.keyCode) !== -1 || t.keysRotateRight.indexOf(n.keyCode) !== -1) {
                        var o = t._keys.indexOf(n.keyCode);
                        o === -1 && t._keys.push(n.keyCode),
                        e || n.preventDefault()
                    }
                } else if (t.keysUp.indexOf(n.keyCode) !== -1 || t.keysDown.indexOf(n.keyCode) !== -1 || t.keysLeft.indexOf(n.keyCode) !== -1 || t.keysRight.indexOf(n.keyCode) !== -1 || t.keysUpward.indexOf(n.keyCode) !== -1 || t.keysDownward.indexOf(n.keyCode) !== -1 || t.keysRotateLeft.indexOf(n.keyCode) !== -1 || t.keysRotateRight.indexOf(n.keyCode) !== -1) {
                    var o = t._keys.indexOf(n.keyCode);
                    o >= 0 && t._keys.splice(o, 1),
                    e || n.preventDefault()
                }
            }
        }))
    }
    ,
    i.prototype.detachControl = function(e) {
        this._scene && (this._onKeyboardObserver && this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),
        this._onCanvasBlurObserver && this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),
        this._onKeyboardObserver = null,
        this._onCanvasBlurObserver = null),
        this._keys = []
    }
    ,
    i.prototype.checkInputs = function() {
        if (this._onKeyboardObserver)
            for (var e = this.camera, t = 0; t < this._keys.length; t++) {
                var r = this._keys[t]
                  , n = e._computeLocalCameraSpeed();
                this.keysLeft.indexOf(r) !== -1 ? e._localDirection.copyFromFloats(-n, 0, 0) : this.keysUp.indexOf(r) !== -1 ? e._localDirection.copyFromFloats(0, 0, n) : this.keysRight.indexOf(r) !== -1 ? e._localDirection.copyFromFloats(n, 0, 0) : this.keysDown.indexOf(r) !== -1 ? e._localDirection.copyFromFloats(0, 0, -n) : this.keysUpward.indexOf(r) !== -1 ? e._localDirection.copyFromFloats(0, n, 0) : this.keysDownward.indexOf(r) !== -1 ? e._localDirection.copyFromFloats(0, -n, 0) : this.keysRotateLeft.indexOf(r) !== -1 ? (e._localDirection.copyFromFloats(0, 0, 0),
                e.cameraRotation.y -= this._getLocalRotation()) : this.keysRotateRight.indexOf(r) !== -1 && (e._localDirection.copyFromFloats(0, 0, 0),
                e.cameraRotation.y += this._getLocalRotation()),
                e.getScene().useRightHandedSystem && (e._localDirection.z *= -1),
                e.getViewMatrix().invertToRef(e._cameraTransformMatrix),
                Vector3.TransformNormalToRef(e._localDirection, e._cameraTransformMatrix, e._transformedDirection),
                e.cameraDirection.addInPlace(e._transformedDirection)
            }
    }
    ,
    i.prototype.getClassName = function() {
        return "FreeCameraKeyboardMoveInput"
    }
    ,
    i.prototype._onLostFocus = function() {
        this._keys = []
    }
    ,
    i.prototype.getSimpleName = function() {
        return "keyboard"
    }
    ,
    i.prototype._getLocalRotation = function() {
        var e = this.rotationSpeed * this._engine.getDeltaTime() / 1e3;
        return this.camera.getScene().useRightHandedSystem && (e *= -1),
        this.camera.parent && this.camera.parent._getWorldMatrixDeterminant() < 0 && (e *= -1),
        e
    }
    ,
    __decorate([serialize()], i.prototype, "keysUp", void 0),
    __decorate([serialize()], i.prototype, "keysUpward", void 0),
    __decorate([serialize()], i.prototype, "keysDown", void 0),
    __decorate([serialize()], i.prototype, "keysDownward", void 0),
    __decorate([serialize()], i.prototype, "keysLeft", void 0),
    __decorate([serialize()], i.prototype, "keysRight", void 0),
    __decorate([serialize()], i.prototype, "rotationSpeed", void 0),
    __decorate([serialize()], i.prototype, "keysRotateLeft", void 0),
    __decorate([serialize()], i.prototype, "keysRotateRight", void 0),
    i
}();
CameraInputTypes.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
var FreeCameraMouseInput = function() {
    function i(e) {
        e === void 0 && (e = !0),
        this.touchEnabled = e,
        this.buttons = [0, 1, 2],
        this.angularSensibility = 2e3,
        this.previousPosition = null,
        this.onPointerMovedObservable = new Observable,
        this._allowCameraRotation = !0,
        this._currentActiveButton = -1
    }
    return i.prototype.attachControl = function(e) {
        var t = this;
        e = Tools.BackCompatCameraNoPreventDefault(arguments);
        var r = this.camera.getEngine()
          , n = r.getInputElement();
        this._pointerInput || (this._pointerInput = function(o) {
            var a = o.event
              , s = a.pointerType === "touch";
            if (!r.isInVRExclusivePointerMode && !(!t.touchEnabled && s) && !(o.type !== PointerEventTypes.POINTERMOVE && t.buttons.indexOf(a.button) === -1)) {
                var l = a.srcElement || a.target;
                if (o.type === PointerEventTypes.POINTERDOWN && (t._currentActiveButton === -1 || s)) {
                    try {
                        l == null || l.setPointerCapture(a.pointerId)
                    } catch {}
                    t._currentActiveButton === -1 && (t._currentActiveButton = a.button),
                    t.previousPosition = {
                        x: a.clientX,
                        y: a.clientY
                    },
                    e || (a.preventDefault(),
                    n && n.focus()),
                    r.isPointerLock && t._onMouseMove && t._onMouseMove(o.event)
                } else if (o.type === PointerEventTypes.POINTERUP && (t._currentActiveButton === a.button || s)) {
                    try {
                        l == null || l.releasePointerCapture(a.pointerId)
                    } catch {}
                    t._currentActiveButton = -1,
                    t.previousPosition = null,
                    e || a.preventDefault()
                } else if (o.type === PointerEventTypes.POINTERMOVE) {
                    if (r.isPointerLock && t._onMouseMove)
                        t._onMouseMove(o.event);
                    else if (t.previousPosition) {
                        var u = a.clientX - t.previousPosition.x
                          , c = a.clientY - t.previousPosition.y;
                        t.camera.getScene().useRightHandedSystem && (u *= -1),
                        t.camera.parent && t.camera.parent._getWorldMatrixDeterminant() < 0 && (u *= -1),
                        t._allowCameraRotation && (t.camera.cameraRotation.y += u / t.angularSensibility,
                        t.camera.cameraRotation.x += c / t.angularSensibility),
                        t.onPointerMovedObservable.notifyObservers({
                            offsetX: u,
                            offsetY: c
                        }),
                        t.previousPosition = {
                            x: a.clientX,
                            y: a.clientY
                        },
                        e || a.preventDefault()
                    }
                }
            }
        }
        ),
        this._onMouseMove = function(o) {
            if (!!r.isPointerLock && !r.isInVRExclusivePointerMode) {
                var a = o.movementX || o.mozMovementX || o.webkitMovementX || o.msMovementX || 0;
                t.camera.getScene().useRightHandedSystem && (a *= -1),
                t.camera.parent && t.camera.parent._getWorldMatrixDeterminant() < 0 && (a *= -1),
                t.camera.cameraRotation.y += a / t.angularSensibility;
                var s = o.movementY || o.mozMovementY || o.webkitMovementY || o.msMovementY || 0;
                t.camera.cameraRotation.x += s / t.angularSensibility,
                t.previousPosition = null,
                e || o.preventDefault()
            }
        }
        ,
        this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, PointerEventTypes.POINTERDOWN | PointerEventTypes.POINTERUP | PointerEventTypes.POINTERMOVE),
        n && n.addEventListener("contextmenu", this.onContextMenu.bind(this), !1)
    }
    ,
    i.prototype.onContextMenu = function(e) {
        e.preventDefault()
    }
    ,
    i.prototype.detachControl = function(e) {
        if (this._observer) {
            if (this.camera.getScene().onPointerObservable.remove(this._observer),
            this.onContextMenu) {
                var t = this.camera.getEngine()
                  , r = t.getInputElement();
                r && r.removeEventListener("contextmenu", this.onContextMenu)
            }
            this.onPointerMovedObservable && this.onPointerMovedObservable.clear(),
            this._observer = null,
            this._onMouseMove = null,
            this.previousPosition = null
        }
    }
    ,
    i.prototype.getClassName = function() {
        return "FreeCameraMouseInput"
    }
    ,
    i.prototype.getSimpleName = function() {
        return "mouse"
    }
    ,
    __decorate([serialize()], i.prototype, "buttons", void 0),
    __decorate([serialize()], i.prototype, "angularSensibility", void 0),
    i
}();
CameraInputTypes.FreeCameraMouseInput = FreeCameraMouseInput;
var BaseCameraMouseWheelInput = function() {
    function i() {
        this.wheelPrecisionX = 3,
        this.wheelPrecisionY = 3,
        this.wheelPrecisionZ = 3,
        this.onChangedObservable = new Observable,
        this._wheelDeltaX = 0,
        this._wheelDeltaY = 0,
        this._wheelDeltaZ = 0,
        this._ffMultiplier = 12,
        this._normalize = 120
    }
    return i.prototype.attachControl = function(e) {
        var t = this;
        e = Tools.BackCompatCameraNoPreventDefault(arguments),
        this._wheel = function(r) {
            if (r.type === PointerEventTypes.POINTERWHEEL) {
                var n = r.event
                  , o = n.deltaMode === EventConstants.DOM_DELTA_LINE ? t._ffMultiplier : 1;
                n.deltaY !== void 0 ? (t._wheelDeltaX += t.wheelPrecisionX * o * n.deltaX / t._normalize,
                t._wheelDeltaY -= t.wheelPrecisionY * o * n.deltaY / t._normalize,
                t._wheelDeltaZ += t.wheelPrecisionZ * o * n.deltaZ / t._normalize) : n.wheelDeltaY !== void 0 ? (t._wheelDeltaX += t.wheelPrecisionX * o * n.wheelDeltaX / t._normalize,
                t._wheelDeltaY -= t.wheelPrecisionY * o * n.wheelDeltaY / t._normalize,
                t._wheelDeltaZ += t.wheelPrecisionZ * o * n.wheelDeltaZ / t._normalize) : n.wheelDelta && (t._wheelDeltaY -= t.wheelPrecisionY * n.wheelDelta / t._normalize),
                n.preventDefault && (e || n.preventDefault())
            }
        }
        ,
        this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, PointerEventTypes.POINTERWHEEL)
    }
    ,
    i.prototype.detachControl = function(e) {
        this._observer && (this.camera.getScene().onPointerObservable.remove(this._observer),
        this._observer = null,
        this._wheel = null),
        this.onChangedObservable && this.onChangedObservable.clear()
    }
    ,
    i.prototype.checkInputs = function() {
        this.onChangedObservable.notifyObservers({
            wheelDeltaX: this._wheelDeltaX,
            wheelDeltaY: this._wheelDeltaY,
            wheelDeltaZ: this._wheelDeltaZ
        }),
        this._wheelDeltaX = 0,
        this._wheelDeltaY = 0,
        this._wheelDeltaZ = 0
    }
    ,
    i.prototype.getClassName = function() {
        return "BaseCameraMouseWheelInput"
    }
    ,
    i.prototype.getSimpleName = function() {
        return "mousewheel"
    }
    ,
    __decorate([serialize()], i.prototype, "wheelPrecisionX", void 0),
    __decorate([serialize()], i.prototype, "wheelPrecisionY", void 0),
    __decorate([serialize()], i.prototype, "wheelPrecisionZ", void 0),
    i
}(), _CameraProperty;
(function(i) {
    i[i.MoveRelative = 0] = "MoveRelative",
    i[i.RotateRelative = 1] = "RotateRelative",
    i[i.MoveScene = 2] = "MoveScene"
}
)(_CameraProperty || (_CameraProperty = {}));
var FreeCameraMouseWheelInput = function(i) {
    __extends(e, i);
    function e() {
        var t = i !== null && i.apply(this, arguments) || this;
        return t._moveRelative = Vector3.Zero(),
        t._rotateRelative = Vector3.Zero(),
        t._moveScene = Vector3.Zero(),
        t._wheelXAction = _CameraProperty.MoveRelative,
        t._wheelXActionCoordinate = Coordinate.X,
        t._wheelYAction = _CameraProperty.MoveRelative,
        t._wheelYActionCoordinate = Coordinate.Z,
        t._wheelZAction = null,
        t._wheelZActionCoordinate = null,
        t
    }
    return e.prototype.getClassName = function() {
        return "FreeCameraMouseWheelInput"
    }
    ,
    Object.defineProperty(e.prototype, "wheelXMoveRelative", {
        get: function() {
            return this._wheelXAction !== _CameraProperty.MoveRelative ? null : this._wheelXActionCoordinate
        },
        set: function(t) {
            t === null && this._wheelXAction !== _CameraProperty.MoveRelative || (this._wheelXAction = _CameraProperty.MoveRelative,
            this._wheelXActionCoordinate = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "wheelYMoveRelative", {
        get: function() {
            return this._wheelYAction !== _CameraProperty.MoveRelative ? null : this._wheelYActionCoordinate
        },
        set: function(t) {
            t === null && this._wheelYAction !== _CameraProperty.MoveRelative || (this._wheelYAction = _CameraProperty.MoveRelative,
            this._wheelYActionCoordinate = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "wheelZMoveRelative", {
        get: function() {
            return this._wheelZAction !== _CameraProperty.MoveRelative ? null : this._wheelZActionCoordinate
        },
        set: function(t) {
            t === null && this._wheelZAction !== _CameraProperty.MoveRelative || (this._wheelZAction = _CameraProperty.MoveRelative,
            this._wheelZActionCoordinate = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "wheelXRotateRelative", {
        get: function() {
            return this._wheelXAction !== _CameraProperty.RotateRelative ? null : this._wheelXActionCoordinate
        },
        set: function(t) {
            t === null && this._wheelXAction !== _CameraProperty.RotateRelative || (this._wheelXAction = _CameraProperty.RotateRelative,
            this._wheelXActionCoordinate = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "wheelYRotateRelative", {
        get: function() {
            return this._wheelYAction !== _CameraProperty.RotateRelative ? null : this._wheelYActionCoordinate
        },
        set: function(t) {
            t === null && this._wheelYAction !== _CameraProperty.RotateRelative || (this._wheelYAction = _CameraProperty.RotateRelative,
            this._wheelYActionCoordinate = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "wheelZRotateRelative", {
        get: function() {
            return this._wheelZAction !== _CameraProperty.RotateRelative ? null : this._wheelZActionCoordinate
        },
        set: function(t) {
            t === null && this._wheelZAction !== _CameraProperty.RotateRelative || (this._wheelZAction = _CameraProperty.RotateRelative,
            this._wheelZActionCoordinate = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "wheelXMoveScene", {
        get: function() {
            return this._wheelXAction !== _CameraProperty.MoveScene ? null : this._wheelXActionCoordinate
        },
        set: function(t) {
            t === null && this._wheelXAction !== _CameraProperty.MoveScene || (this._wheelXAction = _CameraProperty.MoveScene,
            this._wheelXActionCoordinate = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "wheelYMoveScene", {
        get: function() {
            return this._wheelYAction !== _CameraProperty.MoveScene ? null : this._wheelYActionCoordinate
        },
        set: function(t) {
            t === null && this._wheelYAction !== _CameraProperty.MoveScene || (this._wheelYAction = _CameraProperty.MoveScene,
            this._wheelYActionCoordinate = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "wheelZMoveScene", {
        get: function() {
            return this._wheelZAction !== _CameraProperty.MoveScene ? null : this._wheelZActionCoordinate
        },
        set: function(t) {
            t === null && this._wheelZAction !== _CameraProperty.MoveScene || (this._wheelZAction = _CameraProperty.MoveScene,
            this._wheelZActionCoordinate = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.checkInputs = function() {
        if (!(this._wheelDeltaX === 0 && this._wheelDeltaY === 0 && this._wheelDeltaZ == 0)) {
            this._moveRelative.setAll(0),
            this._rotateRelative.setAll(0),
            this._moveScene.setAll(0),
            this._updateCamera(),
            this.camera.getScene().useRightHandedSystem && (this._moveRelative.z *= -1);
            var t = Matrix.Zero();
            this.camera.getViewMatrix().invertToRef(t);
            var r = Vector3.Zero();
            Vector3.TransformNormalToRef(this._moveRelative, t, r),
            this.camera.cameraRotation.x += this._rotateRelative.x / 200,
            this.camera.cameraRotation.y += this._rotateRelative.y / 200,
            this.camera.cameraDirection.addInPlace(r),
            this.camera.cameraDirection.addInPlace(this._moveScene),
            i.prototype.checkInputs.call(this)
        }
    }
    ,
    e.prototype._updateCamera = function() {
        this._updateCameraProperty(this._wheelDeltaX, this._wheelXAction, this._wheelXActionCoordinate),
        this._updateCameraProperty(this._wheelDeltaY, this._wheelYAction, this._wheelYActionCoordinate),
        this._updateCameraProperty(this._wheelDeltaZ, this._wheelZAction, this._wheelZActionCoordinate)
    }
    ,
    e.prototype._updateCameraProperty = function(t, r, n) {
        if (t !== 0 && !(r === null || n === null)) {
            var o = null;
            switch (r) {
            case _CameraProperty.MoveRelative:
                o = this._moveRelative;
                break;
            case _CameraProperty.RotateRelative:
                o = this._rotateRelative;
                break;
            case _CameraProperty.MoveScene:
                o = this._moveScene;
                break
            }
            switch (n) {
            case Coordinate.X:
                o.set(t, 0, 0);
                break;
            case Coordinate.Y:
                o.set(0, t, 0);
                break;
            case Coordinate.Z:
                o.set(0, 0, t);
                break
            }
        }
    }
    ,
    __decorate([serialize()], e.prototype, "wheelXMoveRelative", null),
    __decorate([serialize()], e.prototype, "wheelYMoveRelative", null),
    __decorate([serialize()], e.prototype, "wheelZMoveRelative", null),
    __decorate([serialize()], e.prototype, "wheelXRotateRelative", null),
    __decorate([serialize()], e.prototype, "wheelYRotateRelative", null),
    __decorate([serialize()], e.prototype, "wheelZRotateRelative", null),
    __decorate([serialize()], e.prototype, "wheelXMoveScene", null),
    __decorate([serialize()], e.prototype, "wheelYMoveScene", null),
    __decorate([serialize()], e.prototype, "wheelZMoveScene", null),
    e
}(BaseCameraMouseWheelInput);
CameraInputTypes.FreeCameraMouseWheelInput = FreeCameraMouseWheelInput;
var FreeCameraTouchInput = function() {
    function i(e) {
        e === void 0 && (e = !1),
        this.allowMouse = e,
        this.touchAngularSensibility = 2e5,
        this.touchMoveSensibility = 250,
        this.singleFingerRotate = !1,
        this._offsetX = null,
        this._offsetY = null,
        this._pointerPressed = new Array
    }
    return i.prototype.attachControl = function(e) {
        var t = this;
        e = Tools.BackCompatCameraNoPreventDefault(arguments);
        var r = null;
        if (this._pointerInput === void 0 && (this._onLostFocus = function() {
            t._offsetX = null,
            t._offsetY = null
        }
        ,
        this._pointerInput = function(a) {
            var s = a.event
              , l = !t.camera.getEngine().hostInformation.isMobile && s instanceof MouseEvent;
            if (!(!t.allowMouse && (s.pointerType === "mouse" || l))) {
                if (a.type === PointerEventTypes.POINTERDOWN) {
                    if (e || s.preventDefault(),
                    t._pointerPressed.push(s.pointerId),
                    t._pointerPressed.length !== 1)
                        return;
                    r = {
                        x: s.clientX,
                        y: s.clientY
                    }
                } else if (a.type === PointerEventTypes.POINTERUP) {
                    e || s.preventDefault();
                    var u = t._pointerPressed.indexOf(s.pointerId);
                    if (u === -1 || (t._pointerPressed.splice(u, 1),
                    u != 0))
                        return;
                    r = null,
                    t._offsetX = null,
                    t._offsetY = null
                } else if (a.type === PointerEventTypes.POINTERMOVE) {
                    if (e || s.preventDefault(),
                    !r)
                        return;
                    var u = t._pointerPressed.indexOf(s.pointerId);
                    if (u != 0)
                        return;
                    t._offsetX = s.clientX - r.x,
                    t._offsetY = -(s.clientY - r.y)
                }
            }
        }
        ),
        this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, PointerEventTypes.POINTERDOWN | PointerEventTypes.POINTERUP | PointerEventTypes.POINTERMOVE),
        this._onLostFocus) {
            var n = this.camera.getEngine()
              , o = n.getInputElement();
            o && o.addEventListener("blur", this._onLostFocus)
        }
    }
    ,
    i.prototype.detachControl = function(e) {
        if (this._pointerInput) {
            if (this._observer && (this.camera.getScene().onPointerObservable.remove(this._observer),
            this._observer = null),
            this._onLostFocus) {
                var t = this.camera.getEngine()
                  , r = t.getInputElement();
                r && r.removeEventListener("blur", this._onLostFocus),
                this._onLostFocus = null
            }
            this._pointerPressed = [],
            this._offsetX = null,
            this._offsetY = null
        }
    }
    ,
    i.prototype.checkInputs = function() {
        if (!(this._offsetX === null || this._offsetY === null) && !(this._offsetX === 0 && this._offsetY === 0)) {
            var e = this.camera;
            e.cameraRotation.y = this._offsetX / this.touchAngularSensibility;
            var t = this.singleFingerRotate && this._pointerPressed.length === 1 || !this.singleFingerRotate && this._pointerPressed.length > 1;
            if (t)
                e.cameraRotation.x = -this._offsetY / this.touchAngularSensibility;
            else {
                var r = e._computeLocalCameraSpeed()
                  , n = new Vector3(0,0,r * this._offsetY / this.touchMoveSensibility);
                Matrix.RotationYawPitchRollToRef(e.rotation.y, e.rotation.x, 0, e._cameraRotationMatrix),
                e.cameraDirection.addInPlace(Vector3.TransformCoordinates(n, e._cameraRotationMatrix))
            }
        }
    }
    ,
    i.prototype.getClassName = function() {
        return "FreeCameraTouchInput"
    }
    ,
    i.prototype.getSimpleName = function() {
        return "touch"
    }
    ,
    __decorate([serialize()], i.prototype, "touchAngularSensibility", void 0),
    __decorate([serialize()], i.prototype, "touchMoveSensibility", void 0),
    i
}();
CameraInputTypes.FreeCameraTouchInput = FreeCameraTouchInput;
var FreeCameraInputsManager = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t) || this;
        return r._mouseInput = null,
        r._mouseWheelInput = null,
        r
    }
    return e.prototype.addKeyboard = function() {
        return this.add(new FreeCameraKeyboardMoveInput),
        this
    }
    ,
    e.prototype.addMouse = function(t) {
        return t === void 0 && (t = !0),
        this._mouseInput || (this._mouseInput = new FreeCameraMouseInput(t),
        this.add(this._mouseInput)),
        this
    }
    ,
    e.prototype.removeMouse = function() {
        return this._mouseInput && this.remove(this._mouseInput),
        this
    }
    ,
    e.prototype.addMouseWheel = function() {
        return this._mouseWheelInput || (this._mouseWheelInput = new FreeCameraMouseWheelInput,
        this.add(this._mouseWheelInput)),
        this
    }
    ,
    e.prototype.removeMouseWheel = function() {
        return this._mouseWheelInput && this.remove(this._mouseWheelInput),
        this
    }
    ,
    e.prototype.addTouch = function() {
        return this.add(new FreeCameraTouchInput),
        this
    }
    ,
    e.prototype.clear = function() {
        i.prototype.clear.call(this),
        this._mouseInput = null
    }
    ,
    e
}(CameraInputsManager)
  , FreeCamera = function(i) {
    __extends(e, i);
    function e(t, r, n, o) {
        o === void 0 && (o = !0);
        var a = i.call(this, t, r, n, o) || this;
        return a.ellipsoid = new Vector3(.5,1,.5),
        a.ellipsoidOffset = new Vector3(0,0,0),
        a.checkCollisions = !1,
        a.applyGravity = !1,
        a._needMoveForGravity = !1,
        a._oldPosition = Vector3.Zero(),
        a._diffPosition = Vector3.Zero(),
        a._newPosition = Vector3.Zero(),
        a._collisionMask = -1,
        a._onCollisionPositionChange = function(s, l, u) {
            u === void 0 && (u = null);
            var c = function(h) {
                a._newPosition.copyFrom(h),
                a._newPosition.subtractToRef(a._oldPosition, a._diffPosition),
                a._diffPosition.length() > Engine.CollisionsEpsilon && (a.position.addInPlace(a._diffPosition),
                a.onCollide && u && a.onCollide(u))
            };
            c(l)
        }
        ,
        a.inputs = new FreeCameraInputsManager(a),
        a.inputs.addKeyboard().addMouse(),
        a
    }
    return Object.defineProperty(e.prototype, "angularSensibility", {
        get: function() {
            var t = this.inputs.attached.mouse;
            return t ? t.angularSensibility : 0
        },
        set: function(t) {
            var r = this.inputs.attached.mouse;
            r && (r.angularSensibility = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "keysUp", {
        get: function() {
            var t = this.inputs.attached.keyboard;
            return t ? t.keysUp : []
        },
        set: function(t) {
            var r = this.inputs.attached.keyboard;
            r && (r.keysUp = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "keysUpward", {
        get: function() {
            var t = this.inputs.attached.keyboard;
            return t ? t.keysUpward : []
        },
        set: function(t) {
            var r = this.inputs.attached.keyboard;
            r && (r.keysUpward = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "keysDown", {
        get: function() {
            var t = this.inputs.attached.keyboard;
            return t ? t.keysDown : []
        },
        set: function(t) {
            var r = this.inputs.attached.keyboard;
            r && (r.keysDown = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "keysDownward", {
        get: function() {
            var t = this.inputs.attached.keyboard;
            return t ? t.keysDownward : []
        },
        set: function(t) {
            var r = this.inputs.attached.keyboard;
            r && (r.keysDownward = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "keysLeft", {
        get: function() {
            var t = this.inputs.attached.keyboard;
            return t ? t.keysLeft : []
        },
        set: function(t) {
            var r = this.inputs.attached.keyboard;
            r && (r.keysLeft = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "keysRight", {
        get: function() {
            var t = this.inputs.attached.keyboard;
            return t ? t.keysRight : []
        },
        set: function(t) {
            var r = this.inputs.attached.keyboard;
            r && (r.keysRight = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "keysRotateLeft", {
        get: function() {
            var t = this.inputs.attached.keyboard;
            return t ? t.keysRotateLeft : []
        },
        set: function(t) {
            var r = this.inputs.attached.keyboard;
            r && (r.keysRotateLeft = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "keysRotateRight", {
        get: function() {
            var t = this.inputs.attached.keyboard;
            return t ? t.keysRotateRight : []
        },
        set: function(t) {
            var r = this.inputs.attached.keyboard;
            r && (r.keysRotateRight = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.attachControl = function(t, r) {
        r = Tools.BackCompatCameraNoPreventDefault(arguments),
        this.inputs.attachElement(r)
    }
    ,
    e.prototype.detachControl = function(t) {
        this.inputs.detachElement(),
        this.cameraDirection = new Vector3(0,0,0),
        this.cameraRotation = new Vector2(0,0)
    }
    ,
    Object.defineProperty(e.prototype, "collisionMask", {
        get: function() {
            return this._collisionMask
        },
        set: function(t) {
            this._collisionMask = isNaN(t) ? -1 : t
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._collideWithWorld = function(t) {
        var r;
        this.parent ? r = Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix()) : r = this.position,
        r.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition),
        this._oldPosition.addInPlace(this.ellipsoidOffset);
        var n = this.getScene().collisionCoordinator;
        this._collider || (this._collider = n.createCollider()),
        this._collider._radius = this.ellipsoid,
        this._collider.collisionMask = this._collisionMask;
        var o = t;
        this.applyGravity && (o = t.add(this.getScene().gravity)),
        n.getNewPosition(this._oldPosition, o, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId)
    }
    ,
    e.prototype._checkInputs = function() {
        this._localDirection || (this._localDirection = Vector3.Zero(),
        this._transformedDirection = Vector3.Zero()),
        this.inputs.checkInputs(),
        i.prototype._checkInputs.call(this)
    }
    ,
    e.prototype._decideIfNeedsToMove = function() {
        return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0
    }
    ,
    e.prototype._updatePosition = function() {
        this.checkCollisions && this.getScene().collisionsEnabled ? this._collideWithWorld(this.cameraDirection) : i.prototype._updatePosition.call(this)
    }
    ,
    e.prototype.dispose = function() {
        this.inputs.clear(),
        i.prototype.dispose.call(this)
    }
    ,
    e.prototype.getClassName = function() {
        return "FreeCamera"
    }
    ,
    __decorate([serializeAsVector3()], e.prototype, "ellipsoid", void 0),
    __decorate([serializeAsVector3()], e.prototype, "ellipsoidOffset", void 0),
    __decorate([serialize()], e.prototype, "checkCollisions", void 0),
    __decorate([serialize()], e.prototype, "applyGravity", void 0),
    e
}(TargetCamera)
  , ShadowLight = function(i) {
    __extends(e, i);
    function e() {
        var t = i !== null && i.apply(this, arguments) || this;
        return t._needProjectionMatrixCompute = !0,
        t
    }
    return e.prototype._setPosition = function(t) {
        this._position = t
    }
    ,
    Object.defineProperty(e.prototype, "position", {
        get: function() {
            return this._position
        },
        set: function(t) {
            this._setPosition(t)
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._setDirection = function(t) {
        this._direction = t
    }
    ,
    Object.defineProperty(e.prototype, "direction", {
        get: function() {
            return this._direction
        },
        set: function(t) {
            this._setDirection(t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "shadowMinZ", {
        get: function() {
            return this._shadowMinZ
        },
        set: function(t) {
            this._shadowMinZ = t,
            this.forceProjectionMatrixCompute()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "shadowMaxZ", {
        get: function() {
            return this._shadowMaxZ
        },
        set: function(t) {
            this._shadowMaxZ = t,
            this.forceProjectionMatrixCompute()
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.computeTransformedInformation = function() {
        return this.parent && this.parent.getWorldMatrix ? (this.transformedPosition || (this.transformedPosition = Vector3.Zero()),
        Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition),
        this.direction && (this.transformedDirection || (this.transformedDirection = Vector3.Zero()),
        Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection)),
        !0) : !1
    }
    ,
    e.prototype.getDepthScale = function() {
        return 50
    }
    ,
    e.prototype.getShadowDirection = function(t) {
        return this.transformedDirection ? this.transformedDirection : this.direction
    }
    ,
    e.prototype.getAbsolutePosition = function() {
        return this.transformedPosition ? this.transformedPosition : this.position
    }
    ,
    e.prototype.setDirectionToTarget = function(t) {
        return this.direction = Vector3.Normalize(t.subtract(this.position)),
        this.direction
    }
    ,
    e.prototype.getRotation = function() {
        this.direction.normalize();
        var t = Vector3.Cross(this.direction, Axis.Y)
          , r = Vector3.Cross(t, this.direction);
        return Vector3.RotationFromAxis(t, r, this.direction)
    }
    ,
    e.prototype.needCube = function() {
        return !1
    }
    ,
    e.prototype.needProjectionMatrixCompute = function() {
        return this._needProjectionMatrixCompute
    }
    ,
    e.prototype.forceProjectionMatrixCompute = function() {
        this._needProjectionMatrixCompute = !0
    }
    ,
    e.prototype._initCache = function() {
        i.prototype._initCache.call(this),
        this._cache.position = Vector3.Zero()
    }
    ,
    e.prototype._isSynchronized = function() {
        return !!this._cache.position.equals(this.position)
    }
    ,
    e.prototype.computeWorldMatrix = function(t) {
        return !t && this.isSynchronized() ? (this._currentRenderId = this.getScene().getRenderId(),
        this._worldMatrix) : (this._updateCache(),
        this._cache.position.copyFrom(this.position),
        this._worldMatrix || (this._worldMatrix = Matrix.Identity()),
        Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix),
        this.parent && this.parent.getWorldMatrix && (this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix),
        this._markSyncedWithParent()),
        this._worldMatrixDeterminantIsDirty = !0,
        this._worldMatrix)
    }
    ,
    e.prototype.getDepthMinZ = function(t) {
        return this.shadowMinZ !== void 0 ? this.shadowMinZ : t.minZ
    }
    ,
    e.prototype.getDepthMaxZ = function(t) {
        return this.shadowMaxZ !== void 0 ? this.shadowMaxZ : t.maxZ
    }
    ,
    e.prototype.setShadowProjectionMatrix = function(t, r, n) {
        return this.customProjectionMatrixBuilder ? this.customProjectionMatrixBuilder(r, n, t) : this._setDefaultShadowProjectionMatrix(t, r, n),
        this
    }
    ,
    __decorate([serializeAsVector3()], e.prototype, "position", null),
    __decorate([serializeAsVector3()], e.prototype, "direction", null),
    __decorate([serialize()], e.prototype, "shadowMinZ", null),
    __decorate([serialize()], e.prototype, "shadowMaxZ", null),
    e
}(Light);
Node$2.AddNodeConstructor("Light_Type_1", function(i, e) {
    return function() {
        return new DirectionalLight(i,Vector3.Zero(),e)
    }
});
var DirectionalLight = function(i) {
    __extends(e, i);
    function e(t, r, n) {
        var o = i.call(this, t, n) || this;
        return o._shadowFrustumSize = 0,
        o._shadowOrthoScale = .1,
        o.autoUpdateExtends = !0,
        o.autoCalcShadowZBounds = !1,
        o._orthoLeft = Number.MAX_VALUE,
        o._orthoRight = Number.MIN_VALUE,
        o._orthoTop = Number.MIN_VALUE,
        o._orthoBottom = Number.MAX_VALUE,
        o.position = r.scale(-1),
        o.direction = r,
        o
    }
    return Object.defineProperty(e.prototype, "shadowFrustumSize", {
        get: function() {
            return this._shadowFrustumSize
        },
        set: function(t) {
            this._shadowFrustumSize = t,
            this.forceProjectionMatrixCompute()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "shadowOrthoScale", {
        get: function() {
            return this._shadowOrthoScale
        },
        set: function(t) {
            this._shadowOrthoScale = t,
            this.forceProjectionMatrixCompute()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "orthoLeft", {
        get: function() {
            return this._orthoLeft
        },
        set: function(t) {
            this._orthoLeft = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "orthoRight", {
        get: function() {
            return this._orthoRight
        },
        set: function(t) {
            this._orthoRight = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "orthoTop", {
        get: function() {
            return this._orthoTop
        },
        set: function(t) {
            this._orthoTop = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "orthoBottom", {
        get: function() {
            return this._orthoBottom
        },
        set: function(t) {
            this._orthoBottom = t
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getClassName = function() {
        return "DirectionalLight"
    }
    ,
    e.prototype.getTypeID = function() {
        return Light.LIGHTTYPEID_DIRECTIONALLIGHT
    }
    ,
    e.prototype._setDefaultShadowProjectionMatrix = function(t, r, n) {
        this.shadowFrustumSize > 0 ? this._setDefaultFixedFrustumShadowProjectionMatrix(t) : this._setDefaultAutoExtendShadowProjectionMatrix(t, r, n)
    }
    ,
    e.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function(t) {
        var r = this.getScene().activeCamera;
        !r || Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== void 0 ? this.shadowMinZ : r.minZ, this.shadowMaxZ !== void 0 ? this.shadowMaxZ : r.maxZ, t, this.getScene().getEngine().isNDCHalfZRange)
    }
    ,
    e.prototype._setDefaultAutoExtendShadowProjectionMatrix = function(t, r, n) {
        var o = this.getScene().activeCamera;
        if (!!o) {
            if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
                var a = Vector3.Zero();
                this._orthoLeft = Number.MAX_VALUE,
                this._orthoRight = Number.MIN_VALUE,
                this._orthoTop = Number.MIN_VALUE,
                this._orthoBottom = Number.MAX_VALUE;
                for (var s = Number.MAX_VALUE, l = Number.MIN_VALUE, u = 0; u < n.length; u++) {
                    var c = n[u];
                    if (!!c)
                        for (var h = c.getBoundingInfo(), f = h.boundingBox, d = 0; d < f.vectorsWorld.length; d++)
                            Vector3.TransformCoordinatesToRef(f.vectorsWorld[d], r, a),
                            a.x < this._orthoLeft && (this._orthoLeft = a.x),
                            a.y < this._orthoBottom && (this._orthoBottom = a.y),
                            a.x > this._orthoRight && (this._orthoRight = a.x),
                            a.y > this._orthoTop && (this._orthoTop = a.y),
                            this.autoCalcShadowZBounds && (a.z < s && (s = a.z),
                            a.z > l && (l = a.z))
                }
                this.autoCalcShadowZBounds && (this._shadowMinZ = s,
                this._shadowMaxZ = l)
            }
            var _ = this._orthoRight - this._orthoLeft
              , g = this._orthoTop - this._orthoBottom
              , m = this.shadowMinZ !== void 0 ? this.shadowMinZ : o.minZ
              , v = this.shadowMaxZ !== void 0 ? this.shadowMaxZ : o.maxZ
              , y = this.getScene().getEngine().useReverseDepthBuffer;
            Matrix.OrthoOffCenterLHToRef(this._orthoLeft - _ * this.shadowOrthoScale, this._orthoRight + _ * this.shadowOrthoScale, this._orthoBottom - g * this.shadowOrthoScale, this._orthoTop + g * this.shadowOrthoScale, y ? v : m, y ? m : v, t, this.getScene().getEngine().isNDCHalfZRange)
        }
    }
    ,
    e.prototype._buildUniformLayout = function() {
        this._uniformBuffer.addUniform("vLightData", 4),
        this._uniformBuffer.addUniform("vLightDiffuse", 4),
        this._uniformBuffer.addUniform("vLightSpecular", 4),
        this._uniformBuffer.addUniform("shadowsInfo", 3),
        this._uniformBuffer.addUniform("depthValues", 2),
        this._uniformBuffer.create()
    }
    ,
    e.prototype.transferToEffect = function(t, r) {
        return this.computeTransformedInformation() ? (this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, r),
        this) : (this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, r),
        this)
    }
    ,
    e.prototype.transferToNodeMaterialEffect = function(t, r) {
        return this.computeTransformedInformation() ? (t.setFloat3(r, this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z),
        this) : (t.setFloat3(r, this.direction.x, this.direction.y, this.direction.z),
        this)
    }
    ,
    e.prototype.getDepthMinZ = function(t) {
        var r = this._scene.getEngine();
        return !r.useReverseDepthBuffer && r.isNDCHalfZRange ? 0 : 1
    }
    ,
    e.prototype.getDepthMaxZ = function(t) {
        var r = this._scene.getEngine();
        return r.useReverseDepthBuffer && r.isNDCHalfZRange ? 0 : 1
    }
    ,
    e.prototype.prepareLightSpecificDefines = function(t, r) {
        t["DIRLIGHT" + r] = !0
    }
    ,
    __decorate([serialize()], e.prototype, "shadowFrustumSize", null),
    __decorate([serialize()], e.prototype, "shadowOrthoScale", null),
    __decorate([serialize()], e.prototype, "autoUpdateExtends", void 0),
    __decorate([serialize()], e.prototype, "autoCalcShadowZBounds", void 0),
    __decorate([serialize("orthoLeft")], e.prototype, "_orthoLeft", void 0),
    __decorate([serialize("orthoRight")], e.prototype, "_orthoRight", void 0),
    __decorate([serialize("orthoTop")], e.prototype, "_orthoTop", void 0),
    __decorate([serialize("orthoBottom")], e.prototype, "_orthoBottom", void 0),
    e
}(ShadowLight);
Node$2.AddNodeConstructor("Light_Type_3", function(i, e) {
    return function() {
        return new HemisphericLight(i,Vector3.Zero(),e)
    }
});
var HemisphericLight = function(i) {
    __extends(e, i);
    function e(t, r, n) {
        var o = i.call(this, t, n) || this;
        return o.groundColor = new Color3(0,0,0),
        o.direction = r || Vector3.Up(),
        o
    }
    return e.prototype._buildUniformLayout = function() {
        this._uniformBuffer.addUniform("vLightData", 4),
        this._uniformBuffer.addUniform("vLightDiffuse", 4),
        this._uniformBuffer.addUniform("vLightSpecular", 4),
        this._uniformBuffer.addUniform("vLightGround", 3),
        this._uniformBuffer.addUniform("shadowsInfo", 3),
        this._uniformBuffer.addUniform("depthValues", 2),
        this._uniformBuffer.create()
    }
    ,
    e.prototype.getClassName = function() {
        return "HemisphericLight"
    }
    ,
    e.prototype.setDirectionToTarget = function(t) {
        return this.direction = Vector3.Normalize(t.subtract(Vector3.Zero())),
        this.direction
    }
    ,
    e.prototype.getShadowGenerator = function() {
        return null
    }
    ,
    e.prototype.transferToEffect = function(t, r) {
        var n = Vector3.Normalize(this.direction);
        return this._uniformBuffer.updateFloat4("vLightData", n.x, n.y, n.z, 0, r),
        this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), r),
        this
    }
    ,
    e.prototype.transferToNodeMaterialEffect = function(t, r) {
        var n = Vector3.Normalize(this.direction);
        return t.setFloat3(r, n.x, n.y, n.z),
        this
    }
    ,
    e.prototype.computeWorldMatrix = function() {
        return this._worldMatrix || (this._worldMatrix = Matrix.Identity()),
        this._worldMatrix
    }
    ,
    e.prototype.getTypeID = function() {
        return Light.LIGHTTYPEID_HEMISPHERICLIGHT
    }
    ,
    e.prototype.prepareLightSpecificDefines = function(t, r) {
        t["HEMILIGHT" + r] = !0
    }
    ,
    __decorate([serializeAsColor3()], e.prototype, "groundColor", void 0),
    __decorate([serializeAsVector3()], e.prototype, "direction", void 0),
    e
}(Light)
  , RenderTargetWrapper = function() {
    function i(e, t, r, n) {
        this._textures = null,
        this._attachments = null,
        this._generateStencilBuffer = !1,
        this._generateDepthBuffer = !1,
        this._depthStencilTextureWithStencil = !1,
        this._isMulti = e,
        this._isCube = t,
        this._size = r,
        this._engine = n,
        this._depthStencilTexture = null
    }
    return Object.defineProperty(i.prototype, "isCube", {
        get: function() {
            return this._isCube
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "isMulti", {
        get: function() {
            return this._isMulti
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "is2DArray", {
        get: function() {
            return this.layers > 0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "size", {
        get: function() {
            return this.width
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "width", {
        get: function() {
            return this._size.width || this._size
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "height", {
        get: function() {
            return this._size.height || this._size
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "layers", {
        get: function() {
            return this._size.layers || 0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "texture", {
        get: function() {
            var e, t;
            return (t = (e = this._textures) === null || e === void 0 ? void 0 : e[0]) !== null && t !== void 0 ? t : null
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "textures", {
        get: function() {
            return this._textures
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "samples", {
        get: function() {
            var e, t;
            return (t = (e = this.texture) === null || e === void 0 ? void 0 : e.samples) !== null && t !== void 0 ? t : 1
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.setSamples = function(e, t, r) {
        return t === void 0 && (t = !0),
        r === void 0 && (r = !1),
        this.samples === e && !r ? e : this._isMulti ? this._engine.updateMultipleRenderTargetTextureSampleCount(this, e, t) : this._engine.updateRenderTargetTextureSampleCount(this, e)
    }
    ,
    i.prototype.setTextures = function(e) {
        Array.isArray(e) ? this._textures = e : e ? this._textures = [e] : this._textures = null
    }
    ,
    i.prototype.setTexture = function(e, t, r) {
        t === void 0 && (t = 0),
        r === void 0 && (r = !0),
        this._textures || (this._textures = []),
        this._textures[t] && r && this._textures[t].dispose(),
        this._textures[t] = e
    }
    ,
    i.prototype.createDepthStencilTexture = function(e, t, r, n, o) {
        var a;
        return e === void 0 && (e = 0),
        t === void 0 && (t = !0),
        r === void 0 && (r = !1),
        n === void 0 && (n = 1),
        o === void 0 && (o = 15),
        (a = this._depthStencilTexture) === null || a === void 0 || a.dispose(),
        this._depthStencilTextureWithStencil = r,
        this._depthStencilTexture = this._engine.createDepthStencilTexture(this._size, {
            bilinearFiltering: t,
            comparisonFunction: e,
            generateStencil: r,
            isCube: this._isCube,
            samples: n,
            depthTextureFormat: o
        }, this),
        this._depthStencilTexture
    }
    ,
    i.prototype._shareDepth = function(e) {
        this._depthStencilTexture && (e._depthStencilTexture && e._depthStencilTexture.dispose(),
        e._depthStencilTexture = this._depthStencilTexture,
        this._depthStencilTexture.incrementReferences())
    }
    ,
    i.prototype._swapAndDie = function(e) {
        this.texture && this.texture._swapAndDie(e),
        this._textures = null,
        this.dispose(!0)
    }
    ,
    i.prototype._cloneRenderTargetWrapper = function() {
        var e, t, r, n, o, a, s = null;
        if (this._isMulti) {
            var l = this.textures;
            if (l && l.length > 0) {
                var u = !1
                  , c = l.length
                  , h = l[l.length - 1]._source;
                (h === InternalTextureSource.Depth || h === InternalTextureSource.DepthStencil) && (u = !0,
                c--);
                for (var f = [], d = [], _ = 0; _ < c; ++_) {
                    var g = l[_];
                    f.push(g.samplingMode),
                    d.push(g.type)
                }
                var m = {
                    samplingModes: f,
                    generateMipMaps: l[0].generateMipMaps,
                    generateDepthBuffer: this._generateDepthBuffer,
                    generateStencilBuffer: this._generateStencilBuffer,
                    generateDepthTexture: u,
                    types: d,
                    textureCount: c
                }
                  , v = {
                    width: this.width,
                    height: this.height
                };
                s = this._engine.createMultipleRenderTarget(v, m)
            }
        } else {
            var y = {};
            if (y.generateDepthBuffer = this._generateDepthBuffer,
            y.generateMipMaps = (t = (e = this.texture) === null || e === void 0 ? void 0 : e.generateMipMaps) !== null && t !== void 0 ? t : !1,
            y.generateStencilBuffer = this._generateStencilBuffer,
            y.samplingMode = (r = this.texture) === null || r === void 0 ? void 0 : r.samplingMode,
            y.type = (n = this.texture) === null || n === void 0 ? void 0 : n.type,
            y.format = (o = this.texture) === null || o === void 0 ? void 0 : o.format,
            this.isCube)
                s = this._engine.createRenderTargetCubeTexture(this.width, y);
            else {
                var v = {
                    width: this.width,
                    height: this.height,
                    layers: this.is2DArray ? (a = this.texture) === null || a === void 0 ? void 0 : a.depth : void 0
                };
                s = this._engine.createRenderTargetTexture(v, y)
            }
            s.texture.isReady = !0
        }
        return s
    }
    ,
    i.prototype._swapRenderTargetWrapper = function(e) {
        if (this._textures && e._textures)
            for (var t = 0; t < this._textures.length; ++t)
                this._textures[t]._swapAndDie(e._textures[t], !1),
                e._textures[t].isReady = !0;
        this._depthStencilTexture && e._depthStencilTexture && (this._depthStencilTexture._swapAndDie(e._depthStencilTexture),
        e._depthStencilTexture.isReady = !0),
        this._textures = null,
        this._depthStencilTexture = null
    }
    ,
    i.prototype._rebuild = function() {
        var e = this._cloneRenderTargetWrapper();
        if (!!e) {
            if (this._depthStencilTexture) {
                var t = this._depthStencilTexture.samplingMode
                  , r = t === 2 || t === 3 || t === 11;
                e.createDepthStencilTexture(this._depthStencilTexture._comparisonFunction, r, this._depthStencilTextureWithStencil, this._depthStencilTexture.samples)
            }
            this.samples > 1 && e.setSamples(this.samples),
            e._swapRenderTargetWrapper(this),
            e.dispose()
        }
    }
    ,
    i.prototype.releaseTextures = function() {
        var e, t;
        if (this._textures)
            for (var r = 0; (t = r < ((e = this._textures) === null || e === void 0 ? void 0 : e.length)) !== null && t !== void 0 && t; ++r)
                this._textures[r].dispose();
        this._textures = null
    }
    ,
    i.prototype.dispose = function(e) {
        var t;
        e === void 0 && (e = !1),
        e || ((t = this._depthStencilTexture) === null || t === void 0 || t.dispose(),
        this._depthStencilTexture = null,
        this.releaseTextures()),
        this._engine._releaseRenderTargetWrapper(this)
    }
    ,
    i
}()
  , WebGLRenderTargetWrapper = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a) {
        var s = i.call(this, t, r, n, o) || this;
        return s._framebuffer = null,
        s._depthStencilBuffer = null,
        s._MSAAFramebuffer = null,
        s._colorTextureArray = null,
        s._depthStencilTextureArray = null,
        s._context = a,
        s
    }
    return e.prototype._cloneRenderTargetWrapper = function() {
        var t = null;
        return this._colorTextureArray && this._depthStencilTextureArray ? (t = this._engine.createMultiviewRenderTargetTexture(this.width, this.height),
        t.texture.isReady = !0) : t = i.prototype._cloneRenderTargetWrapper.call(this),
        t
    }
    ,
    e.prototype._swapRenderTargetWrapper = function(t) {
        i.prototype._swapRenderTargetWrapper.call(this, t),
        t._framebuffer = this._framebuffer,
        t._depthStencilBuffer = this._depthStencilBuffer,
        t._MSAAFramebuffer = this._MSAAFramebuffer,
        t._colorTextureArray = this._colorTextureArray,
        t._depthStencilTextureArray = this._depthStencilTextureArray,
        this._framebuffer = this._depthStencilBuffer = this._MSAAFramebuffer = this._colorTextureArray = this._depthStencilTextureArray = null
    }
    ,
    e.prototype._shareDepth = function(t) {
        i.prototype._shareDepth.call(this, t);
        var r = this._context
          , n = this._depthStencilBuffer
          , o = t._framebuffer;
        t._depthStencilBuffer && r.deleteRenderbuffer(t._depthStencilBuffer),
        t._depthStencilBuffer = this._depthStencilBuffer,
        this._engine._bindUnboundFramebuffer(o),
        r.framebufferRenderbuffer(r.FRAMEBUFFER, r.DEPTH_ATTACHMENT, r.RENDERBUFFER, n),
        this._engine._bindUnboundFramebuffer(null)
    }
    ,
    e.prototype._bindTextureRenderTarget = function(t, r, n, o) {
        if (r === void 0 && (r = 0),
        n === void 0 && (n = -1),
        o === void 0 && (o = 0),
        !!t._hardwareTexture) {
            var a = this._context
              , s = this._framebuffer
              , l = this._engine._currentFramebuffer;
            this._engine._bindUnboundFramebuffer(s);
            var u = a[this._engine.webGLVersion > 1 ? "COLOR_ATTACHMENT" + r : "COLOR_ATTACHMENT" + r + "_WEBGL"]
              , c = n !== -1 ? a.TEXTURE_CUBE_MAP_POSITIVE_X + n : a.TEXTURE_2D;
            a.framebufferTexture2D(a.FRAMEBUFFER, u, c, t._hardwareTexture.underlyingResource, o),
            this._engine._bindUnboundFramebuffer(l)
        }
    }
    ,
    e.prototype.setTexture = function(t, r, n) {
        r === void 0 && (r = 0),
        n === void 0 && (n = !0),
        i.prototype.setTexture.call(this, t, r, n),
        this._bindTextureRenderTarget(t, r)
    }
    ,
    e.prototype.dispose = function(t) {
        t === void 0 && (t = !1);
        var r = this._context;
        t || (this._colorTextureArray && (this._context.deleteTexture(this._colorTextureArray),
        this._colorTextureArray = null),
        this._depthStencilTextureArray && (this._context.deleteTexture(this._depthStencilTextureArray),
        this._depthStencilTextureArray = null)),
        this._framebuffer && (r.deleteFramebuffer(this._framebuffer),
        this._framebuffer = null),
        this._depthStencilBuffer && (r.deleteRenderbuffer(this._depthStencilBuffer),
        this._depthStencilBuffer = null),
        this._MSAAFramebuffer && (r.deleteFramebuffer(this._MSAAFramebuffer),
        this._MSAAFramebuffer = null),
        i.prototype.dispose.call(this, t)
    }
    ,
    e
}(RenderTargetWrapper);
ThinEngine.prototype._createHardwareRenderTargetWrapper = function(i, e, t) {
    var r = new WebGLRenderTargetWrapper(i,e,t,this,this._gl);
    return this._renderTargetWrapperCache.push(r),
    r
}
;
ThinEngine.prototype.createRenderTargetTexture = function(i, e) {
    var t = this._createHardwareRenderTargetWrapper(!1, !1, i)
      , r = {};
    e !== void 0 && typeof e == "object" ? (r.generateDepthBuffer = !!e.generateDepthBuffer,
    r.generateStencilBuffer = !!e.generateStencilBuffer) : (r.generateDepthBuffer = !0,
    r.generateStencilBuffer = !1);
    var n = this._createInternalTexture(i, e, !0, InternalTextureSource.RenderTarget)
      , o = i.width || i
      , a = i.height || i
      , s = this._currentFramebuffer
      , l = this._gl
      , u = l.createFramebuffer();
    return this._bindUnboundFramebuffer(u),
    t._depthStencilBuffer = this._setupFramebufferDepthAttachments(!!r.generateStencilBuffer, r.generateDepthBuffer, o, a),
    n.is2DArray || l.framebufferTexture2D(l.FRAMEBUFFER, l.COLOR_ATTACHMENT0, l.TEXTURE_2D, n._hardwareTexture.underlyingResource, 0),
    this._bindUnboundFramebuffer(s),
    t._framebuffer = u,
    t._generateDepthBuffer = r.generateDepthBuffer,
    t._generateStencilBuffer = !!r.generateStencilBuffer,
    t.setTextures(n),
    t
}
;
ThinEngine.prototype.createDepthStencilTexture = function(i, e, t) {
    if (e.isCube) {
        var r = i.width || i;
        return this._createDepthStencilCubeTexture(r, e, t)
    } else
        return this._createDepthStencilTexture(i, e, t)
}
;
ThinEngine.prototype._createDepthStencilTexture = function(i, e, t) {
    var r = this._gl
      , n = i.layers || 0
      , o = n !== 0 ? r.TEXTURE_2D_ARRAY : r.TEXTURE_2D
      , a = new InternalTexture(this,InternalTextureSource.DepthStencil);
    if (!this._caps.depthTextureExtension)
        return Logger$2.Error("Depth texture is not supported by your browser or hardware."),
        a;
    var s = __assign({
        bilinearFiltering: !1,
        comparisonFunction: 0,
        generateStencil: !1
    }, e);
    this._bindTextureDirectly(o, a, !0),
    this._setupDepthStencilTexture(a, i, s.generateStencil, s.comparisonFunction === 0 ? !1 : s.bilinearFiltering, s.comparisonFunction),
    t._depthStencilTexture = a,
    t._depthStencilTextureWithStencil = s.generateStencil;
    var l = s.generateStencil ? r.UNSIGNED_INT_24_8 : r.UNSIGNED_INT
      , u = s.generateStencil ? r.DEPTH_STENCIL : r.DEPTH_COMPONENT
      , c = u;
    return this.webGLVersion > 1 && (c = s.generateStencil ? r.DEPTH24_STENCIL8 : r.DEPTH_COMPONENT24),
    a.is2DArray ? r.texImage3D(o, 0, c, a.width, a.height, n, 0, u, l, null) : r.texImage2D(o, 0, c, a.width, a.height, 0, u, l, null),
    this._bindTextureDirectly(o, null),
    this._internalTexturesCache.push(a),
    a
}
;
ThinEngine.prototype.updateRenderTargetTextureSampleCount = function(i, e) {
    if (this.webGLVersion < 2 || !i || !i.texture)
        return 1;
    if (i.samples === e)
        return e;
    var t = this._gl;
    e = Math.min(e, this.getCaps().maxMSAASamples),
    i._depthStencilBuffer && (t.deleteRenderbuffer(i._depthStencilBuffer),
    i._depthStencilBuffer = null),
    i._MSAAFramebuffer && (t.deleteFramebuffer(i._MSAAFramebuffer),
    i._MSAAFramebuffer = null);
    var r = i.texture._hardwareTexture;
    if (r._MSAARenderBuffer && (t.deleteRenderbuffer(r._MSAARenderBuffer),
    r._MSAARenderBuffer = null),
    e > 1 && t.renderbufferStorageMultisample) {
        var n = t.createFramebuffer();
        if (!n)
            throw new Error("Unable to create multi sampled framebuffer");
        i._MSAAFramebuffer = n,
        this._bindUnboundFramebuffer(i._MSAAFramebuffer);
        var o = this._createRenderBuffer(i.texture.width, i.texture.height, e, -1, this._getRGBAMultiSampleBufferFormat(i.texture.type), t.COLOR_ATTACHMENT0, !1);
        if (!o)
            throw new Error("Unable to create multi sampled framebuffer");
        r._MSAARenderBuffer = o
    } else
        this._bindUnboundFramebuffer(i._framebuffer);
    return i.texture.samples = e,
    i._depthStencilBuffer = this._setupFramebufferDepthAttachments(i._generateStencilBuffer, i._generateDepthBuffer, i.texture.width, i.texture.height, e),
    this._bindUnboundFramebuffer(null),
    e
}
;
ThinEngine.prototype.createRenderTargetCubeTexture = function(i, e) {
    var t = this._createHardwareRenderTargetWrapper(!1, !0, i)
      , r = __assign({
        generateMipMaps: !0,
        generateDepthBuffer: !0,
        generateStencilBuffer: !1,
        type: 0,
        samplingMode: 3,
        format: 5
    }, e);
    r.generateStencilBuffer = r.generateDepthBuffer && r.generateStencilBuffer,
    (r.type === 1 && !this._caps.textureFloatLinearFiltering || r.type === 2 && !this._caps.textureHalfFloatLinearFiltering) && (r.samplingMode = 1);
    var n = this._gl
      , o = new InternalTexture(this,InternalTextureSource.RenderTarget);
    this._bindTextureDirectly(n.TEXTURE_CUBE_MAP, o, !0);
    var a = this._getSamplingParameters(r.samplingMode, r.generateMipMaps);
    r.type === 1 && !this._caps.textureFloat && (r.type = 0,
    Logger$2.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type")),
    n.texParameteri(n.TEXTURE_CUBE_MAP, n.TEXTURE_MAG_FILTER, a.mag),
    n.texParameteri(n.TEXTURE_CUBE_MAP, n.TEXTURE_MIN_FILTER, a.min),
    n.texParameteri(n.TEXTURE_CUBE_MAP, n.TEXTURE_WRAP_S, n.CLAMP_TO_EDGE),
    n.texParameteri(n.TEXTURE_CUBE_MAP, n.TEXTURE_WRAP_T, n.CLAMP_TO_EDGE);
    for (var s = 0; s < 6; s++)
        n.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X + s, 0, this._getRGBABufferInternalSizedFormat(r.type, r.format), i, i, 0, this._getInternalFormat(r.format), this._getWebGLTextureType(r.type), null);
    var l = n.createFramebuffer();
    return this._bindUnboundFramebuffer(l),
    t._depthStencilBuffer = this._setupFramebufferDepthAttachments(r.generateStencilBuffer, r.generateDepthBuffer, i, i),
    r.generateMipMaps && n.generateMipmap(n.TEXTURE_CUBE_MAP),
    this._bindTextureDirectly(n.TEXTURE_CUBE_MAP, null),
    this._bindUnboundFramebuffer(null),
    t._framebuffer = l,
    t._generateDepthBuffer = r.generateDepthBuffer,
    t._generateStencilBuffer = r.generateStencilBuffer,
    o.width = i,
    o.height = i,
    o.isReady = !0,
    o.isCube = !0,
    o.samples = 1,
    o.generateMipMaps = r.generateMipMaps,
    o.samplingMode = r.samplingMode,
    o.type = r.type,
    o.format = r.format,
    this._internalTexturesCache.push(o),
    t.setTextures(o),
    t
}
;
var RenderTargetTexture = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a, s, l, u, c, h, f, d, _, g, m) {
        a === void 0 && (a = !0),
        s === void 0 && (s = 0),
        l === void 0 && (l = !1),
        u === void 0 && (u = Texture.TRILINEAR_SAMPLINGMODE),
        c === void 0 && (c = !0),
        h === void 0 && (h = !1),
        f === void 0 && (f = !1),
        d === void 0 && (d = 5),
        _ === void 0 && (_ = !1);
        var v, y = i.call(this, null, n, !o, void 0, u, void 0, void 0, void 0, void 0, d) || this;
        if (y.renderParticles = !0,
        y.renderSprites = !1,
        y.ignoreCameraViewport = !1,
        y.onBeforeBindObservable = new Observable,
        y.onAfterUnbindObservable = new Observable,
        y.onBeforeRenderObservable = new Observable,
        y.onAfterRenderObservable = new Observable,
        y.onClearObservable = new Observable,
        y.onResizeObservable = new Observable,
        y._cleared = !1,
        y.skipInitialClear = !1,
        y._currentRefreshId = -1,
        y._refreshRate = 1,
        y._samples = 1,
        y._canRescale = !0,
        y._renderTarget = null,
        y.boundingBoxPosition = Vector3.Zero(),
        n = y.getScene(),
        !n)
            return y;
        var b = y.getScene().getEngine();
        return y._coordinatesMode = Texture.PROJECTION_MODE,
        y.renderList = new Array,
        y.name = t,
        y.isRenderTarget = !0,
        y._initialSizeParameter = r,
        y._renderPassIds = [],
        y.__isCube = l,
        y._processSizeParameter(r),
        y.renderPassId = y._renderPassIds[0],
        y._resizeObserver = b.onResizeObservable.add(function() {}),
        y._generateMipMaps = !!o,
        y._doNotChangeAspectRatio = a,
        y._renderingManager = new RenderingManager(n),
        y._renderingManager._useSceneAutoClearSetup = !0,
        f || (y._renderTargetOptions = {
            generateMipMaps: o,
            type: s,
            format: (v = y._format) !== null && v !== void 0 ? v : void 0,
            samplingMode: y.samplingMode,
            generateDepthBuffer: c,
            generateStencilBuffer: h,
            samples: g,
            creationFlags: m
        },
        y.samplingMode === Texture.NEAREST_SAMPLINGMODE && (y.wrapU = Texture.CLAMP_ADDRESSMODE,
        y.wrapV = Texture.CLAMP_ADDRESSMODE),
        _ || (l ? (y._renderTarget = n.getEngine().createRenderTargetCubeTexture(y.getRenderSize(), y._renderTargetOptions),
        y.coordinatesMode = Texture.INVCUBIC_MODE,
        y._textureMatrix = Matrix.Identity()) : y._renderTarget = n.getEngine().createRenderTargetTexture(y._size, y._renderTargetOptions),
        y._texture = y._renderTarget.texture,
        g !== void 0 && (y.samples = g))),
        y
    }
    return Object.defineProperty(e.prototype, "renderList", {
        get: function() {
            return this._renderList
        },
        set: function(t) {
            this._renderList = t,
            this._renderList && this._hookArray(this._renderList)
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._hookArray = function(t) {
        var r = this
          , n = t.push;
        t.push = function() {
            for (var a, s = [], l = 0; l < arguments.length; l++)
                s[l] = arguments[l];
            var u = t.length === 0
              , c = n.apply(t, s);
            return u && ((a = r.getScene()) === null || a === void 0 || a.meshes.forEach(function(h) {
                h._markSubMeshesAsLightDirty()
            })),
            c
        }
        ;
        var o = t.splice;
        t.splice = function(a, s) {
            var l, u = o.apply(t, [a, s]);
            return t.length === 0 && ((l = r.getScene()) === null || l === void 0 || l.meshes.forEach(function(c) {
                c._markSubMeshesAsLightDirty()
            })),
            u
        }
    }
    ,
    Object.defineProperty(e.prototype, "postProcesses", {
        get: function() {
            return this._postProcesses
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "_prePassEnabled", {
        get: function() {
            return !!this._prePassRenderTarget && this._prePassRenderTarget.enabled
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "onAfterUnbind", {
        set: function(t) {
            this._onAfterUnbindObserver && this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),
            this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "onBeforeRender", {
        set: function(t) {
            this._onBeforeRenderObserver && this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),
            this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "onAfterRender", {
        set: function(t) {
            this._onAfterRenderObserver && this.onAfterRenderObservable.remove(this._onAfterRenderObserver),
            this._onAfterRenderObserver = this.onAfterRenderObservable.add(t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "onClear", {
        set: function(t) {
            this._onClearObserver && this.onClearObservable.remove(this._onClearObserver),
            this._onClearObserver = this.onClearObservable.add(t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "renderPassIds", {
        get: function() {
            return this._renderPassIds
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.setMaterialForRendering = function(t, r) {
        var n;
        Array.isArray(t) ? n = t : n = [t];
        for (var o = 0; o < n.length; ++o)
            for (var a = 0; a < this._renderPassIds.length; ++a)
                n[o].setMaterialForRenderPass(this._renderPassIds[a], r !== void 0 ? Array.isArray(r) ? r[a] : r : void 0)
    }
    ,
    Object.defineProperty(e.prototype, "renderTargetOptions", {
        get: function() {
            return this._renderTargetOptions
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "renderTarget", {
        get: function() {
            return this._renderTarget
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._onRatioRescale = function() {
        this._sizeRatio && this.resize(this._initialSizeParameter)
    }
    ,
    Object.defineProperty(e.prototype, "boundingBoxSize", {
        get: function() {
            return this._boundingBoxSize
        },
        set: function(t) {
            if (!(this._boundingBoxSize && this._boundingBoxSize.equals(t))) {
                this._boundingBoxSize = t;
                var r = this.getScene();
                r && r.markAllMaterialsAsDirty(1)
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "depthStencilTexture", {
        get: function() {
            var t, r;
            return (r = (t = this._renderTarget) === null || t === void 0 ? void 0 : t._depthStencilTexture) !== null && r !== void 0 ? r : null
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.createDepthStencilTexture = function(t, r, n, o) {
        var a;
        t === void 0 && (t = 0),
        r === void 0 && (r = !0),
        n === void 0 && (n = !1),
        o === void 0 && (o = 1),
        (a = this._renderTarget) === null || a === void 0 || a.createDepthStencilTexture(t, r, n, o)
    }
    ,
    e.prototype._releaseRenderPassId = function() {
        if (this._scene)
            for (var t = this._scene.getEngine(), r = 0; r < this._renderPassIds.length; ++r)
                t.releaseRenderPassId(this._renderPassIds[r]);
        this._renderPassIds = []
    }
    ,
    e.prototype._createRenderPassId = function() {
        this._releaseRenderPassId();
        for (var t = this._scene.getEngine(), r = this.__isCube ? 6 : this.getRenderLayers() || 1, n = 0; n < r; ++n)
            this._renderPassIds[n] = t.createRenderPassId("RenderTargetTexture - " + this.name + "#" + n)
    }
    ,
    e.prototype._processSizeParameter = function(t) {
        if (t.ratio) {
            this._sizeRatio = t.ratio;
            var r = this._getEngine();
            this._size = {
                width: this._bestReflectionRenderTargetDimension(r.getRenderWidth(), this._sizeRatio),
                height: this._bestReflectionRenderTargetDimension(r.getRenderHeight(), this._sizeRatio)
            }
        } else
            this._size = t;
        this._createRenderPassId()
    }
    ,
    Object.defineProperty(e.prototype, "samples", {
        get: function() {
            var t, r;
            return (r = (t = this._renderTarget) === null || t === void 0 ? void 0 : t.samples) !== null && r !== void 0 ? r : this._samples
        },
        set: function(t) {
            this._renderTarget && (this._samples = this._renderTarget.setSamples(t))
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.resetRefreshCounter = function() {
        this._currentRefreshId = -1
    }
    ,
    Object.defineProperty(e.prototype, "refreshRate", {
        get: function() {
            return this._refreshRate
        },
        set: function(t) {
            this._refreshRate = t,
            this.resetRefreshCounter()
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.addPostProcess = function(t) {
        if (!this._postProcessManager) {
            var r = this.getScene();
            if (!r)
                return;
            this._postProcessManager = new PostProcessManager(r),
            this._postProcesses = new Array
        }
        this._postProcesses.push(t),
        this._postProcesses[0].autoClear = !1
    }
    ,
    e.prototype.clearPostProcesses = function(t) {
        if (t === void 0 && (t = !1),
        !!this._postProcesses) {
            if (t)
                for (var r = 0, n = this._postProcesses; r < n.length; r++) {
                    var o = n[r];
                    o.dispose()
                }
            this._postProcesses = []
        }
    }
    ,
    e.prototype.removePostProcess = function(t) {
        if (!!this._postProcesses) {
            var r = this._postProcesses.indexOf(t);
            r !== -1 && (this._postProcesses.splice(r, 1),
            this._postProcesses.length > 0 && (this._postProcesses[0].autoClear = !1))
        }
    }
    ,
    e.prototype._shouldRender = function() {
        return this._currentRefreshId === -1 ? (this._currentRefreshId = 1,
        !0) : this.refreshRate === this._currentRefreshId ? (this._currentRefreshId = 1,
        !0) : (this._currentRefreshId++,
        !1)
    }
    ,
    e.prototype.getRenderSize = function() {
        return this.getRenderWidth()
    }
    ,
    e.prototype.getRenderWidth = function() {
        return this._size.width ? this._size.width : this._size
    }
    ,
    e.prototype.getRenderHeight = function() {
        return this._size.width ? this._size.height : this._size
    }
    ,
    e.prototype.getRenderLayers = function() {
        var t = this._size.layers;
        return t || 0
    }
    ,
    e.prototype.disableRescaling = function() {
        this._canRescale = !1
    }
    ,
    Object.defineProperty(e.prototype, "canRescale", {
        get: function() {
            return this._canRescale
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.scale = function(t) {
        var r = Math.max(1, this.getRenderSize() * t);
        this.resize(r)
    }
    ,
    e.prototype.getReflectionTextureMatrix = function() {
        return this.isCube ? this._textureMatrix : i.prototype.getReflectionTextureMatrix.call(this)
    }
    ,
    e.prototype.resize = function(t) {
        var r, n = this.isCube;
        (r = this._renderTarget) === null || r === void 0 || r.dispose(),
        this._renderTarget = null;
        var o = this.getScene();
        !o || (this._processSizeParameter(t),
        n ? this._renderTarget = o.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions) : this._renderTarget = o.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions),
        this._texture = this._renderTarget.texture,
        this._renderTargetOptions.samples !== void 0 && (this.samples = this._renderTargetOptions.samples),
        this.onResizeObservable.hasObservers() && this.onResizeObservable.notifyObservers(this))
    }
    ,
    e.prototype.render = function(t, r) {
        t === void 0 && (t = !1),
        r === void 0 && (r = !1),
        this._render(t, r)
    }
    ,
    e.prototype.isReadyForRendering = function() {
        return this._render(!1, !1, !0)
    }
    ,
    e.prototype._render = function(t, r, n) {
        var o;
        t === void 0 && (t = !1),
        r === void 0 && (r = !1),
        n === void 0 && (n = !1);
        var a = this.getScene();
        if (!a)
            return n;
        var s = a.getEngine();
        if (this.useCameraPostProcesses !== void 0 && (t = this.useCameraPostProcesses),
        this._waitingRenderList) {
            this.renderList = [];
            for (var l = 0; l < this._waitingRenderList.length; l++) {
                var u = this._waitingRenderList[l]
                  , c = a.getMeshById(u);
                c && this.renderList.push(c)
            }
            this._waitingRenderList = void 0
        }
        if (this.renderListPredicate) {
            this.renderList ? this.renderList.length = 0 : this.renderList = [];
            var a = this.getScene();
            if (!a)
                return n;
            for (var h = a.meshes, l = 0; l < h.length; l++) {
                var f = h[l];
                this.renderListPredicate(f) && this.renderList.push(f)
            }
        }
        var d = s.currentRenderPassId;
        this.onBeforeBindObservable.notifyObservers(this);
        var _ = (o = this.activeCamera) !== null && o !== void 0 ? o : a.activeCamera;
        _ && (_ !== a.activeCamera && a.setTransformMatrix(_.getViewMatrix(), _.getProjectionMatrix(!0)),
        s.setViewport(_.viewport, this.getRenderWidth(), this.getRenderHeight())),
        this._defaultRenderListPrepared = !1;
        var g = n;
        if (n) {
            a.getViewMatrix() || a.updateTransformMatrix();
            for (var y = this.is2DArray ? this.getRenderLayers() : this.isCube ? 6 : 1, m = 0; m < y && g; m++) {
                var b = null
                  , T = this.renderList ? this.renderList : a.getActiveMeshes().data
                  , C = this.renderList ? this.renderList.length : a.getActiveMeshes().length;
                s.currentRenderPassId = this._renderPassIds[m],
                this.onBeforeRenderObservable.notifyObservers(m),
                this.getCustomRenderList && (b = this.getCustomRenderList(m, T, C)),
                b || (b = T),
                this._doNotChangeAspectRatio || a.updateTransformMatrix(!0);
                for (var A = 0; A < b.length && g; ++A) {
                    var S = b[A];
                    if (!(!S.isEnabled() || S.isBlocked || !S.isVisible || !S.subMeshes)) {
                        if (this.customIsReadyFunction) {
                            if (!this.customIsReadyFunction(S, this.refreshRate)) {
                                g = !1;
                                break
                            }
                        } else if (!S.isReady(!0)) {
                            g = !1;
                            break
                        }
                    }
                }
                this.onAfterRenderObservable.notifyObservers(m)
            }
        } else if (this.is2DArray)
            for (var m = 0; m < this.getRenderLayers(); m++)
                this.renderToTarget(0, t, r, m, _),
                a.incrementRenderId(),
                a.resetCachedMaterial();
        else if (this.isCube)
            for (var v = 0; v < 6; v++)
                this.renderToTarget(v, t, r, void 0, _),
                a.incrementRenderId(),
                a.resetCachedMaterial();
        else
            this.renderToTarget(0, t, r, void 0, _);
        return this.onAfterUnbindObservable.notifyObservers(this),
        s.currentRenderPassId = d,
        a.activeCamera && ((a.getEngine().scenes.length > 1 || this.activeCamera && this.activeCamera !== a.activeCamera) && a.setTransformMatrix(a.activeCamera.getViewMatrix(), a.activeCamera.getProjectionMatrix(!0)),
        s.setViewport(a.activeCamera.viewport)),
        a.resetCachedMaterial(),
        g
    }
    ,
    e.prototype._bestReflectionRenderTargetDimension = function(t, r) {
        var n = 128
          , o = t * r
          , a = Engine.NearestPOT(o + n * n / (n + o));
        return Math.min(Engine.FloorPOT(t), a)
    }
    ,
    e.prototype._prepareRenderingManager = function(t, r, n, o) {
        var a = this.getScene();
        if (!!a) {
            this._renderingManager.reset();
            for (var s = a.getRenderId(), l = 0; l < r; l++) {
                var u = t[l];
                if (u && !u.isBlocked) {
                    if (this.customIsReadyFunction) {
                        if (!this.customIsReadyFunction(u, this.refreshRate)) {
                            this.resetRefreshCounter();
                            continue
                        }
                    } else if (!u.isReady(this.refreshRate === 0)) {
                        this.resetRefreshCounter();
                        continue
                    }
                    if (!u._internalAbstractMeshDataInfo._currentLODIsUpToDate && a.activeCamera && (u._internalAbstractMeshDataInfo._currentLOD = a.customLODSelector ? a.customLODSelector(u, this.activeCamera || a.activeCamera) : u.getLOD(this.activeCamera || a.activeCamera),
                    u._internalAbstractMeshDataInfo._currentLODIsUpToDate = !0),
                    !u._internalAbstractMeshDataInfo._currentLOD)
                        continue;
                    var c = u._internalAbstractMeshDataInfo._currentLOD;
                    c._preActivateForIntermediateRendering(s);
                    var h = void 0;
                    if (o && n ? h = (u.layerMask & n.layerMask) === 0 : h = !1,
                    u.isEnabled() && u.isVisible && u.subMeshes && !h && (c !== u && c._activate(s, !0),
                    u._activate(s, !0) && u.subMeshes.length)) {
                        u.isAnInstance ? u._internalAbstractMeshDataInfo._actAsRegularMesh && (c = u) : c._internalAbstractMeshDataInfo._onlyForInstancesIntermediate = !1,
                        c._internalAbstractMeshDataInfo._isActiveIntermediate = !0;
                        for (var f = 0; f < c.subMeshes.length; f++) {
                            var d = c.subMeshes[f];
                            this._renderingManager.dispatch(d, c)
                        }
                    }
                }
            }
            for (var _ = 0; _ < a.particleSystems.length; _++) {
                var g = a.particleSystems[_]
                  , m = g.emitter;
                !g.isStarted() || !m || !m.position || !m.isEnabled() || t.indexOf(m) >= 0 && this._renderingManager.dispatchParticles(g)
            }
        }
    }
    ,
    e.prototype._bindFrameBuffer = function(t, r) {
        t === void 0 && (t = 0),
        r === void 0 && (r = 0);
        var n = this.getScene();
        if (!!n) {
            var o = n.getEngine();
            this._renderTarget && o.bindFramebuffer(this._renderTarget, this.isCube ? t : void 0, void 0, void 0, this.ignoreCameraViewport, 0, r)
        }
    }
    ,
    e.prototype.unbindFrameBuffer = function(t, r) {
        var n = this;
        !this._renderTarget || t.unBindFramebuffer(this._renderTarget, this.isCube, function() {
            n.onAfterRenderObservable.notifyObservers(r)
        })
    }
    ,
    e.prototype._prepareFrame = function(t, r, n, o) {
        this._postProcessManager ? this._prePassEnabled || this._postProcessManager._prepareFrame(this._texture, this._postProcesses) : (!o || !t.postProcessManager._prepareFrame(this._texture)) && this._bindFrameBuffer(r, n)
    }
    ,
    e.prototype.renderToTarget = function(t, r, n, o, a) {
        var s, l, u, c;
        o === void 0 && (o = 0),
        a === void 0 && (a = null);
        var h = this.getScene();
        if (!!h) {
            var f = h.getEngine();
            if (!!this._texture) {
                (s = f._debugPushGroup) === null || s === void 0 || s.call(f, "render to face #" + t + " layer #" + o, 1),
                this._prepareFrame(h, t, o, r),
                this.is2DArray ? (f.currentRenderPassId = this._renderPassIds[o],
                this.onBeforeRenderObservable.notifyObservers(o)) : (f.currentRenderPassId = this._renderPassIds[t],
                this.onBeforeRenderObservable.notifyObservers(t));
                var d = f.snapshotRendering && f.snapshotRenderingMode === 1;
                if (d)
                    this.onClearObservable.hasObservers() ? this.onClearObservable.notifyObservers(f) : this.skipInitialClear || f.clear(this.clearColor || h.clearColor, !0, !0, !0);
                else {
                    var _ = null
                      , g = this.renderList ? this.renderList : h.getActiveMeshes().data
                      , m = this.renderList ? this.renderList.length : h.getActiveMeshes().length;
                    this.getCustomRenderList && (_ = this.getCustomRenderList(this.is2DArray ? o : t, g, m)),
                    _ ? this._prepareRenderingManager(_, _.length, a, !1) : (this._defaultRenderListPrepared || (this._prepareRenderingManager(g, m, a, !this.renderList),
                    this._defaultRenderListPrepared = !0),
                    _ = g);
                    for (var v = 0, y = h._beforeRenderTargetClearStage; v < y.length; v++) {
                        var b = y[v];
                        b.action(this, t, o)
                    }
                    this.onClearObservable.hasObservers() ? this.onClearObservable.notifyObservers(f) : this.skipInitialClear || f.clear(this.clearColor || h.clearColor, !0, !0, !0),
                    this._doNotChangeAspectRatio || h.updateTransformMatrix(!0);
                    for (var T = 0, C = h._beforeRenderTargetDrawStage; T < C.length; T++) {
                        var b = C[T];
                        b.action(this, t, o)
                    }
                    this._renderingManager.render(this.customRenderFunction, _, this.renderParticles, this.renderSprites);
                    for (var A = 0, S = h._afterRenderTargetDrawStage; A < S.length; A++) {
                        var b = S[A];
                        b.action(this, t, o)
                    }
                    var P = this._texture.generateMipMaps;
                    this._texture.generateMipMaps = !1,
                    this._postProcessManager ? this._postProcessManager._finalizeFrame(!1, (l = this._renderTarget) !== null && l !== void 0 ? l : void 0, t, this._postProcesses, this.ignoreCameraViewport) : r && h.postProcessManager._finalizeFrame(!1, (u = this._renderTarget) !== null && u !== void 0 ? u : void 0, t),
                    this._texture.generateMipMaps = P,
                    this._doNotChangeAspectRatio || h.updateTransformMatrix(!0),
                    n && Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), f)
                }
                this.unbindFrameBuffer(f, t),
                this.isCube && t === 5 && f.generateMipMapsForCubemap(this._texture),
                (c = f._debugPopGroup) === null || c === void 0 || c.call(f, 1)
            }
        }
    }
    ,
    e.prototype.setRenderingOrder = function(t, r, n, o) {
        r === void 0 && (r = null),
        n === void 0 && (n = null),
        o === void 0 && (o = null),
        this._renderingManager.setRenderingOrder(t, r, n, o)
    }
    ,
    e.prototype.setRenderingAutoClearDepthStencil = function(t, r) {
        this._renderingManager.setRenderingAutoClearDepthStencil(t, r),
        this._renderingManager._useSceneAutoClearSetup = !1
    }
    ,
    e.prototype.clone = function() {
        var t = this.getSize()
          , r = new e(this.name,t,this.getScene(),this._renderTargetOptions.generateMipMaps,this._doNotChangeAspectRatio,this._renderTargetOptions.type,this.isCube,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer,this._renderTargetOptions.generateStencilBuffer,void 0,this._renderTargetOptions.format,void 0,this._renderTargetOptions.samples);
        return r.hasAlpha = this.hasAlpha,
        r.level = this.level,
        r.coordinatesMode = this.coordinatesMode,
        this.renderList && (r.renderList = this.renderList.slice(0)),
        r
    }
    ,
    e.prototype.serialize = function() {
        if (!this.name)
            return null;
        var t = i.prototype.serialize.call(this);
        if (t.renderTargetSize = this.getRenderSize(),
        t.renderList = [],
        this.renderList)
            for (var r = 0; r < this.renderList.length; r++)
                t.renderList.push(this.renderList[r].id);
        return t
    }
    ,
    e.prototype.disposeFramebufferObjects = function() {
        var t;
        (t = this._renderTarget) === null || t === void 0 || t.dispose(!0)
    }
    ,
    e.prototype.releaseInternalTexture = function() {
        var t;
        (t = this._renderTarget) === null || t === void 0 || t.releaseTextures(),
        this._texture = null
    }
    ,
    e.prototype.dispose = function() {
        var t;
        this.onResizeObservable.clear(),
        this.onClearObservable.clear(),
        this.onAfterRenderObservable.clear(),
        this.onAfterUnbindObservable.clear(),
        this.onBeforeBindObservable.clear(),
        this.onBeforeRenderObservable.clear(),
        this._postProcessManager && (this._postProcessManager.dispose(),
        this._postProcessManager = null),
        this._prePassRenderTarget && this._prePassRenderTarget.dispose(),
        this._releaseRenderPassId(),
        this.clearPostProcesses(!0),
        this._resizeObserver && (this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver),
        this._resizeObserver = null),
        this.renderList = null;
        var r = this.getScene();
        if (!!r) {
            var n = r.customRenderTargets.indexOf(this);
            n >= 0 && r.customRenderTargets.splice(n, 1);
            for (var o = 0, a = r.cameras; o < a.length; o++) {
                var s = a[o];
                n = s.customRenderTargets.indexOf(this),
                n >= 0 && s.customRenderTargets.splice(n, 1)
            }
            (t = this._renderTarget) === null || t === void 0 || t.dispose(),
            this._renderTarget = null,
            this._texture = null,
            i.prototype.dispose.call(this)
        }
    }
    ,
    e.prototype._rebuild = function() {
        this.refreshRate === e.REFRESHRATE_RENDER_ONCE && (this.refreshRate = e.REFRESHRATE_RENDER_ONCE),
        this._postProcessManager && this._postProcessManager._rebuild()
    }
    ,
    e.prototype.freeRenderingGroups = function() {
        this._renderingManager && this._renderingManager.freeRenderingGroups()
    }
    ,
    e.prototype.getViewCount = function() {
        return 1
    }
    ,
    e.REFRESHRATE_RENDER_ONCE = 0,
    e.REFRESHRATE_RENDER_ONEVERYFRAME = 1,
    e.REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2,
    e
}(Texture);
Texture._CreateRenderTargetTexture = function(i, e, t, r, n) {
    return new RenderTargetTexture(i,e,t,r)
}
;
var name$2_ = "postprocessVertexShader"
  , shader$2_ = `
attribute vec2 position;
uniform vec2 scale;

varying vec2 vUV;
const vec2 madd=vec2(0.5,0.5);
void main(void) {
vUV=(position*madd+madd)*scale;
gl_Position=vec4(position,0.0,1.0);
}`;
ShaderStore.ShadersStore[name$2_] = shader$2_;
var PostProcess = function() {
    function i(e, t, r, n, o, a, s, l, u, c, h, f, d, _, g) {
        s === void 0 && (s = 1),
        c === void 0 && (c = null),
        h === void 0 && (h = 0),
        f === void 0 && (f = "postprocess"),
        _ === void 0 && (_ = !1),
        g === void 0 && (g = 5),
        this._parentContainer = null,
        this.width = -1,
        this.height = -1,
        this.nodeMaterialSource = null,
        this._outputTexture = null,
        this.autoClear = !0,
        this.alphaMode = 0,
        this.animations = new Array,
        this.enablePixelPerfectMode = !1,
        this.forceFullscreenViewport = !0,
        this.scaleMode = 1,
        this.alwaysForcePOT = !1,
        this._samples = 1,
        this.adaptScaleToCurrentViewport = !1,
        this._reusable = !1,
        this._renderId = 0,
        this.externalTextureSamplerBinding = !1,
        this._textures = new SmartArray(2),
        this._textureCache = [],
        this._currentRenderTextureInd = 0,
        this._scaleRatio = new Vector2(1,1),
        this._texelSize = Vector2.Zero(),
        this.onActivateObservable = new Observable,
        this.onSizeChangedObservable = new Observable,
        this.onApplyObservable = new Observable,
        this.onBeforeRenderObservable = new Observable,
        this.onAfterRenderObservable = new Observable,
        this.name = e,
        a != null ? (this._camera = a,
        this._scene = a.getScene(),
        a.attachPostProcess(this),
        this._engine = this._scene.getEngine(),
        this._scene.postProcesses.push(this),
        this.uniqueId = this._scene.getUniqueId()) : l && (this._engine = l,
        this._engine.postProcesses.push(this)),
        this._options = o,
        this.renderTargetSamplingMode = s || 1,
        this._reusable = u || !1,
        this._textureType = h,
        this._textureFormat = g,
        this._samplers = n || [],
        this._samplers.push("textureSampler"),
        this._fragmentUrl = t,
        this._vertexUrl = f,
        this._parameters = r || [],
        this._parameters.push("scale"),
        this._indexParameters = d,
        this._drawWrapper = new DrawWrapper(this._engine),
        _ || this.updateEffect(c)
    }
    return Object.defineProperty(i.prototype, "samples", {
        get: function() {
            return this._samples
        },
        set: function(e) {
            var t = this;
            this._samples = Math.min(e, this._engine.getCaps().maxMSAASamples),
            this._textures.forEach(function(r) {
                r.samples !== t._samples && t._engine.updateRenderTargetTextureSampleCount(r, t._samples)
            })
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.getEffectName = function() {
        return this._fragmentUrl
    }
    ,
    Object.defineProperty(i.prototype, "onActivate", {
        set: function(e) {
            this._onActivateObserver && this.onActivateObservable.remove(this._onActivateObserver),
            e && (this._onActivateObserver = this.onActivateObservable.add(e))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "onSizeChanged", {
        set: function(e) {
            this._onSizeChangedObserver && this.onSizeChangedObservable.remove(this._onSizeChangedObserver),
            this._onSizeChangedObserver = this.onSizeChangedObservable.add(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "onApply", {
        set: function(e) {
            this._onApplyObserver && this.onApplyObservable.remove(this._onApplyObserver),
            this._onApplyObserver = this.onApplyObservable.add(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "onBeforeRender", {
        set: function(e) {
            this._onBeforeRenderObserver && this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),
            this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "onAfterRender", {
        set: function(e) {
            this._onAfterRenderObserver && this.onAfterRenderObservable.remove(this._onAfterRenderObserver),
            this._onAfterRenderObserver = this.onAfterRenderObservable.add(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "inputTexture", {
        get: function() {
            return this._textures.data[this._currentRenderTextureInd]
        },
        set: function(e) {
            this._forcedOutputTexture = e
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.restoreDefaultInputTexture = function() {
        this._forcedOutputTexture && (this._forcedOutputTexture = null,
        this.markTextureDirty())
    }
    ,
    i.prototype.getCamera = function() {
        return this._camera
    }
    ,
    Object.defineProperty(i.prototype, "texelSize", {
        get: function() {
            return this._shareOutputWithPostProcess ? this._shareOutputWithPostProcess.texelSize : (this._forcedOutputTexture && this._texelSize.copyFromFloats(1 / this._forcedOutputTexture.width, 1 / this._forcedOutputTexture.height),
            this._texelSize)
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.getClassName = function() {
        return "PostProcess"
    }
    ,
    i.prototype.getEngine = function() {
        return this._engine
    }
    ,
    i.prototype.getEffect = function() {
        return this._drawWrapper.effect
    }
    ,
    i.prototype.shareOutputWith = function(e) {
        return this._disposeTextures(),
        this._shareOutputWithPostProcess = e,
        this
    }
    ,
    i.prototype.useOwnOutput = function() {
        this._textures.length == 0 && (this._textures = new SmartArray(2)),
        this._shareOutputWithPostProcess = null
    }
    ,
    i.prototype.updateEffect = function(e, t, r, n, o, a, s, l) {
        e === void 0 && (e = null),
        t === void 0 && (t = null),
        r === void 0 && (r = null),
        this._postProcessDefines = e,
        this._drawWrapper.effect = this._engine.createEffect({
            vertex: s != null ? s : this._vertexUrl,
            fragment: l != null ? l : this._fragmentUrl
        }, ["position"], t || this._parameters, r || this._samplers, e !== null ? e : "", void 0, o, a, n || this._indexParameters)
    }
    ,
    i.prototype.isReusable = function() {
        return this._reusable
    }
    ,
    i.prototype.markTextureDirty = function() {
        this.width = -1
    }
    ,
    i.prototype._createRenderTargetTexture = function(e, t, r) {
        r === void 0 && (r = 0);
        for (var n = 0; n < this._textureCache.length; n++)
            if (this._textureCache[n].texture.width === e.width && this._textureCache[n].texture.height === e.height && this._textureCache[n].postProcessChannel === r && this._textureCache[n].texture._generateDepthBuffer === t.generateDepthBuffer)
                return this._textureCache[n].texture;
        var o = this._engine.createRenderTargetTexture(e, t);
        return this._textureCache.push({
            texture: o,
            postProcessChannel: r,
            lastUsedRenderId: -1
        }),
        o
    }
    ,
    i.prototype._flushTextureCache = function() {
        for (var e = this._renderId, t = this._textureCache.length - 1; t >= 0; t--)
            if (e - this._textureCache[t].lastUsedRenderId > 100) {
                for (var r = !1, n = 0; n < this._textures.length; n++)
                    if (this._textures.data[n] === this._textureCache[t].texture) {
                        r = !0;
                        break
                    }
                r || (this._textureCache[t].texture.dispose(),
                this._textureCache.splice(t, 1))
            }
    }
    ,
    i.prototype._resize = function(e, t, r, n, o) {
        this._textures.length > 0 && this._textures.reset(),
        this.width = e,
        this.height = t;
        for (var a = null, s = 0; s < r._postProcesses.length; s++)
            if (r._postProcesses[s] !== null) {
                a = r._postProcesses[s];
                break
            }
        var l = {
            width: this.width,
            height: this.height
        }
          , u = {
            generateMipMaps: n,
            generateDepthBuffer: o || a === this,
            generateStencilBuffer: (o || a === this) && this._engine.isStencilEnable,
            samplingMode: this.renderTargetSamplingMode,
            type: this._textureType,
            format: this._textureFormat
        };
        this._textures.push(this._createRenderTargetTexture(l, u, 0)),
        this._reusable && this._textures.push(this._createRenderTargetTexture(l, u, 1)),
        this._texelSize.copyFromFloats(1 / this.width, 1 / this.height),
        this.onSizeChangedObservable.notifyObservers(this)
    }
    ,
    i.prototype.activate = function(e, t, r) {
        var n = this, o, a;
        t === void 0 && (t = null),
        e = e || this._camera;
        var s = e.getScene()
          , l = s.getEngine()
          , u = l.getCaps().maxTextureSize
          , c = (t ? t.width : this._engine.getRenderWidth(!0)) * this._options | 0
          , h = (t ? t.height : this._engine.getRenderHeight(!0)) * this._options | 0
          , f = e.parent;
        f && (f.leftCamera == e || f.rightCamera == e) && (c /= 2);
        var d = this._options.width || c
          , _ = this._options.height || h
          , g = this.renderTargetSamplingMode !== 7 && this.renderTargetSamplingMode !== 1 && this.renderTargetSamplingMode !== 2;
        if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
            if (this.adaptScaleToCurrentViewport) {
                var m = l.currentViewport;
                m && (d *= m.width,
                _ *= m.height)
            }
            (g || this.alwaysForcePOT) && (this._options.width || (d = l.needPOTTextures ? Engine.GetExponentOfTwo(d, u, this.scaleMode) : d),
            this._options.height || (_ = l.needPOTTextures ? Engine.GetExponentOfTwo(_, u, this.scaleMode) : _)),
            (this.width !== d || this.height !== _) && this._resize(d, _, e, g, r),
            this._textures.forEach(function(T) {
                T.samples !== n.samples && n._engine.updateRenderTargetTextureSampleCount(T, n.samples)
            }),
            this._flushTextureCache(),
            this._renderId++
        }
        var v;
        if (this._shareOutputWithPostProcess)
            v = this._shareOutputWithPostProcess.inputTexture;
        else if (this._forcedOutputTexture)
            v = this._forcedOutputTexture,
            this.width = this._forcedOutputTexture.width,
            this.height = this._forcedOutputTexture.height;
        else {
            v = this.inputTexture;
            for (var y = void 0, b = 0; b < this._textureCache.length; b++)
                if (this._textureCache[b].texture === v) {
                    y = this._textureCache[b];
                    break
                }
            y && (y.lastUsedRenderId = this._renderId)
        }
        return this.enablePixelPerfectMode ? (this._scaleRatio.copyFromFloats(c / d, h / _),
        this._engine.bindFramebuffer(v, 0, c, h, this.forceFullscreenViewport)) : (this._scaleRatio.copyFromFloats(1, 1),
        this._engine.bindFramebuffer(v, 0, void 0, void 0, this.forceFullscreenViewport)),
        (a = (o = this._engine)._debugInsertMarker) === null || a === void 0 || a.call(o, "post process " + this.name + " input"),
        this.onActivateObservable.notifyObservers(e),
        this.autoClear && this.alphaMode === 0 && this._engine.clear(this.clearColor ? this.clearColor : s.clearColor, s._allowPostProcessClearColor, !0, !0),
        this._reusable && (this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2),
        v
    }
    ,
    Object.defineProperty(i.prototype, "isSupported", {
        get: function() {
            return this._drawWrapper.effect.isSupported
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "aspectRatio", {
        get: function() {
            return this._shareOutputWithPostProcess ? this._shareOutputWithPostProcess.aspectRatio : this._forcedOutputTexture ? this._forcedOutputTexture.width / this._forcedOutputTexture.height : this.width / this.height
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.isReady = function() {
        var e, t;
        return (t = (e = this._drawWrapper.effect) === null || e === void 0 ? void 0 : e.isReady()) !== null && t !== void 0 ? t : !1
    }
    ,
    i.prototype.apply = function() {
        var e;
        if (!(!((e = this._drawWrapper.effect) === null || e === void 0) && e.isReady()))
            return null;
        this._engine.enableEffect(this._drawWrapper),
        this._engine.setState(!1),
        this._engine.setDepthBuffer(!1),
        this._engine.setDepthWrite(!1),
        this._engine.setAlphaMode(this.alphaMode),
        this.alphaConstants && this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
        var t;
        return this._shareOutputWithPostProcess ? t = this._shareOutputWithPostProcess.inputTexture : this._forcedOutputTexture ? t = this._forcedOutputTexture : t = this.inputTexture,
        this.externalTextureSamplerBinding || this._drawWrapper.effect._bindTexture("textureSampler", t == null ? void 0 : t.texture),
        this._drawWrapper.effect.setVector2("scale", this._scaleRatio),
        this.onApplyObservable.notifyObservers(this._drawWrapper.effect),
        this._drawWrapper.effect
    }
    ,
    i.prototype._disposeTextures = function() {
        if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
            this._disposeTextureCache();
            return
        }
        this._disposeTextureCache(),
        this._textures.dispose()
    }
    ,
    i.prototype._disposeTextureCache = function() {
        for (var e = this._textureCache.length - 1; e >= 0; e--)
            this._textureCache[e].texture.dispose();
        this._textureCache.length = 0
    }
    ,
    i.prototype.setPrePassRenderer = function(e) {
        return this._prePassEffectConfiguration ? (this._prePassEffectConfiguration = e.addEffectConfiguration(this._prePassEffectConfiguration),
        this._prePassEffectConfiguration.enabled = !0,
        !0) : !1
    }
    ,
    i.prototype.dispose = function(e) {
        e = e || this._camera,
        this._disposeTextures();
        var t;
        if (this._scene && (t = this._scene.postProcesses.indexOf(this),
        t !== -1 && this._scene.postProcesses.splice(t, 1)),
        this._parentContainer) {
            var r = this._parentContainer.postProcesses.indexOf(this);
            r > -1 && this._parentContainer.postProcesses.splice(r, 1),
            this._parentContainer = null
        }
        if (t = this._engine.postProcesses.indexOf(this),
        t !== -1 && this._engine.postProcesses.splice(t, 1),
        !!e) {
            if (e.detachPostProcess(this),
            t = e._postProcesses.indexOf(this),
            t === 0 && e._postProcesses.length > 0) {
                var n = this._camera._getFirstPostProcess();
                n && n.markTextureDirty()
            }
            this.onActivateObservable.clear(),
            this.onAfterRenderObservable.clear(),
            this.onApplyObservable.clear(),
            this.onBeforeRenderObservable.clear(),
            this.onSizeChangedObservable.clear()
        }
    }
    ,
    i.prototype.serialize = function() {
        var e = SerializationHelper.Serialize(this)
          , t = this.getCamera() || this._scene && this._scene.activeCamera;
        return e.customType = "BABYLON." + this.getClassName(),
        e.cameraId = t ? t.id : null,
        e.reusable = this._reusable,
        e.textureType = this._textureType,
        e.fragmentUrl = this._fragmentUrl,
        e.parameters = this._parameters,
        e.samplers = this._samplers,
        e.options = this._options,
        e.defines = this._postProcessDefines,
        e.textureFormat = this._textureFormat,
        e.vertexUrl = this._vertexUrl,
        e.indexParameters = this._indexParameters,
        e
    }
    ,
    i.prototype.clone = function() {
        var e = this.serialize();
        e._engine = this._engine,
        e.cameraId = null;
        var t = i.Parse(e, this._scene, "");
        return t ? (t.onActivateObservable = this.onActivateObservable.clone(),
        t.onSizeChangedObservable = this.onSizeChangedObservable.clone(),
        t.onApplyObservable = this.onApplyObservable.clone(),
        t.onBeforeRenderObservable = this.onBeforeRenderObservable.clone(),
        t.onAfterRenderObservable = this.onAfterRenderObservable.clone(),
        t._prePassEffectConfiguration = this._prePassEffectConfiguration,
        t) : null
    }
    ,
    i.Parse = function(e, t, r) {
        var n = GetClass(e.customType);
        if (!n || !n._Parse)
            return null;
        var o = t ? t.getCameraById(e.cameraId) : null;
        return n._Parse(e, o, t, r)
    }
    ,
    i._Parse = function(e, t, r, n) {
        return SerializationHelper.Parse(function() {
            return new i(e.name,e.fragmentUrl,e.parameters,e.samplers,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable,e.defines,e.textureType,e.vertexUrl,e.indexParameters,!1,e.textureFormat)
        }, e, r, n)
    }
    ,
    __decorate([serialize()], i.prototype, "uniqueId", void 0),
    __decorate([serialize()], i.prototype, "name", void 0),
    __decorate([serialize()], i.prototype, "width", void 0),
    __decorate([serialize()], i.prototype, "height", void 0),
    __decorate([serialize()], i.prototype, "renderTargetSamplingMode", void 0),
    __decorate([serializeAsColor4()], i.prototype, "clearColor", void 0),
    __decorate([serialize()], i.prototype, "autoClear", void 0),
    __decorate([serialize()], i.prototype, "alphaMode", void 0),
    __decorate([serialize()], i.prototype, "alphaConstants", void 0),
    __decorate([serialize()], i.prototype, "enablePixelPerfectMode", void 0),
    __decorate([serialize()], i.prototype, "forceFullscreenViewport", void 0),
    __decorate([serialize()], i.prototype, "scaleMode", void 0),
    __decorate([serialize()], i.prototype, "alwaysForcePOT", void 0),
    __decorate([serialize("samples")], i.prototype, "_samples", void 0),
    __decorate([serialize()], i.prototype, "adaptScaleToCurrentViewport", void 0),
    i
}();
RegisterClass("BABYLON.PostProcess", PostProcess);
var name$2Z = "kernelBlurVaryingDeclaration"
  , shader$2Z = "varying vec2 sampleCoord{X};";
ShaderStore.IncludesShadersStore[name$2Z] = shader$2Z;
var name$2Y = "packingFunctions"
  , shader$2Y = `vec4 pack(float depth)
{
const vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);
const vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);
vec4 res=fract(depth*bit_shift);
res-=res.xxyz*bit_mask;
return res;
}
float unpack(vec4 color)
{
const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);
return dot(color,bit_shift);
}`;
ShaderStore.IncludesShadersStore[name$2Y] = shader$2Y;
var name$2X = "kernelBlurFragment"
  , shader$2X = `#ifdef DOF
factor=sampleCoC(sampleCoord{X});
computedWeight=KERNEL_WEIGHT{X}*factor;
sumOfWeights+=computedWeight;
#else
computedWeight=KERNEL_WEIGHT{X};
#endif
#ifdef PACKEDFLOAT
blend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;
#else
blend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;
#endif`;
ShaderStore.IncludesShadersStore[name$2X] = shader$2X;
var name$2W = "kernelBlurFragment2"
  , shader$2W = `#ifdef DOF
factor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});
computedWeight=KERNEL_DEP_WEIGHT{X}*factor;
sumOfWeights+=computedWeight;
#else
computedWeight=KERNEL_DEP_WEIGHT{X};
#endif
#ifdef PACKEDFLOAT
blend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;
#else
blend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;
#endif`;
ShaderStore.IncludesShadersStore[name$2W] = shader$2W;
var name$2V = "kernelBlurPixelShader"
  , shader$2V = `
uniform sampler2D textureSampler;
uniform vec2 delta;

varying vec2 sampleCenter;
#ifdef DOF
uniform sampler2D circleOfConfusionSampler;
uniform vec2 cameraMinMaxZ;
float sampleDistance(in vec2 offset) {
float depth=texture2D(circleOfConfusionSampler,offset).g;
return cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth;
}
float sampleCoC(in vec2 offset) {
float coc=texture2D(circleOfConfusionSampler,offset).r;
return coc;
}
#endif
#include<kernelBlurVaryingDeclaration>[0..varyingCount]
#ifdef PACKEDFLOAT
#include<packingFunctions>
#endif
void main(void)
{
float computedWeight=0.0;
#ifdef PACKEDFLOAT
float blend=0.;
#else
vec4 blend=vec4(0.);
#endif
#ifdef DOF
float sumOfWeights=CENTER_WEIGHT;
float factor=0.0;

#ifdef PACKEDFLOAT
blend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;
#else
blend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;
#endif
#endif
#include<kernelBlurFragment>[0..varyingCount]
#include<kernelBlurFragment2>[0..depCount]
#ifdef PACKEDFLOAT
gl_FragColor=pack(blend);
#else
gl_FragColor=blend;
#endif
#ifdef DOF
gl_FragColor/=sumOfWeights;
#endif
}`;
ShaderStore.ShadersStore[name$2V] = shader$2V;
var name$2U = "kernelBlurVertex"
  , shader$2U = "sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};";
ShaderStore.IncludesShadersStore[name$2U] = shader$2U;
var name$2T = "kernelBlurVertexShader"
  , shader$2T = `
attribute vec2 position;

uniform vec2 delta;

varying vec2 sampleCenter;
#include<kernelBlurVaryingDeclaration>[0..varyingCount]
const vec2 madd=vec2(0.5,0.5);
void main(void) {
sampleCenter=(position*madd+madd);
#include<kernelBlurVertex>[0..varyingCount]
gl_Position=vec4(position,0.0,1.0);
}`;
ShaderStore.ShadersStore[name$2T] = shader$2T;
var BlurPostProcess = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a, s, l, u, c, h, f) {
        s === void 0 && (s = Texture.BILINEAR_SAMPLINGMODE),
        c === void 0 && (c = 0),
        h === void 0 && (h = ""),
        f === void 0 && (f = !1);
        var d = i.call(this, t, "kernelBlur", ["delta", "direction", "cameraMinMaxZ"], ["circleOfConfusionSampler"], o, a, s, l, u, null, c, "kernelBlur", {
            varyingCount: 0,
            depCount: 0
        }, !0) || this;
        return d.blockCompilation = f,
        d._packedFloat = !1,
        d._staticDefines = "",
        d._staticDefines = h,
        d.direction = r,
        d.onApplyObservable.add(function(_) {
            d._outputTexture ? _.setFloat2("delta", 1 / d._outputTexture.width * d.direction.x, 1 / d._outputTexture.height * d.direction.y) : _.setFloat2("delta", 1 / d.width * d.direction.x, 1 / d.height * d.direction.y)
        }),
        d.kernel = n,
        d
    }
    return Object.defineProperty(e.prototype, "kernel", {
        get: function() {
            return this._idealKernel
        },
        set: function(t) {
            this._idealKernel !== t && (t = Math.max(t, 1),
            this._idealKernel = t,
            this._kernel = this._nearestBestKernel(t),
            this.blockCompilation || this._updateParameters())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "packedFloat", {
        get: function() {
            return this._packedFloat
        },
        set: function(t) {
            this._packedFloat !== t && (this._packedFloat = t,
            this.blockCompilation || this._updateParameters())
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getClassName = function() {
        return "BlurPostProcess"
    }
    ,
    e.prototype.updateEffect = function(t, r, n, o, a, s) {
        this._updateParameters(a, s)
    }
    ,
    e.prototype._updateParameters = function(t, r) {
        for (var n = this._kernel, o = (n - 1) / 2, a = [], s = [], l = 0, u = 0; u < n; u++) {
            var c = u / (n - 1)
              , h = this._gaussianWeight(c * 2 - 1);
            a[u] = u - o,
            s[u] = h,
            l += h
        }
        for (var u = 0; u < s.length; u++)
            s[u] /= l;
        for (var f = [], d = [], _ = [], u = 0; u <= o; u += 2) {
            var g = Math.min(u + 1, Math.floor(o))
              , m = u === g;
            if (m)
                _.push({
                    o: a[u],
                    w: s[u]
                });
            else {
                var v = g === o
                  , y = s[u] + s[g] * (v ? .5 : 1)
                  , b = a[u] + 1 / (1 + s[u] / s[g]);
                b === 0 ? (_.push({
                    o: a[u],
                    w: s[u]
                }),
                _.push({
                    o: a[u + 1],
                    w: s[u + 1]
                })) : (_.push({
                    o: b,
                    w: y
                }),
                _.push({
                    o: -b,
                    w: y
                }))
            }
        }
        for (var u = 0; u < _.length; u++)
            d[u] = _[u].o,
            f[u] = _[u].w;
        a = d,
        s = f;
        var T = this.getEngine().getCaps().maxVaryingVectors
          , C = Math.max(T, 0) - 1
          , A = Math.min(a.length, C)
          , S = "";
        S += this._staticDefines,
        this._staticDefines.indexOf("DOF") != -1 && (S += "#define CENTER_WEIGHT " + this._glslFloat(s[A - 1]) + `\r
`,
        A--);
        for (var u = 0; u < A; u++)
            S += "#define KERNEL_OFFSET" + u + " " + this._glslFloat(a[u]) + `\r
`,
            S += "#define KERNEL_WEIGHT" + u + " " + this._glslFloat(s[u]) + `\r
`;
        for (var P = 0, u = C; u < a.length; u++)
            S += "#define KERNEL_DEP_OFFSET" + P + " " + this._glslFloat(a[u]) + `\r
`,
            S += "#define KERNEL_DEP_WEIGHT" + P + " " + this._glslFloat(s[u]) + `\r
`,
            P++;
        this.packedFloat && (S += "#define PACKEDFLOAT 1"),
        this.blockCompilation = !1,
        i.prototype.updateEffect.call(this, S, null, null, {
            varyingCount: A,
            depCount: P
        }, t, r)
    }
    ,
    e.prototype._nearestBestKernel = function(t) {
        for (var r = Math.round(t), n = 0, o = [r, r - 1, r + 1, r - 2, r + 2]; n < o.length; n++) {
            var a = o[n];
            if (a % 2 !== 0 && Math.floor(a / 2) % 2 === 0 && a > 0)
                return Math.max(a, 3)
        }
        return Math.max(r, 3)
    }
    ,
    e.prototype._gaussianWeight = function(t) {
        var r = .3333333333333333
          , n = Math.sqrt(2 * Math.PI) * r
          , o = -(t * t / (2 * r * r))
          , a = 1 / n * Math.exp(o);
        return a
    }
    ,
    e.prototype._glslFloat = function(t, r) {
        return r === void 0 && (r = 8),
        t.toFixed(r).replace(/0+$/, "")
    }
    ,
    e._Parse = function(t, r, n, o) {
        return SerializationHelper.Parse(function() {
            return new e(t.name,t.direction,t.kernel,t.options,r,t.renderTargetSamplingMode,n.getEngine(),t.reusable,t.textureType,void 0,!1)
        }, t, n, o)
    }
    ,
    __decorate([serialize("kernel")], e.prototype, "_kernel", void 0),
    __decorate([serialize("packedFloat")], e.prototype, "_packedFloat", void 0),
    __decorate([serializeAsVector2()], e.prototype, "direction", void 0),
    e
}(PostProcess);
RegisterClass("BABYLON.BlurPostProcess", BlurPostProcess);
var EffectFallbacks = function() {
    function i() {
        this._defines = {},
        this._currentRank = 32,
        this._maxRank = -1,
        this._mesh = null
    }
    return i.prototype.unBindMesh = function() {
        this._mesh = null
    }
    ,
    i.prototype.addFallback = function(e, t) {
        this._defines[e] || (e < this._currentRank && (this._currentRank = e),
        e > this._maxRank && (this._maxRank = e),
        this._defines[e] = new Array),
        this._defines[e].push(t)
    }
    ,
    i.prototype.addCPUSkinningFallback = function(e, t) {
        this._mesh = t,
        e < this._currentRank && (this._currentRank = e),
        e > this._maxRank && (this._maxRank = e)
    }
    ,
    Object.defineProperty(i.prototype, "hasMoreFallbacks", {
        get: function() {
            return this._currentRank <= this._maxRank
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.reduce = function(e, t) {
        if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
            this._mesh.computeBonesUsingShaders = !1,
            e = e.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0"),
            t._bonesComputationForcedToCPU = !0;
            for (var r = this._mesh.getScene(), n = 0; n < r.meshes.length; n++) {
                var o = r.meshes[n];
                if (!o.material) {
                    !this._mesh.material && o.computeBonesUsingShaders && o.numBoneInfluencers > 0 && (o.computeBonesUsingShaders = !1);
                    continue
                }
                if (!(!o.computeBonesUsingShaders || o.numBoneInfluencers === 0)) {
                    if (o.material.getEffect() === t)
                        o.computeBonesUsingShaders = !1;
                    else if (o.subMeshes)
                        for (var a = 0, s = o.subMeshes; a < s.length; a++) {
                            var l = s[a]
                              , u = l.effect;
                            if (u === t) {
                                o.computeBonesUsingShaders = !1;
                                break
                            }
                        }
                }
            }
        } else {
            var c = this._defines[this._currentRank];
            if (c)
                for (var n = 0; n < c.length; n++)
                    e = e.replace("#define " + c[n], "");
            this._currentRank++
        }
        return e
    }
    ,
    i
}()
  , name$2S = "bayerDitherFunctions"
  , shader$2S = `




float bayerDither2(vec2 _P) {
return mod(2.0*_P.y+_P.x+1.0,4.0);
}


float bayerDither4(vec2 _P) {
vec2 P1=mod(_P,2.0);
vec2 P2=floor(0.5*mod(_P,4.0));
return 4.0*bayerDither2(P1)+bayerDither2(P2);
}

float bayerDither8(vec2 _P) {
vec2 P1=mod(_P,2.0);
vec2 P2=floor(0.5*mod(_P,4.0));
vec2 P4=floor(0.25*mod(_P,8.0));
return 4.0*(4.0*bayerDither2(P1)+bayerDither2(P2))+bayerDither2(P4);
}
`;
ShaderStore.IncludesShadersStore[name$2S] = shader$2S;
var name$2R = "shadowMapFragmentExtraDeclaration"
  , shader$2R = `#if SM_FLOAT == 0
#include<packingFunctions>
#endif
#if SM_SOFTTRANSPARENTSHADOW == 1
#include<bayerDitherFunctions>
uniform float softTransparentShadowSM;
#endif
varying float vDepthMetricSM;
#if SM_USEDISTANCE == 1
uniform vec3 lightDataSM;
varying vec3 vPositionWSM;
#endif
uniform vec3 biasAndScaleSM;
uniform vec2 depthValuesSM;
#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP == 1
varying float zSM;
#endif
`;
ShaderStore.IncludesShadersStore[name$2R] = shader$2R;
var name$2Q = "clipPlaneFragmentDeclaration"
  , shader$2Q = `#ifdef CLIPPLANE
varying float fClipDistance;
#endif
#ifdef CLIPPLANE2
varying float fClipDistance2;
#endif
#ifdef CLIPPLANE3
varying float fClipDistance3;
#endif
#ifdef CLIPPLANE4
varying float fClipDistance4;
#endif
#ifdef CLIPPLANE5
varying float fClipDistance5;
#endif
#ifdef CLIPPLANE6
varying float fClipDistance6;
#endif`;
ShaderStore.IncludesShadersStore[name$2Q] = shader$2Q;
var name$2P = "clipPlaneFragment"
  , shader$2P = `#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)


if (false) {}
#endif
#ifdef CLIPPLANE
else if (fClipDistance>0.0)
{
discard;
}
#endif
#ifdef CLIPPLANE2
else if (fClipDistance2>0.0)
{
discard;
}
#endif
#ifdef CLIPPLANE3
else if (fClipDistance3>0.0)
{
discard;
}
#endif
#ifdef CLIPPLANE4
else if (fClipDistance4>0.0)
{
discard;
}
#endif
#ifdef CLIPPLANE5
else if (fClipDistance5>0.0)
{
discard;
}
#endif
#ifdef CLIPPLANE6
else if (fClipDistance6>0.0)
{
discard;
}
#endif`;
ShaderStore.IncludesShadersStore[name$2P] = shader$2P;
var name$2O = "shadowMapFragment"
  , shader$2O = ` float depthSM=vDepthMetricSM;
#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP == 1
#if SM_USEDISTANCE == 1
depthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;
#else
#ifdef USE_REVERSE_DEPTHBUFFER
depthSM=(-zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;
#else
depthSM=(zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;
#endif
#endif
#ifdef USE_REVERSE_DEPTHBUFFER
gl_FragDepth=clamp(1.0-depthSM,0.0,1.0);
#else
gl_FragDepth=clamp(depthSM,0.0,1.0);
#endif
#elif SM_USEDISTANCE == 1
depthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;
#endif
#if SM_ESM == 1
depthSM=clamp(exp(-min(87.,biasAndScaleSM.z*depthSM)),0.,1.);
#endif
#if SM_FLOAT == 1
gl_FragColor=vec4(depthSM,1.0,1.0,1.0);
#else
gl_FragColor=pack(depthSM);
#endif
return;`;
ShaderStore.IncludesShadersStore[name$2O] = shader$2O;
var name$2N = "shadowMapPixelShader"
  , shader$2N = `#include<shadowMapFragmentExtraDeclaration>
#ifdef ALPHATEST
varying vec2 vUV;
uniform sampler2D diffuseSampler;
#endif
#include<clipPlaneFragmentDeclaration>
void main(void)
{
#include<clipPlaneFragment>
#ifdef ALPHATEST
float alphaFromAlphaTexture=texture2D(diffuseSampler,vUV).a;
if (alphaFromAlphaTexture<0.4)
discard;
#endif
#if SM_SOFTTRANSPARENTSHADOW == 1
#ifdef ALPHATEST
if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM*alphaFromAlphaTexture) discard;
#else
if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM) discard;
#endif
#endif
#include<shadowMapFragment>
}`;
ShaderStore.ShadersStore[name$2N] = shader$2N;
var name$2M = "bonesDeclaration"
  , shader$2M = `#if NUM_BONE_INFLUENCERS>0
attribute vec4 matricesIndices;
attribute vec4 matricesWeights;
#if NUM_BONE_INFLUENCERS>4
attribute vec4 matricesIndicesExtra;
attribute vec4 matricesWeightsExtra;
#endif
#ifndef BAKED_VERTEX_ANIMATION_TEXTURE
#ifdef BONETEXTURE
uniform sampler2D boneSampler;
uniform float boneTextureWidth;
#else
uniform mat4 mBones[BonesPerMesh];
#ifdef BONES_VELOCITY_ENABLED
uniform mat4 mPreviousBones[BonesPerMesh];
#endif
#endif
#ifdef BONETEXTURE
#define inline
mat4 readMatrixFromRawSampler(sampler2D smp,float index)
{
float offset=index*4.0;
float dx=1.0/boneTextureWidth;
vec4 m0=texture2D(smp,vec2(dx*(offset+0.5),0.));
vec4 m1=texture2D(smp,vec2(dx*(offset+1.5),0.));
vec4 m2=texture2D(smp,vec2(dx*(offset+2.5),0.));
vec4 m3=texture2D(smp,vec2(dx*(offset+3.5),0.));
return mat4(m0,m1,m2,m3);
}
#endif
#endif
#endif`;
ShaderStore.IncludesShadersStore[name$2M] = shader$2M;
var name$2L = "bakedVertexAnimationDeclaration"
  , shader$2L = `#ifdef BAKED_VERTEX_ANIMATION_TEXTURE
uniform float bakedVertexAnimationTime;
uniform vec2 bakedVertexAnimationTextureSizeInverted;
uniform vec4 bakedVertexAnimationSettings;
uniform sampler2D bakedVertexAnimationTexture;
#ifdef INSTANCES
attribute vec4 bakedVertexAnimationSettingsInstanced;
attribute float bakedVertexAnimationTimeInstanced;
#endif
#define inline
mat4 readMatrixFromRawSamplerVAT(sampler2D smp,float index,float frame)
{
float offset=index*4.0;
float frameUV=(frame+0.5)*bakedVertexAnimationTextureSizeInverted.y;
float dx=bakedVertexAnimationTextureSizeInverted.x;
vec4 m0=texture2D(smp,vec2(dx*(offset+0.5),frameUV));
vec4 m1=texture2D(smp,vec2(dx*(offset+1.5),frameUV));
vec4 m2=texture2D(smp,vec2(dx*(offset+2.5),frameUV));
vec4 m3=texture2D(smp,vec2(dx*(offset+3.5),frameUV));
return mat4(m0,m1,m2,m3);
}
#endif`;
ShaderStore.IncludesShadersStore[name$2L] = shader$2L;
var name$2K = "morphTargetsVertexGlobalDeclaration"
  , shader$2K = `#ifdef MORPHTARGETS
uniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];
#ifdef MORPHTARGETS_TEXTURE
precision mediump sampler2DArray;
uniform float morphTargetTextureIndices[NUM_MORPH_INFLUENCERS];
uniform vec3 morphTargetTextureInfo;
uniform sampler2DArray morphTargets;
vec3 readVector3FromRawSampler(int targetIndex,float vertexIndex)
{
float y=floor(vertexIndex/morphTargetTextureInfo.y);
float x=vertexIndex-y*morphTargetTextureInfo.y;
vec3 textureUV=vec3((x+0.5)/morphTargetTextureInfo.y,(y+0.5)/morphTargetTextureInfo.z,morphTargetTextureIndices[targetIndex]);
return texture(morphTargets,textureUV).xyz;
}
#endif
#endif`;
ShaderStore.IncludesShadersStore[name$2K] = shader$2K;
var name$2J = "morphTargetsVertexDeclaration"
  , shader$2J = `#ifdef MORPHTARGETS
#ifndef MORPHTARGETS_TEXTURE
attribute vec3 position{X};
#ifdef MORPHTARGETS_NORMAL
attribute vec3 normal{X};
#endif
#ifdef MORPHTARGETS_TANGENT
attribute vec3 tangent{X};
#endif
#ifdef MORPHTARGETS_UV
attribute vec2 uv_{X};
#endif
#endif
#endif`;
ShaderStore.IncludesShadersStore[name$2J] = shader$2J;
var name$2I = "helperFunctions"
  , shader$2I = `const float PI=3.1415926535897932384626433832795;
const float HALF_MIN=5.96046448e-08;
const float LinearEncodePowerApprox=2.2;
const float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;
const vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);
const float Epsilon=0.0000001;
#define saturate(x) clamp(x,0.0,1.0)
#define absEps(x) abs(x)+Epsilon
#define maxEps(x) max(x,Epsilon)
#define saturateEps(x) clamp(x,Epsilon,1.0)
mat3 transposeMat3(mat3 inMatrix) {
vec3 i0=inMatrix[0];
vec3 i1=inMatrix[1];
vec3 i2=inMatrix[2];
mat3 outMatrix=mat3(
vec3(i0.x,i1.x,i2.x),
vec3(i0.y,i1.y,i2.y),
vec3(i0.z,i1.z,i2.z)
);
return outMatrix;
}

mat3 inverseMat3(mat3 inMatrix) {
float a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];
float a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];
float a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];
float b01=a22*a11-a12*a21;
float b11=-a22*a10+a12*a20;
float b21=a21*a10-a11*a20;
float det=a00*b01+a01*b11+a02*b21;
return mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),
b11,(a22*a00-a02*a20),(-a12*a00+a02*a10),
b21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;
}
float toLinearSpace(float color)
{
return pow(color,LinearEncodePowerApprox);
}
vec3 toLinearSpace(vec3 color)
{
return pow(color,vec3(LinearEncodePowerApprox));
}
vec4 toLinearSpace(vec4 color)
{
return vec4(pow(color.rgb,vec3(LinearEncodePowerApprox)),color.a);
}
vec3 toGammaSpace(vec3 color)
{
return pow(color,vec3(GammaEncodePowerApprox));
}
vec4 toGammaSpace(vec4 color)
{
return vec4(pow(color.rgb,vec3(GammaEncodePowerApprox)),color.a);
}
float toGammaSpace(float color)
{
return pow(color,GammaEncodePowerApprox);
}
float square(float value)
{
return value*value;
}
float pow5(float value) {
float sq=value*value;
return sq*sq*value;
}
float getLuminance(vec3 color)
{
return clamp(dot(color,LuminanceEncodeApprox),0.,1.);
}

float getRand(vec2 seed) {
return fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);
}
float dither(vec2 seed,float varianceAmount) {
float rand=getRand(seed);
float dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);
return dither;
}

const float rgbdMaxRange=255.0;
vec4 toRGBD(vec3 color) {
float maxRGB=maxEps(max(color.r,max(color.g,color.b)));
float D=max(rgbdMaxRange/maxRGB,1.);
D=clamp(floor(D)/255.0,0.,1.);

vec3 rgb=color.rgb*D;

rgb=toGammaSpace(rgb);
return vec4(clamp(rgb,0.,1.),D);
}
vec3 fromRGBD(vec4 rgbd) {

rgbd.rgb=toLinearSpace(rgbd.rgb);

return rgbd.rgb/rgbd.a;
}
vec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {

vec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;
vec3 halfSize=cubeSize*0.5;
vec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;
vec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;

vec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);

float distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);

vec3 intersectPositionWS=vertexPos+origVec*distance;

return intersectPositionWS-cubePos;
}
`;
ShaderStore.IncludesShadersStore[name$2I] = shader$2I;
var name$2H = "sceneVertexDeclaration"
  , shader$2H = `uniform mat4 viewProjection;
#ifdef MULTIVIEW
uniform mat4 viewProjectionR;
#endif
uniform mat4 view;
uniform mat4 projection;
uniform vec4 vEyePosition;
`;
ShaderStore.IncludesShadersStore[name$2H] = shader$2H;
var name$2G = "meshVertexDeclaration"
  , shader$2G = `uniform mat4 world;
uniform float visibility;
`;
ShaderStore.IncludesShadersStore[name$2G] = shader$2G;
var name$2F = "shadowMapVertexDeclaration"
  , shader$2F = `#include<sceneVertexDeclaration>
#include<meshVertexDeclaration>
`;
ShaderStore.IncludesShadersStore[name$2F] = shader$2F;
var name$2E = "sceneUboDeclaration"
  , shader$2E = `layout(std140,column_major) uniform;
uniform Scene {
mat4 viewProjection;
#ifdef MULTIVIEW
mat4 viewProjectionR;
#endif
mat4 view;
mat4 projection;
vec4 vEyePosition;
};
`;
ShaderStore.IncludesShadersStore[name$2E] = shader$2E;
var name$2D = "meshUboDeclaration"
  , shader$2D = `layout(std140,column_major) uniform;
uniform Mesh
{
mat4 world;
float visibility;
};
#define WORLD_UBO`;
ShaderStore.IncludesShadersStore[name$2D] = shader$2D;
var name$2C = "shadowMapUboDeclaration"
  , shader$2C = `layout(std140,column_major) uniform;
#include<sceneUboDeclaration>
#include<meshUboDeclaration>
`;
ShaderStore.IncludesShadersStore[name$2C] = shader$2C;
var name$2B = "shadowMapVertexExtraDeclaration"
  , shader$2B = `#if SM_NORMALBIAS == 1
uniform vec3 lightDataSM;
#endif
uniform vec3 biasAndScaleSM;
uniform vec2 depthValuesSM;
varying float vDepthMetricSM;
#if SM_USEDISTANCE == 1
varying vec3 vPositionWSM;
#endif
#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP == 1
varying float zSM;
#endif
`;
ShaderStore.IncludesShadersStore[name$2B] = shader$2B;
var name$2A = "clipPlaneVertexDeclaration"
  , shader$2A = `#ifdef CLIPPLANE
uniform vec4 vClipPlane;
varying float fClipDistance;
#endif
#ifdef CLIPPLANE2
uniform vec4 vClipPlane2;
varying float fClipDistance2;
#endif
#ifdef CLIPPLANE3
uniform vec4 vClipPlane3;
varying float fClipDistance3;
#endif
#ifdef CLIPPLANE4
uniform vec4 vClipPlane4;
varying float fClipDistance4;
#endif
#ifdef CLIPPLANE5
uniform vec4 vClipPlane5;
varying float fClipDistance5;
#endif
#ifdef CLIPPLANE6
uniform vec4 vClipPlane6;
varying float fClipDistance6;
#endif`;
ShaderStore.IncludesShadersStore[name$2A] = shader$2A;
var name$2z = "morphTargetsVertexGlobal"
  , shader$2z = `#ifdef MORPHTARGETS
#ifdef MORPHTARGETS_TEXTURE
float vertexID;
#endif
#endif`;
ShaderStore.IncludesShadersStore[name$2z] = shader$2z;
var name$2y = "morphTargetsVertex"
  , shader$2y = `#ifdef MORPHTARGETS
#ifdef MORPHTARGETS_TEXTURE
vertexID=float(gl_VertexID)*morphTargetTextureInfo.x;
positionUpdated+=(readVector3FromRawSampler({X},vertexID)-position)*morphTargetInfluences[{X}];
vertexID+=1.0;
#ifdef MORPHTARGETS_NORMAL
normalUpdated+=(readVector3FromRawSampler({X},vertexID)-normal)*morphTargetInfluences[{X}];
vertexID+=1.0;
#endif
#ifdef MORPHTARGETS_UV
uvUpdated+=(readVector3FromRawSampler({X},vertexID).xy-uv)*morphTargetInfluences[{X}];
vertexID+=1.0;
#endif
#ifdef MORPHTARGETS_TANGENT
tangentUpdated.xyz+=(readVector3FromRawSampler({X},vertexID)-tangent.xyz)*morphTargetInfluences[{X}];
#endif
#else
positionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];
#ifdef MORPHTARGETS_NORMAL
normalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];
#endif
#ifdef MORPHTARGETS_TANGENT
tangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];
#endif
#ifdef MORPHTARGETS_UV
uvUpdated+=(uv_{X}-uv)*morphTargetInfluences[{X}];
#endif
#endif
#endif`;
ShaderStore.IncludesShadersStore[name$2y] = shader$2y;
var name$2x = "instancesVertex"
  , shader$2x = `#ifdef INSTANCES
mat4 finalWorld=mat4(world0,world1,world2,world3);
#if defined(PREPASS_VELOCITY) || defined(VELOCITY)
mat4 finalPreviousWorld=mat4(previousWorld0,previousWorld1,previousWorld2,previousWorld3);
#endif
#ifdef THIN_INSTANCES
finalWorld=world*finalWorld;
#if defined(PREPASS_VELOCITY) || defined(VELOCITY)
finalPreviousWorld=previousWorld*finalPreviousWorld;
#endif
#endif
#else
mat4 finalWorld=world;
#if defined(PREPASS_VELOCITY) || defined(VELOCITY)
mat4 finalPreviousWorld=previousWorld;
#endif
#endif`;
ShaderStore.IncludesShadersStore[name$2x] = shader$2x;
var name$2w = "bonesVertex"
  , shader$2w = `#ifndef BAKED_VERTEX_ANIMATION_TEXTURE
#if NUM_BONE_INFLUENCERS>0
mat4 influence;
#ifdef BONETEXTURE
influence=readMatrixFromRawSampler(boneSampler,matricesIndices[0])*matricesWeights[0];
#if NUM_BONE_INFLUENCERS>1
influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[1])*matricesWeights[1];
#endif
#if NUM_BONE_INFLUENCERS>2
influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[2])*matricesWeights[2];
#endif
#if NUM_BONE_INFLUENCERS>3
influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[3])*matricesWeights[3];
#endif
#if NUM_BONE_INFLUENCERS>4
influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[0])*matricesWeightsExtra[0];
#endif
#if NUM_BONE_INFLUENCERS>5
influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[1])*matricesWeightsExtra[1];
#endif
#if NUM_BONE_INFLUENCERS>6
influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[2])*matricesWeightsExtra[2];
#endif
#if NUM_BONE_INFLUENCERS>7
influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[3])*matricesWeightsExtra[3];
#endif
#else
influence=mBones[int(matricesIndices[0])]*matricesWeights[0];
#if NUM_BONE_INFLUENCERS>1
influence+=mBones[int(matricesIndices[1])]*matricesWeights[1];
#endif
#if NUM_BONE_INFLUENCERS>2
influence+=mBones[int(matricesIndices[2])]*matricesWeights[2];
#endif
#if NUM_BONE_INFLUENCERS>3
influence+=mBones[int(matricesIndices[3])]*matricesWeights[3];
#endif
#if NUM_BONE_INFLUENCERS>4
influence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];
#endif
#if NUM_BONE_INFLUENCERS>5
influence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];
#endif
#if NUM_BONE_INFLUENCERS>6
influence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];
#endif
#if NUM_BONE_INFLUENCERS>7
influence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];
#endif
#endif
finalWorld=finalWorld*influence;
#endif
#endif`;
ShaderStore.IncludesShadersStore[name$2w] = shader$2w;
var name$2v = "bakedVertexAnimation"
  , shader$2v = `#ifdef BAKED_VERTEX_ANIMATION_TEXTURE
{
#ifdef INSTANCES
#define BVASNAME bakedVertexAnimationSettingsInstanced
#else
#define BVASNAME bakedVertexAnimationSettings
#endif

float VATStartFrame=BVASNAME.x;
float VATEndFrame=BVASNAME.y;
float VATOffsetFrame=BVASNAME.z;
float VATSpeed=BVASNAME.w;
float totalFrames=VATEndFrame-VATStartFrame+1.0;
#ifdef INSTANCES
float time=bakedVertexAnimationTimeInstanced*VATSpeed/totalFrames;
#else
float time=bakedVertexAnimationTime*VATSpeed/totalFrames;
#endif

float frameCorrection=time<1.0 ? 0.0 : 1.0;
float numOfFrames=totalFrames-frameCorrection;
float VATFrameNum=fract(time)*numOfFrames;
VATFrameNum=mod(VATFrameNum+VATOffsetFrame,numOfFrames);
VATFrameNum=floor(VATFrameNum);
VATFrameNum+=VATStartFrame+frameCorrection;
mat4 VATInfluence;
VATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[0],VATFrameNum)*matricesWeights[0];
#if NUM_BONE_INFLUENCERS>1
VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[1],VATFrameNum)*matricesWeights[1];
#endif
#if NUM_BONE_INFLUENCERS>2
VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[2],VATFrameNum)*matricesWeights[2];
#endif
#if NUM_BONE_INFLUENCERS>3
VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[3],VATFrameNum)*matricesWeights[3];
#endif
#if NUM_BONE_INFLUENCERS>4
VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[0],VATFrameNum)*matricesWeightsExtra[0];
#endif
#if NUM_BONE_INFLUENCERS>5
VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[1],VATFrameNum)*matricesWeightsExtra[1];
#endif
#if NUM_BONE_INFLUENCERS>6
VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[2],VATFrameNum)*matricesWeightsExtra[2];
#endif
#if NUM_BONE_INFLUENCERS>7
VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[3],VATFrameNum)*matricesWeightsExtra[3];
#endif
finalWorld=finalWorld*VATInfluence;
}
#endif`;
ShaderStore.IncludesShadersStore[name$2v] = shader$2v;
var name$2u = "shadowMapVertexNormalBias"
  , shader$2u = `
#if SM_NORMALBIAS == 1
#if SM_DIRECTIONINLIGHTDATA == 1
vec3 worldLightDirSM=normalize(-lightDataSM.xyz);
#else
vec3 directionToLightSM=lightDataSM.xyz-worldPos.xyz;
vec3 worldLightDirSM=normalize(directionToLightSM);
#endif
float ndlSM=dot(vNormalW,worldLightDirSM);
float sinNLSM=sqrt(1.0-ndlSM*ndlSM);
float normalBiasSM=biasAndScaleSM.y*sinNLSM;
worldPos.xyz-=vNormalW*normalBiasSM;
#endif
`;
ShaderStore.IncludesShadersStore[name$2u] = shader$2u;
var name$2t = "shadowMapVertexMetric"
  , shader$2t = `#if SM_USEDISTANCE == 1
vPositionWSM=worldPos.xyz;
#endif
#if SM_DEPTHTEXTURE == 1
#ifdef IS_NDC_HALF_ZRANGE
#define BIASFACTOR 0.5
#else
#define BIASFACTOR 1.0
#endif

#ifdef USE_REVERSE_DEPTHBUFFER
gl_Position.z-=biasAndScaleSM.x*gl_Position.w*BIASFACTOR;
#else
gl_Position.z+=biasAndScaleSM.x*gl_Position.w*BIASFACTOR;
#endif
#endif
#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP == 1
zSM=gl_Position.z;
gl_Position.z=0.0;
#elif SM_USEDISTANCE == 0

#ifdef USE_REVERSE_DEPTHBUFFER
vDepthMetricSM=(-gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;
#else
vDepthMetricSM=(gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;
#endif
#endif
`;
ShaderStore.IncludesShadersStore[name$2t] = shader$2t;
var name$2s = "clipPlaneVertex"
  , shader$2s = `#ifdef CLIPPLANE
fClipDistance=dot(worldPos,vClipPlane);
#endif
#ifdef CLIPPLANE2
fClipDistance2=dot(worldPos,vClipPlane2);
#endif
#ifdef CLIPPLANE3
fClipDistance3=dot(worldPos,vClipPlane3);
#endif
#ifdef CLIPPLANE4
fClipDistance4=dot(worldPos,vClipPlane4);
#endif
#ifdef CLIPPLANE5
fClipDistance5=dot(worldPos,vClipPlane5);
#endif
#ifdef CLIPPLANE6
fClipDistance6=dot(worldPos,vClipPlane6);
#endif`;
ShaderStore.IncludesShadersStore[name$2s] = shader$2s;
var name$2r = "shadowMapVertexShader"
  , shader$2r = `
attribute vec3 position;
#ifdef NORMAL
attribute vec3 normal;
#endif
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]


#ifdef INSTANCES
attribute vec4 world0;
attribute vec4 world1;
attribute vec4 world2;
attribute vec4 world3;
#endif
#include<helperFunctions>
#include<__decl__shadowMapVertex>
#ifdef ALPHATEST
varying vec2 vUV;
uniform mat4 diffuseMatrix;
#ifdef UV1
attribute vec2 uv;
#endif
#ifdef UV2
attribute vec2 uv2;
#endif
#endif
#include<shadowMapVertexExtraDeclaration>
#include<clipPlaneVertexDeclaration>
void main(void)
{
vec3 positionUpdated=position;
#ifdef UV1
vec2 uvUpdated=uv;
#endif
#ifdef NORMAL
vec3 normalUpdated=normal;
#endif
#include<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
#include<instancesVertex>
#include<bonesVertex>
#include<bakedVertexAnimation>
vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);
#ifdef NORMAL
mat3 normWorldSM=mat3(finalWorld);
#if defined(INSTANCES) && defined(THIN_INSTANCES)
vec3 vNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));
vNormalW=normalize(normWorldSM*vNormalW);
#else
#ifdef NONUNIFORMSCALING
normWorldSM=transposeMat3(inverseMat3(normWorldSM));
#endif
vec3 vNormalW=normalize(normWorldSM*normalUpdated);
#endif
#endif
#include<shadowMapVertexNormalBias>

gl_Position=viewProjection*worldPos;
#include<shadowMapVertexMetric>
#ifdef ALPHATEST
#ifdef UV1
vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));
#endif
#ifdef UV2
vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));
#endif
#endif
#include<clipPlaneVertex>
}`;
ShaderStore.ShadersStore[name$2r] = shader$2r;
var name$2q = "depthBoxBlurPixelShader"
  , shader$2q = `
varying vec2 vUV;
uniform sampler2D textureSampler;

uniform vec2 screenSize;
void main(void)
{
vec4 colorDepth=vec4(0.0);
for (int x=-OFFSET; x<=OFFSET; x++)
for (int y=-OFFSET; y<=OFFSET; y++)
colorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);
gl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));
}`;
ShaderStore.ShadersStore[name$2q] = shader$2q;
var name$2p = "shadowMapFragmentSoftTransparentShadow"
  , shader$2p = `#if SM_SOFTTRANSPARENTSHADOW == 1
if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM*alpha) discard;
#endif
`;
ShaderStore.IncludesShadersStore[name$2p] = shader$2p;
var ShadowGenerator = function() {
    function i(e, t, r) {
        this.onBeforeShadowMapRenderObservable = new Observable,
        this.onAfterShadowMapRenderObservable = new Observable,
        this.onBeforeShadowMapRenderMeshObservable = new Observable,
        this.onAfterShadowMapRenderMeshObservable = new Observable,
        this._bias = 5e-5,
        this._normalBias = 0,
        this._blurBoxOffset = 1,
        this._blurScale = 2,
        this._blurKernel = 1,
        this._useKernelBlur = !1,
        this._filter = i.FILTER_NONE,
        this._filteringQuality = i.QUALITY_HIGH,
        this._contactHardeningLightSizeUVRatio = .1,
        this._darkness = 0,
        this._transparencyShadow = !1,
        this.enableSoftTransparentShadow = !1,
        this.frustumEdgeFalloff = 0,
        this.forceBackFacesOnly = !1,
        this._lightDirection = Vector3.Zero(),
        this._viewMatrix = Matrix.Zero(),
        this._projectionMatrix = Matrix.Zero(),
        this._transformMatrix = Matrix.Zero(),
        this._cachedPosition = new Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),
        this._cachedDirection = new Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),
        this._currentFaceIndex = 0,
        this._currentFaceIndexCache = 0,
        this._defaultTextureMatrix = Matrix.Identity(),
        this._mapSize = e,
        this._light = t,
        this._scene = t.getScene(),
        t._shadowGenerator = this,
        this.id = t.id,
        this._useUBO = this._scene.getEngine().supportsUniformBuffers,
        this._useUBO && (this._sceneUBOs = [],
        this._sceneUBOs.push(this._scene.createSceneUniformBuffer('Scene for Shadow Generator (light "' + this._light.name + '")'))),
        i._SceneComponentInitialization(this._scene);
        var n = this._scene.getEngine().getCaps();
        r ? n.textureFloatRender && n.textureFloatLinearFiltering ? this._textureType = 1 : n.textureHalfFloatRender && n.textureHalfFloatLinearFiltering ? this._textureType = 2 : this._textureType = 0 : n.textureHalfFloatRender && n.textureHalfFloatLinearFiltering ? this._textureType = 2 : n.textureFloatRender && n.textureFloatLinearFiltering ? this._textureType = 1 : this._textureType = 0,
        this._initializeGenerator(),
        this._applyFilterValues()
    }
    return Object.defineProperty(i.prototype, "bias", {
        get: function() {
            return this._bias
        },
        set: function(e) {
            this._bias = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "normalBias", {
        get: function() {
            return this._normalBias
        },
        set: function(e) {
            this._normalBias = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "blurBoxOffset", {
        get: function() {
            return this._blurBoxOffset
        },
        set: function(e) {
            this._blurBoxOffset !== e && (this._blurBoxOffset = e,
            this._disposeBlurPostProcesses())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "blurScale", {
        get: function() {
            return this._blurScale
        },
        set: function(e) {
            this._blurScale !== e && (this._blurScale = e,
            this._disposeBlurPostProcesses())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "blurKernel", {
        get: function() {
            return this._blurKernel
        },
        set: function(e) {
            this._blurKernel !== e && (this._blurKernel = e,
            this._disposeBlurPostProcesses())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "useKernelBlur", {
        get: function() {
            return this._useKernelBlur
        },
        set: function(e) {
            this._useKernelBlur !== e && (this._useKernelBlur = e,
            this._disposeBlurPostProcesses())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "depthScale", {
        get: function() {
            return this._depthScale !== void 0 ? this._depthScale : this._light.getDepthScale()
        },
        set: function(e) {
            this._depthScale = e
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype._validateFilter = function(e) {
        return e
    }
    ,
    Object.defineProperty(i.prototype, "filter", {
        get: function() {
            return this._filter
        },
        set: function(e) {
            if (e = this._validateFilter(e),
            this._light.needCube()) {
                if (e === i.FILTER_BLUREXPONENTIALSHADOWMAP) {
                    this.useExponentialShadowMap = !0;
                    return
                } else if (e === i.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
                    this.useCloseExponentialShadowMap = !0;
                    return
                } else if (e === i.FILTER_PCF || e === i.FILTER_PCSS) {
                    this.usePoissonSampling = !0;
                    return
                }
            }
            if ((e === i.FILTER_PCF || e === i.FILTER_PCSS) && !this._scene.getEngine()._features.supportShadowSamplers) {
                this.usePoissonSampling = !0;
                return
            }
            this._filter !== e && (this._filter = e,
            this._disposeBlurPostProcesses(),
            this._applyFilterValues(),
            this._light._markMeshesAsLightDirty())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "usePoissonSampling", {
        get: function() {
            return this.filter === i.FILTER_POISSONSAMPLING
        },
        set: function(e) {
            var t = this._validateFilter(i.FILTER_POISSONSAMPLING);
            !e && this.filter !== i.FILTER_POISSONSAMPLING || (this.filter = e ? t : i.FILTER_NONE)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "useExponentialShadowMap", {
        get: function() {
            return this.filter === i.FILTER_EXPONENTIALSHADOWMAP
        },
        set: function(e) {
            var t = this._validateFilter(i.FILTER_EXPONENTIALSHADOWMAP);
            !e && this.filter !== i.FILTER_EXPONENTIALSHADOWMAP || (this.filter = e ? t : i.FILTER_NONE)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "useBlurExponentialShadowMap", {
        get: function() {
            return this.filter === i.FILTER_BLUREXPONENTIALSHADOWMAP
        },
        set: function(e) {
            var t = this._validateFilter(i.FILTER_BLUREXPONENTIALSHADOWMAP);
            !e && this.filter !== i.FILTER_BLUREXPONENTIALSHADOWMAP || (this.filter = e ? t : i.FILTER_NONE)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "useCloseExponentialShadowMap", {
        get: function() {
            return this.filter === i.FILTER_CLOSEEXPONENTIALSHADOWMAP
        },
        set: function(e) {
            var t = this._validateFilter(i.FILTER_CLOSEEXPONENTIALSHADOWMAP);
            !e && this.filter !== i.FILTER_CLOSEEXPONENTIALSHADOWMAP || (this.filter = e ? t : i.FILTER_NONE)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "useBlurCloseExponentialShadowMap", {
        get: function() {
            return this.filter === i.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP
        },
        set: function(e) {
            var t = this._validateFilter(i.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP);
            !e && this.filter !== i.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP || (this.filter = e ? t : i.FILTER_NONE)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "usePercentageCloserFiltering", {
        get: function() {
            return this.filter === i.FILTER_PCF
        },
        set: function(e) {
            var t = this._validateFilter(i.FILTER_PCF);
            !e && this.filter !== i.FILTER_PCF || (this.filter = e ? t : i.FILTER_NONE)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "filteringQuality", {
        get: function() {
            return this._filteringQuality
        },
        set: function(e) {
            this._filteringQuality !== e && (this._filteringQuality = e,
            this._disposeBlurPostProcesses(),
            this._applyFilterValues(),
            this._light._markMeshesAsLightDirty())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "useContactHardeningShadow", {
        get: function() {
            return this.filter === i.FILTER_PCSS
        },
        set: function(e) {
            var t = this._validateFilter(i.FILTER_PCSS);
            !e && this.filter !== i.FILTER_PCSS || (this.filter = e ? t : i.FILTER_NONE)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "contactHardeningLightSizeUVRatio", {
        get: function() {
            return this._contactHardeningLightSizeUVRatio
        },
        set: function(e) {
            this._contactHardeningLightSizeUVRatio = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "darkness", {
        get: function() {
            return this._darkness
        },
        set: function(e) {
            this.setDarkness(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.getDarkness = function() {
        return this._darkness
    }
    ,
    i.prototype.setDarkness = function(e) {
        return e >= 1 ? this._darkness = 1 : e <= 0 ? this._darkness = 0 : this._darkness = e,
        this
    }
    ,
    Object.defineProperty(i.prototype, "transparencyShadow", {
        get: function() {
            return this._transparencyShadow
        },
        set: function(e) {
            this.setTransparencyShadow(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.setTransparencyShadow = function(e) {
        return this._transparencyShadow = e,
        this
    }
    ,
    i.prototype.getShadowMap = function() {
        return this._shadowMap
    }
    ,
    i.prototype.getShadowMapForRendering = function() {
        return this._shadowMap2 ? this._shadowMap2 : this._shadowMap
    }
    ,
    i.prototype.getClassName = function() {
        return i.CLASSNAME
    }
    ,
    i.prototype.addShadowCaster = function(e, t) {
        if (t === void 0 && (t = !0),
        !this._shadowMap)
            return this;
        if (this._shadowMap.renderList || (this._shadowMap.renderList = []),
        this._shadowMap.renderList.indexOf(e) === -1 && this._shadowMap.renderList.push(e),
        t)
            for (var r = 0, n = e.getChildMeshes(); r < n.length; r++) {
                var o = n[r];
                this._shadowMap.renderList.indexOf(o) === -1 && this._shadowMap.renderList.push(o)
            }
        return this
    }
    ,
    i.prototype.removeShadowCaster = function(e, t) {
        if (t === void 0 && (t = !0),
        !this._shadowMap || !this._shadowMap.renderList)
            return this;
        var r = this._shadowMap.renderList.indexOf(e);
        if (r !== -1 && this._shadowMap.renderList.splice(r, 1),
        t)
            for (var n = 0, o = e.getChildren(); n < o.length; n++) {
                var a = o[n];
                this.removeShadowCaster(a)
            }
        return this
    }
    ,
    i.prototype.getLight = function() {
        return this._light
    }
    ,
    Object.defineProperty(i.prototype, "mapSize", {
        get: function() {
            return this._mapSize
        },
        set: function(e) {
            this._mapSize = e,
            this._light._markMeshesAsLightDirty(),
            this.recreateShadowMap()
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype._initializeGenerator = function() {
        this._light._markMeshesAsLightDirty(),
        this._initializeShadowMap()
    }
    ,
    i.prototype._createTargetRenderTexture = function() {
        var e = this._scene.getEngine();
        e._features.supportDepthStencilTexture ? (this._shadowMap = new RenderTargetTexture(this._light.name + "_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube(),void 0,!1,!1),
        this._shadowMap.createDepthStencilTexture(e.useReverseDepthBuffer ? 516 : 513, !0)) : this._shadowMap = new RenderTargetTexture(this._light.name + "_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube())
    }
    ,
    i.prototype._initializeShadowMap = function() {
        var e = this;
        if (this._createTargetRenderTexture(),
        this._shadowMap !== null) {
            this._shadowMap.wrapU = Texture.CLAMP_ADDRESSMODE,
            this._shadowMap.wrapV = Texture.CLAMP_ADDRESSMODE,
            this._shadowMap.anisotropicFilteringLevel = 1,
            this._shadowMap.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE),
            this._shadowMap.renderParticles = !1,
            this._shadowMap.ignoreCameraViewport = !0,
            this._storedUniqueId && (this._shadowMap.uniqueId = this._storedUniqueId),
            this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this),
            this._shadowMap.customIsReadyFunction = function(a, s) {
                return !0
            }
            ;
            var t = this._scene.getEngine();
            this._shadowMap.onBeforeBindObservable.add(function() {
                var a;
                e._currentSceneUBO = e._scene.getSceneUniformBuffer(),
                (a = t._debugPushGroup) === null || a === void 0 || a.call(t, "shadow map generation for pass id " + t.currentRenderPassId, 1)
            }),
            this._shadowMap.onBeforeRenderObservable.add(function(a) {
                e._sceneUBOs && e._scene.setSceneUniformBuffer(e._sceneUBOs[0]),
                e._currentFaceIndex = a,
                e._filter === i.FILTER_PCF && t.setColorWrite(!1),
                e.getTransformMatrix(),
                e._scene.setTransformMatrix(e._viewMatrix, e._projectionMatrix),
                e._useUBO && (e._scene.getSceneUniformBuffer().unbindEffect(),
                e._scene.finalizeSceneUbo())
            }),
            this._shadowMap.onAfterUnbindObservable.add(function() {
                var a, s;
                if (e._sceneUBOs && e._scene.setSceneUniformBuffer(e._currentSceneUBO),
                e._scene.updateTransformMatrix(),
                e._filter === i.FILTER_PCF && t.setColorWrite(!0),
                !e.useBlurExponentialShadowMap && !e.useBlurCloseExponentialShadowMap) {
                    (a = t._debugPopGroup) === null || a === void 0 || a.call(t, 1);
                    return
                }
                var l = e.getShadowMapForRendering();
                l && (e._scene.postProcessManager.directRender(e._blurPostProcesses, l.renderTarget, !0),
                t.unBindFramebuffer(l.renderTarget, !0),
                (s = t._debugPopGroup) === null || s === void 0 || s.call(t, 1))
            });
            var r = new Color4(0,0,0,0)
              , n = new Color4(1,1,1,1);
            this._shadowMap.onClearObservable.add(function(a) {
                e._filter === i.FILTER_PCF ? a.clear(n, !1, !0, !1) : e.useExponentialShadowMap || e.useBlurExponentialShadowMap ? a.clear(r, !0, !0, !1) : a.clear(n, !0, !0, !1)
            }),
            this._shadowMap.onResizeObservable.add(function(a) {
                e._storedUniqueId = e._shadowMap.uniqueId,
                e._mapSize = a.getRenderSize(),
                e._light._markMeshesAsLightDirty(),
                e.recreateShadowMap()
            });
            for (var o = RenderingManager.MIN_RENDERINGGROUPS; o < RenderingManager.MAX_RENDERINGGROUPS; o++)
                this._shadowMap.setRenderingAutoClearDepthStencil(o, !1)
        }
    }
    ,
    i.prototype._initializeBlurRTTAndPostProcesses = function() {
        var e = this
          , t = this._scene.getEngine()
          , r = this._mapSize / this.blurScale;
        (!this.useKernelBlur || this.blurScale !== 1) && (this._shadowMap2 = new RenderTargetTexture(this._light.name + "_shadowMap2",r,this._scene,!1,!0,this._textureType,void 0,void 0,!1),
        this._shadowMap2.wrapU = Texture.CLAMP_ADDRESSMODE,
        this._shadowMap2.wrapV = Texture.CLAMP_ADDRESSMODE,
        this._shadowMap2.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE)),
        this.useKernelBlur ? (this._kernelBlurXPostprocess = new BlurPostProcess(this._light.name + "KernelBlurX",new Vector2(1,0),this.blurKernel,1,null,Texture.BILINEAR_SAMPLINGMODE,t,!1,this._textureType),
        this._kernelBlurXPostprocess.width = r,
        this._kernelBlurXPostprocess.height = r,
        this._kernelBlurXPostprocess.externalTextureSamplerBinding = !0,
        this._kernelBlurXPostprocess.onApplyObservable.add(function(n) {
            n.setTexture("textureSampler", e._shadowMap)
        }),
        this._kernelBlurYPostprocess = new BlurPostProcess(this._light.name + "KernelBlurY",new Vector2(0,1),this.blurKernel,1,null,Texture.BILINEAR_SAMPLINGMODE,t,!1,this._textureType),
        this._kernelBlurXPostprocess.autoClear = !1,
        this._kernelBlurYPostprocess.autoClear = !1,
        this._textureType === 0 && (this._kernelBlurXPostprocess.packedFloat = !0,
        this._kernelBlurYPostprocess.packedFloat = !0),
        this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess]) : (this._boxBlurPostprocess = new PostProcess(this._light.name + "DepthBoxBlur","depthBoxBlur",["screenSize", "boxOffset"],[],1,null,Texture.BILINEAR_SAMPLINGMODE,t,!1,"#define OFFSET " + this._blurBoxOffset,this._textureType),
        this._boxBlurPostprocess.externalTextureSamplerBinding = !0,
        this._boxBlurPostprocess.onApplyObservable.add(function(n) {
            n.setFloat2("screenSize", r, r),
            n.setTexture("textureSampler", e._shadowMap)
        }),
        this._boxBlurPostprocess.autoClear = !1,
        this._blurPostProcesses = [this._boxBlurPostprocess])
    }
    ,
    i.prototype._renderForShadowMap = function(e, t, r, n) {
        var o;
        if (n.length)
            for (o = 0; o < n.length; o++)
                this._renderSubMeshForShadowMap(n.data[o]);
        for (o = 0; o < e.length; o++)
            this._renderSubMeshForShadowMap(e.data[o]);
        for (o = 0; o < t.length; o++)
            this._renderSubMeshForShadowMap(t.data[o]);
        if (this._transparencyShadow)
            for (o = 0; o < r.length; o++)
                this._renderSubMeshForShadowMap(r.data[o], !0);
        else
            for (o = 0; o < r.length; o++)
                r.data[o].getEffectiveMesh()._internalAbstractMeshDataInfo._isActiveIntermediate = !1
    }
    ,
    i.prototype._bindCustomEffectForRenderSubMeshForShadowMap = function(e, t, r) {
        t.setMatrix("viewProjection", this.getTransformMatrix())
    }
    ,
    i.prototype._renderSubMeshForShadowMap = function(e, t) {
        var r, n;
        t === void 0 && (t = !1);
        var o = e.getRenderingMesh()
          , a = e.getEffectiveMesh()
          , s = this._scene
          , l = s.getEngine()
          , u = e.getMaterial();
        if (a._internalAbstractMeshDataInfo._isActiveIntermediate = !1,
        !(!u || e.verticesCount === 0 || e._renderId === s.getRenderId())) {
            var c = a._getWorldMatrixDeterminant() < 0
              , h = (r = o.overrideMaterialSideOrientation) !== null && r !== void 0 ? r : u.sideOrientation;
            (s.useRightHandedSystem && !c || !s.useRightHandedSystem && c) && (h = h === 0 ? 1 : 0);
            var f = h === 0;
            l.setState(u.backFaceCulling, void 0, void 0, f, u.cullBackFaces);
            var d = o._getInstancesRenderList(e._id, !!e.getReplacementMesh());
            if (!d.mustReturn) {
                var _ = l.getCaps().instancedArrays && (d.visibleInstances[e._id] !== null && d.visibleInstances[e._id] !== void 0 || o.hasThinInstances);
                if (!(this.customAllowRendering && !this.customAllowRendering(e)))
                    if (this.isReady(e, _, t)) {
                        e._renderId = s.getRenderId();
                        var g = u.shadowDepthWrapper
                          , m = (n = g == null ? void 0 : g.getEffect(e, this, l.currentRenderPassId)) !== null && n !== void 0 ? n : e._getDrawWrapper()
                          , v = DrawWrapper.GetEffect(m);
                        if (l.enableEffect(m),
                        _ || o._bind(e, v, u.fillMode),
                        this.getTransformMatrix(),
                        v.setFloat3("biasAndScaleSM", this.bias, this.normalBias, this.depthScale),
                        this.getLight().getTypeID() === Light.LIGHTTYPEID_DIRECTIONALLIGHT ? v.setVector3("lightDataSM", this._cachedDirection) : v.setVector3("lightDataSM", this._cachedPosition),
                        s.activeCamera && v.setFloat2("depthValuesSM", this.getLight().getDepthMinZ(s.activeCamera), this.getLight().getDepthMinZ(s.activeCamera) + this.getLight().getDepthMaxZ(s.activeCamera)),
                        t && this.enableSoftTransparentShadow && v.setFloat("softTransparentShadowSM", a.visibility * u.alpha),
                        g)
                            e._setMainDrawWrapperOverride(m),
                            g.standalone ? g.baseMaterial.bindForSubMesh(a.getWorldMatrix(), o, e) : u.bindForSubMesh(a.getWorldMatrix(), o, e),
                            e._setMainDrawWrapperOverride(null);
                        else {
                            if (u && u.needAlphaTesting()) {
                                var y = u.getAlphaTestTexture();
                                y && (v.setTexture("diffuseSampler", y),
                                v.setMatrix("diffuseMatrix", y.getTextureMatrix() || this._defaultTextureMatrix))
                            }
                            if (o.useBones && o.computeBonesUsingShaders && o.skeleton) {
                                var b = o.skeleton;
                                if (b.isUsingTextureForMatrices) {
                                    var T = b.getTransformMatrixTexture(o);
                                    if (!T)
                                        return;
                                    v.setTexture("boneSampler", T),
                                    v.setFloat("boneTextureWidth", 4 * (b.bones.length + 1))
                                } else
                                    v.setMatrices("mBones", b.getTransformMatrices(o))
                            }
                            MaterialHelper.BindMorphTargetParameters(o, v),
                            o.morphTargetManager && o.morphTargetManager.isUsingTextureForTargets && o.morphTargetManager._bind(v),
                            MaterialHelper.BindClipPlane(v, s)
                        }
                        !this._useUBO && !g && this._bindCustomEffectForRenderSubMeshForShadowMap(e, v, a),
                        MaterialHelper.BindSceneUniformBuffer(v, this._scene.getSceneUniformBuffer()),
                        this._scene.getSceneUniformBuffer().bindUniformBuffer();
                        var C = a.getWorldMatrix();
                        _ && (a.getMeshUniformBuffer().bindToEffect(v, "Mesh"),
                        a.transferToEffect(C)),
                        this.forceBackFacesOnly && l.setState(!0, 0, !1, !0, u.cullBackFaces),
                        this.onBeforeShadowMapRenderMeshObservable.notifyObservers(o),
                        this.onBeforeShadowMapRenderObservable.notifyObservers(v),
                        o._processRendering(a, e, v, u.fillMode, d, _, function(A, S, P, R) {
                            R && a !== R ? (R.getMeshUniformBuffer().bindToEffect(v, "Mesh"),
                            R.transferToEffect(S)) : (a.getMeshUniformBuffer().bindToEffect(v, "Mesh"),
                            a.transferToEffect(C))
                        }),
                        this.forceBackFacesOnly && l.setState(!0, 0, !1, !1, u.cullBackFaces),
                        this.onAfterShadowMapRenderObservable.notifyObservers(v),
                        this.onAfterShadowMapRenderMeshObservable.notifyObservers(o)
                    } else
                        this._shadowMap && this._shadowMap.resetRefreshCounter()
            }
        }
    }
    ,
    i.prototype._applyFilterValues = function() {
        !this._shadowMap || (this.filter === i.FILTER_NONE || this.filter === i.FILTER_PCSS ? this._shadowMap.updateSamplingMode(Texture.NEAREST_SAMPLINGMODE) : this._shadowMap.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE))
    }
    ,
    i.prototype.forceCompilation = function(e, t) {
        var r = this
          , n = __assign({
            useInstances: !1
        }, t)
          , o = this.getShadowMap();
        if (!o) {
            e && e(this);
            return
        }
        var a = o.renderList;
        if (!a) {
            e && e(this);
            return
        }
        for (var s = new Array, l = 0, u = a; l < u.length; l++) {
            var c = u[l];
            s.push.apply(s, c.subMeshes)
        }
        if (s.length === 0) {
            e && e(this);
            return
        }
        var h = 0
          , f = function() {
            var d, _;
            if (!(!r._scene || !r._scene.getEngine())) {
                for (; r.isReady(s[h], n.useInstances, (_ = (d = s[h].getMaterial()) === null || d === void 0 ? void 0 : d.needAlphaBlendingForMesh(s[h].getMesh())) !== null && _ !== void 0 ? _ : !1); )
                    if (h++,
                    h >= s.length) {
                        e && e(r);
                        return
                    }
                setTimeout(f, 16)
            }
        };
        f()
    }
    ,
    i.prototype.forceCompilationAsync = function(e) {
        var t = this;
        return new Promise(function(r) {
            t.forceCompilation(function() {
                r()
            }, e)
        }
        )
    }
    ,
    i.prototype._isReadyCustomDefines = function(e, t, r) {}
    ,
    i.prototype._prepareShadowDefines = function(e, t, r, n) {
        r.push("#define SM_FLOAT " + (this._textureType !== 0 ? "1" : "0")),
        r.push("#define SM_ESM " + (this.useExponentialShadowMap || this.useBlurExponentialShadowMap ? "1" : "0")),
        r.push("#define SM_DEPTHTEXTURE " + (this.usePercentageCloserFiltering || this.useContactHardeningShadow ? "1" : "0"));
        var o = e.getMesh();
        return r.push("#define SM_NORMALBIAS " + (this.normalBias && o.isVerticesDataPresent(VertexBuffer.NormalKind) ? "1" : "0")),
        r.push("#define SM_DIRECTIONINLIGHTDATA " + (this.getLight().getTypeID() === Light.LIGHTTYPEID_DIRECTIONALLIGHT ? "1" : "0")),
        r.push("#define SM_USEDISTANCE " + (this._light.needCube() ? "1" : "0")),
        r.push("#define SM_SOFTTRANSPARENTSHADOW " + (this.enableSoftTransparentShadow && n ? "1" : "0")),
        this._isReadyCustomDefines(r, e, t),
        r
    }
    ,
    i.prototype.isReady = function(e, t, r) {
        var n = e.getMaterial()
          , o = n == null ? void 0 : n.shadowDepthWrapper
          , a = [];
        if (this._prepareShadowDefines(e, t, a, r),
        o) {
            if (!o.isReadyForSubMesh(e, a, this, t, this._scene.getEngine().currentRenderPassId))
                return !1
        } else {
            var s = e._getDrawWrapper(void 0, !0)
              , l = s.effect
              , u = s.defines
              , c = [VertexBuffer.PositionKind]
              , h = e.getMesh();
            if (this.normalBias && h.isVerticesDataPresent(VertexBuffer.NormalKind) && (c.push(VertexBuffer.NormalKind),
            a.push("#define NORMAL"),
            h.nonUniformScaling && a.push("#define NONUNIFORMSCALING")),
            n && n.needAlphaTesting()) {
                var f = n.getAlphaTestTexture();
                if (f) {
                    if (!f.isReady())
                        return !1;
                    a.push("#define ALPHATEST"),
                    h.isVerticesDataPresent(VertexBuffer.UVKind) && (c.push(VertexBuffer.UVKind),
                    a.push("#define UV1")),
                    h.isVerticesDataPresent(VertexBuffer.UV2Kind) && f.coordinatesIndex === 1 && (c.push(VertexBuffer.UV2Kind),
                    a.push("#define UV2"))
                }
            }
            var d = new EffectFallbacks;
            if (h.useBones && h.computeBonesUsingShaders && h.skeleton) {
                c.push(VertexBuffer.MatricesIndicesKind),
                c.push(VertexBuffer.MatricesWeightsKind),
                h.numBoneInfluencers > 4 && (c.push(VertexBuffer.MatricesIndicesExtraKind),
                c.push(VertexBuffer.MatricesWeightsExtraKind));
                var _ = h.skeleton;
                a.push("#define NUM_BONE_INFLUENCERS " + h.numBoneInfluencers),
                h.numBoneInfluencers > 0 && d.addCPUSkinningFallback(0, h),
                _.isUsingTextureForMatrices ? a.push("#define BONETEXTURE") : a.push("#define BonesPerMesh " + (_.bones.length + 1))
            } else
                a.push("#define NUM_BONE_INFLUENCERS 0");
            var g = h.morphTargetManager
              , m = 0;
            g && g.numInfluencers > 0 && (a.push("#define MORPHTARGETS"),
            m = g.numInfluencers,
            a.push("#define NUM_MORPH_INFLUENCERS " + m),
            g.isUsingTextureForTargets && a.push("#define MORPHTARGETS_TEXTURE"),
            MaterialHelper.PrepareAttributesForMorphTargetsInfluencers(c, h, m));
            var v = this._scene;
            if (v.clipPlane && a.push("#define CLIPPLANE"),
            v.clipPlane2 && a.push("#define CLIPPLANE2"),
            v.clipPlane3 && a.push("#define CLIPPLANE3"),
            v.clipPlane4 && a.push("#define CLIPPLANE4"),
            v.clipPlane5 && a.push("#define CLIPPLANE5"),
            v.clipPlane6 && a.push("#define CLIPPLANE6"),
            t && (a.push("#define INSTANCES"),
            MaterialHelper.PushAttributesForInstances(c),
            e.getRenderingMesh().hasThinInstances && a.push("#define THIN_INSTANCES")),
            this.customShaderOptions && this.customShaderOptions.defines)
                for (var y = 0, b = this.customShaderOptions.defines; y < b.length; y++) {
                    var T = b[y];
                    a.indexOf(T) === -1 && a.push(T)
                }
            var C = a.join(`
`);
            if (u !== C) {
                u = C;
                var A = "shadowMap"
                  , S = ["world", "mBones", "viewProjection", "diffuseMatrix", "lightDataSM", "depthValuesSM", "biasAndScaleSM", "morphTargetInfluences", "boneTextureWidth", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "vClipPlane5", "vClipPlane6", "softTransparentShadowSM", "morphTargetTextureInfo", "morphTargetTextureIndices"]
                  , P = ["diffuseSampler", "boneSampler", "morphTargets"]
                  , R = ["Scene", "Mesh"];
                if (this.customShaderOptions) {
                    if (A = this.customShaderOptions.shaderName,
                    this.customShaderOptions.attributes)
                        for (var M = 0, x = this.customShaderOptions.attributes; M < x.length; M++) {
                            var I = x[M];
                            c.indexOf(I) === -1 && c.push(I)
                        }
                    if (this.customShaderOptions.uniforms)
                        for (var w = 0, O = this.customShaderOptions.uniforms; w < O.length; w++) {
                            var D = O[w];
                            S.indexOf(D) === -1 && S.push(D)
                        }
                    if (this.customShaderOptions.samplers)
                        for (var F = 0, V = this.customShaderOptions.samplers; F < V.length; F++) {
                            var N = V[F];
                            P.indexOf(N) === -1 && P.push(N)
                        }
                }
                var L = this._scene.getEngine();
                l = L.createEffect(A, {
                    attributes: c,
                    uniformsNames: S,
                    uniformBuffersNames: R,
                    samplers: P,
                    defines: C,
                    fallbacks: d,
                    onCompiled: null,
                    onError: null,
                    indexParameters: {
                        maxSimultaneousMorphTargets: m
                    }
                }, L),
                s.setEffect(l, u)
            }
            if (!l.isReady())
                return !1
        }
        return (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) && (!this._blurPostProcesses || !this._blurPostProcesses.length) && this._initializeBlurRTTAndPostProcesses(),
        !(this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady() || this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady() || this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady())
    }
    ,
    i.prototype.prepareDefines = function(e, t) {
        var r = this._scene
          , n = this._light;
        !r.shadowsEnabled || !n.shadowEnabled || (e["SHADOW" + t] = !0,
        this.useContactHardeningShadow ? (e["SHADOWPCSS" + t] = !0,
        this._filteringQuality === i.QUALITY_LOW ? e["SHADOWLOWQUALITY" + t] = !0 : this._filteringQuality === i.QUALITY_MEDIUM && (e["SHADOWMEDIUMQUALITY" + t] = !0)) : this.usePercentageCloserFiltering ? (e["SHADOWPCF" + t] = !0,
        this._filteringQuality === i.QUALITY_LOW ? e["SHADOWLOWQUALITY" + t] = !0 : this._filteringQuality === i.QUALITY_MEDIUM && (e["SHADOWMEDIUMQUALITY" + t] = !0)) : this.usePoissonSampling ? e["SHADOWPOISSON" + t] = !0 : this.useExponentialShadowMap || this.useBlurExponentialShadowMap ? e["SHADOWESM" + t] = !0 : (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) && (e["SHADOWCLOSEESM" + t] = !0),
        n.needCube() && (e["SHADOWCUBE" + t] = !0))
    }
    ,
    i.prototype.bindShadowLight = function(e, t) {
        var r = this._light
          , n = this._scene;
        if (!(!n.shadowsEnabled || !r.shadowEnabled)) {
            var o = n.activeCamera;
            if (!!o) {
                var a = this.getShadowMap();
                !a || (r.needCube() || t.setMatrix("lightMatrix" + e, this.getTransformMatrix()),
                this._filter === i.FILTER_PCF ? (t.setDepthStencilTexture("shadowSampler" + e, this.getShadowMapForRendering()),
                r._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), a.getSize().width, 1 / a.getSize().width, this.frustumEdgeFalloff, e)) : this._filter === i.FILTER_PCSS ? (t.setDepthStencilTexture("shadowSampler" + e, this.getShadowMapForRendering()),
                t.setTexture("depthSampler" + e, this.getShadowMapForRendering()),
                r._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / a.getSize().width, this._contactHardeningLightSizeUVRatio * a.getSize().width, this.frustumEdgeFalloff, e)) : (t.setTexture("shadowSampler" + e, this.getShadowMapForRendering()),
                r._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / a.getSize().width, this.depthScale, this.frustumEdgeFalloff, e)),
                r._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(o), this.getLight().getDepthMinZ(o) + this.getLight().getDepthMaxZ(o), e))
            }
        }
    }
    ,
    i.prototype.getTransformMatrix = function() {
        var e = this._scene;
        if (this._currentRenderId === e.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex)
            return this._transformMatrix;
        this._currentRenderId = e.getRenderId(),
        this._currentFaceIndexCache = this._currentFaceIndex;
        var t = this._light.position;
        if (this._light.computeTransformedInformation() && (t = this._light.transformedPosition),
        Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection),
        Math.abs(Vector3.Dot(this._lightDirection, Vector3.Up())) === 1 && (this._lightDirection.z = 1e-13),
        this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !t.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
            this._cachedPosition.copyFrom(t),
            this._cachedDirection.copyFrom(this._lightDirection),
            Matrix.LookAtLHToRef(t, t.add(this._lightDirection), Vector3.Up(), this._viewMatrix);
            var r = this.getShadowMap();
            if (r) {
                var n = r.renderList;
                n && this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, n)
            }
            this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix)
        }
        return this._transformMatrix
    }
    ,
    i.prototype.recreateShadowMap = function() {
        var e = this._shadowMap;
        if (!!e) {
            var t = e.renderList;
            if (this._disposeRTTandPostProcesses(),
            this._initializeGenerator(),
            this.filter = this.filter,
            this._applyFilterValues(),
            t) {
                this._shadowMap.renderList || (this._shadowMap.renderList = []);
                for (var r = 0, n = t; r < n.length; r++) {
                    var o = n[r];
                    this._shadowMap.renderList.push(o)
                }
            } else
                this._shadowMap.renderList = null
        }
    }
    ,
    i.prototype._disposeBlurPostProcesses = function() {
        this._shadowMap2 && (this._shadowMap2.dispose(),
        this._shadowMap2 = null),
        this._boxBlurPostprocess && (this._boxBlurPostprocess.dispose(),
        this._boxBlurPostprocess = null),
        this._kernelBlurXPostprocess && (this._kernelBlurXPostprocess.dispose(),
        this._kernelBlurXPostprocess = null),
        this._kernelBlurYPostprocess && (this._kernelBlurYPostprocess.dispose(),
        this._kernelBlurYPostprocess = null),
        this._blurPostProcesses = []
    }
    ,
    i.prototype._disposeRTTandPostProcesses = function() {
        this._shadowMap && (this._shadowMap.dispose(),
        this._shadowMap = null),
        this._disposeBlurPostProcesses()
    }
    ,
    i.prototype._disposeSceneUBOs = function() {
        if (this._sceneUBOs) {
            for (var e = 0, t = this._sceneUBOs; e < t.length; e++) {
                var r = t[e];
                r.dispose()
            }
            this._sceneUBOs = []
        }
    }
    ,
    i.prototype.dispose = function() {
        this._disposeRTTandPostProcesses(),
        this._disposeSceneUBOs(),
        this._light && (this._light._shadowGenerator = null,
        this._light._markMeshesAsLightDirty()),
        this.onBeforeShadowMapRenderMeshObservable.clear(),
        this.onBeforeShadowMapRenderObservable.clear(),
        this.onAfterShadowMapRenderMeshObservable.clear(),
        this.onAfterShadowMapRenderObservable.clear()
    }
    ,
    i.prototype.serialize = function() {
        var e = {}
          , t = this.getShadowMap();
        if (!t)
            return e;
        if (e.className = this.getClassName(),
        e.lightId = this._light.id,
        e.id = this.id,
        e.mapSize = t.getRenderSize(),
        e.forceBackFacesOnly = this.forceBackFacesOnly,
        e.darkness = this.getDarkness(),
        e.transparencyShadow = this._transparencyShadow,
        e.frustumEdgeFalloff = this.frustumEdgeFalloff,
        e.bias = this.bias,
        e.normalBias = this.normalBias,
        e.usePercentageCloserFiltering = this.usePercentageCloserFiltering,
        e.useContactHardeningShadow = this.useContactHardeningShadow,
        e.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio,
        e.filteringQuality = this.filteringQuality,
        e.useExponentialShadowMap = this.useExponentialShadowMap,
        e.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap,
        e.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap,
        e.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap,
        e.usePoissonSampling = this.usePoissonSampling,
        e.depthScale = this.depthScale,
        e.blurBoxOffset = this.blurBoxOffset,
        e.blurKernel = this.blurKernel,
        e.blurScale = this.blurScale,
        e.useKernelBlur = this.useKernelBlur,
        e.renderList = [],
        t.renderList)
            for (var r = 0; r < t.renderList.length; r++) {
                var n = t.renderList[r];
                e.renderList.push(n.id)
            }
        return e
    }
    ,
    i.Parse = function(e, t, r) {
        for (var n = t.getLightById(e.lightId), o = r ? r(e.mapSize, n) : new i(e.mapSize,n), a = o.getShadowMap(), s = 0; s < e.renderList.length; s++) {
            var l = t.getMeshesById(e.renderList[s]);
            l.forEach(function(u) {
                !a || (a.renderList || (a.renderList = []),
                a.renderList.push(u))
            })
        }
        return e.id !== void 0 && (o.id = e.id),
        o.forceBackFacesOnly = !!e.forceBackFacesOnly,
        e.darkness !== void 0 && o.setDarkness(e.darkness),
        e.transparencyShadow && o.setTransparencyShadow(!0),
        e.frustumEdgeFalloff !== void 0 && (o.frustumEdgeFalloff = e.frustumEdgeFalloff),
        e.bias !== void 0 && (o.bias = e.bias),
        e.normalBias !== void 0 && (o.normalBias = e.normalBias),
        e.usePercentageCloserFiltering ? o.usePercentageCloserFiltering = !0 : e.useContactHardeningShadow ? o.useContactHardeningShadow = !0 : e.usePoissonSampling ? o.usePoissonSampling = !0 : e.useExponentialShadowMap ? o.useExponentialShadowMap = !0 : e.useBlurExponentialShadowMap ? o.useBlurExponentialShadowMap = !0 : e.useCloseExponentialShadowMap ? o.useCloseExponentialShadowMap = !0 : e.useBlurCloseExponentialShadowMap ? o.useBlurCloseExponentialShadowMap = !0 : e.useVarianceShadowMap ? o.useExponentialShadowMap = !0 : e.useBlurVarianceShadowMap && (o.useBlurExponentialShadowMap = !0),
        e.contactHardeningLightSizeUVRatio !== void 0 && (o.contactHardeningLightSizeUVRatio = e.contactHardeningLightSizeUVRatio),
        e.filteringQuality !== void 0 && (o.filteringQuality = e.filteringQuality),
        e.depthScale && (o.depthScale = e.depthScale),
        e.blurScale && (o.blurScale = e.blurScale),
        e.blurBoxOffset && (o.blurBoxOffset = e.blurBoxOffset),
        e.useKernelBlur && (o.useKernelBlur = e.useKernelBlur),
        e.blurKernel && (o.blurKernel = e.blurKernel),
        o
    }
    ,
    i.CLASSNAME = "ShadowGenerator",
    i.FILTER_NONE = 0,
    i.FILTER_EXPONENTIALSHADOWMAP = 1,
    i.FILTER_POISSONSAMPLING = 2,
    i.FILTER_BLUREXPONENTIALSHADOWMAP = 3,
    i.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4,
    i.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5,
    i.FILTER_PCF = 6,
    i.FILTER_PCSS = 7,
    i.QUALITY_HIGH = 0,
    i.QUALITY_MEDIUM = 1,
    i.QUALITY_LOW = 2,
    i._SceneComponentInitialization = function(e) {
        throw _WarnImport("ShadowGeneratorSceneComponent")
    }
    ,
    i
}()
  , PushMaterial = function(i) {
    __extends(e, i);
    function e(t, r, n) {
        n === void 0 && (n = !0);
        var o = i.call(this, t, r) || this;
        return o._normalMatrix = new Matrix,
        o._storeEffectOnSubMeshes = n,
        o
    }
    return e.prototype.getEffect = function() {
        return this._storeEffectOnSubMeshes ? this._activeEffect : i.prototype.getEffect.call(this)
    }
    ,
    e.prototype.isReady = function(t, r) {
        return t ? !this._storeEffectOnSubMeshes || !t.subMeshes || t.subMeshes.length === 0 ? !0 : this.isReadyForSubMesh(t, t.subMeshes[0], r) : !1
    }
    ,
    e.prototype._isReadyForSubMesh = function(t) {
        var r = t.materialDefines;
        return !!(!this.checkReadyOnEveryCall && t.effect && r && r._renderId === this.getScene().getRenderId())
    }
    ,
    e.prototype.bindOnlyWorldMatrix = function(t) {
        this._activeEffect.setMatrix("world", t)
    }
    ,
    e.prototype.bindOnlyNormalMatrix = function(t) {
        this._activeEffect.setMatrix("normalMatrix", t)
    }
    ,
    e.prototype.bind = function(t, r) {
        !r || this.bindForSubMesh(t, r, r.subMeshes[0])
    }
    ,
    e.prototype._afterBind = function(t, r) {
        r === void 0 && (r = null),
        i.prototype._afterBind.call(this, t, r),
        this.getScene()._cachedEffect = r
    }
    ,
    e.prototype._mustRebind = function(t, r, n) {
        return n === void 0 && (n = 1),
        t.isCachedMaterialInvalid(this, r, n)
    }
    ,
    e
}(Material)
  , onCreatedEffectParameters$3 = {
    effect: null,
    subMesh: null
}
  , ShaderMaterial = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a) {
        o === void 0 && (o = {}),
        a === void 0 && (a = !0);
        var s = i.call(this, t, r, a) || this;
        return s._textures = {},
        s._textureArrays = {},
        s._externalTextures = {},
        s._floats = {},
        s._ints = {},
        s._floatsArrays = {},
        s._colors3 = {},
        s._colors3Arrays = {},
        s._colors4 = {},
        s._colors4Arrays = {},
        s._vectors2 = {},
        s._vectors3 = {},
        s._vectors4 = {},
        s._matrices = {},
        s._matrixArrays = {},
        s._matrices3x3 = {},
        s._matrices2x2 = {},
        s._vectors2Arrays = {},
        s._vectors3Arrays = {},
        s._vectors4Arrays = {},
        s._uniformBuffers = {},
        s._textureSamplers = {},
        s._storageBuffers = {},
        s._cachedWorldViewMatrix = new Matrix,
        s._cachedWorldViewProjectionMatrix = new Matrix,
        s._multiview = !1,
        s._shaderPath = n,
        s._options = __assign({
            needAlphaBlending: !1,
            needAlphaTesting: !1,
            attributes: ["position", "normal", "uv"],
            uniforms: ["worldViewProjection"],
            uniformBuffers: [],
            samplers: [],
            externalTextures: [],
            samplerObjects: [],
            storageBuffers: [],
            defines: [],
            useClipPlane: !1
        }, o),
        s
    }
    return Object.defineProperty(e.prototype, "shaderPath", {
        get: function() {
            return this._shaderPath
        },
        set: function(t) {
            this._shaderPath = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "options", {
        get: function() {
            return this._options
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getClassName = function() {
        return "ShaderMaterial"
    }
    ,
    e.prototype.needAlphaBlending = function() {
        return this.alpha < 1 || this._options.needAlphaBlending
    }
    ,
    e.prototype.needAlphaTesting = function() {
        return this._options.needAlphaTesting
    }
    ,
    e.prototype._checkUniform = function(t) {
        this._options.uniforms.indexOf(t) === -1 && this._options.uniforms.push(t)
    }
    ,
    e.prototype.setTexture = function(t, r) {
        return this._options.samplers.indexOf(t) === -1 && this._options.samplers.push(t),
        this._textures[t] = r,
        this
    }
    ,
    e.prototype.setTextureArray = function(t, r) {
        return this._options.samplers.indexOf(t) === -1 && this._options.samplers.push(t),
        this._checkUniform(t),
        this._textureArrays[t] = r,
        this
    }
    ,
    e.prototype.setExternalTexture = function(t, r) {
        return this._options.externalTextures.indexOf(t) === -1 && this._options.externalTextures.push(t),
        this._externalTextures[t] = r,
        this
    }
    ,
    e.prototype.setFloat = function(t, r) {
        return this._checkUniform(t),
        this._floats[t] = r,
        this
    }
    ,
    e.prototype.setInt = function(t, r) {
        return this._checkUniform(t),
        this._ints[t] = r,
        this
    }
    ,
    e.prototype.setFloats = function(t, r) {
        return this._checkUniform(t),
        this._floatsArrays[t] = r,
        this
    }
    ,
    e.prototype.setColor3 = function(t, r) {
        return this._checkUniform(t),
        this._colors3[t] = r,
        this
    }
    ,
    e.prototype.setColor3Array = function(t, r) {
        return this._checkUniform(t),
        this._colors3Arrays[t] = r.reduce(function(n, o) {
            return o.toArray(n, n.length),
            n
        }, []),
        this
    }
    ,
    e.prototype.setColor4 = function(t, r) {
        return this._checkUniform(t),
        this._colors4[t] = r,
        this
    }
    ,
    e.prototype.setColor4Array = function(t, r) {
        return this._checkUniform(t),
        this._colors4Arrays[t] = r.reduce(function(n, o) {
            return o.toArray(n, n.length),
            n
        }, []),
        this
    }
    ,
    e.prototype.setVector2 = function(t, r) {
        return this._checkUniform(t),
        this._vectors2[t] = r,
        this
    }
    ,
    e.prototype.setVector3 = function(t, r) {
        return this._checkUniform(t),
        this._vectors3[t] = r,
        this
    }
    ,
    e.prototype.setVector4 = function(t, r) {
        return this._checkUniform(t),
        this._vectors4[t] = r,
        this
    }
    ,
    e.prototype.setMatrix = function(t, r) {
        return this._checkUniform(t),
        this._matrices[t] = r,
        this
    }
    ,
    e.prototype.setMatrices = function(t, r) {
        this._checkUniform(t);
        for (var n = new Float32Array(r.length * 16), o = 0; o < r.length; o++) {
            var a = r[o];
            a.copyToArray(n, o * 16)
        }
        return this._matrixArrays[t] = n,
        this
    }
    ,
    e.prototype.setMatrix3x3 = function(t, r) {
        return this._checkUniform(t),
        this._matrices3x3[t] = r,
        this
    }
    ,
    e.prototype.setMatrix2x2 = function(t, r) {
        return this._checkUniform(t),
        this._matrices2x2[t] = r,
        this
    }
    ,
    e.prototype.setArray2 = function(t, r) {
        return this._checkUniform(t),
        this._vectors2Arrays[t] = r,
        this
    }
    ,
    e.prototype.setArray3 = function(t, r) {
        return this._checkUniform(t),
        this._vectors3Arrays[t] = r,
        this
    }
    ,
    e.prototype.setArray4 = function(t, r) {
        return this._checkUniform(t),
        this._vectors4Arrays[t] = r,
        this
    }
    ,
    e.prototype.setUniformBuffer = function(t, r) {
        return this._options.uniformBuffers.indexOf(t) === -1 && this._options.uniformBuffers.push(t),
        this._uniformBuffers[t] = r,
        this
    }
    ,
    e.prototype.setTextureSampler = function(t, r) {
        return this._options.samplerObjects.indexOf(t) === -1 && this._options.samplerObjects.push(t),
        this._textureSamplers[t] = r,
        this
    }
    ,
    e.prototype.setStorageBuffer = function(t, r) {
        return this._options.storageBuffers.indexOf(t) === -1 && this._options.storageBuffers.push(t),
        this._storageBuffers[t] = r,
        this
    }
    ,
    e.prototype.isReadyForSubMesh = function(t, r, n) {
        return this.isReady(t, n, r)
    }
    ,
    e.prototype.isReady = function(t, r, n) {
        var o, a, s, l, u = n && this._storeEffectOnSubMeshes;
        if (this.isFrozen)
            if (u) {
                if (n.effect && n.effect._wasPreviouslyReady)
                    return !0
            } else {
                var c = this._drawWrapper.effect;
                if (c && c._wasPreviouslyReady && this._effectUsesInstances === r)
                    return !0
            }
        var h = this.getScene()
          , f = h.getEngine()
          , d = []
          , _ = []
          , g = new EffectFallbacks
          , m = this._shaderPath
          , v = this._options.uniforms
          , y = this._options.uniformBuffers
          , b = this._options.samplers;
        f.getCaps().multiview && h.activeCamera && h.activeCamera.outputRenderTarget && h.activeCamera.outputRenderTarget.getViewCount() > 1 && (this._multiview = !0,
        d.push("#define MULTIVIEW"),
        this._options.uniforms.indexOf("viewProjection") !== -1 && this._options.uniforms.indexOf("viewProjectionR") === -1 && this._options.uniforms.push("viewProjectionR"));
        for (var T = 0; T < this._options.defines.length; T++) {
            var C = this._options.defines[T].indexOf("#define") === 0 ? this._options.defines[T] : "#define " + this._options.defines[T];
            d.push(C)
        }
        for (var T = 0; T < this._options.attributes.length; T++)
            _.push(this._options.attributes[T]);
        if (t && t.isVerticesDataPresent(VertexBuffer.ColorKind) && (_.push(VertexBuffer.ColorKind),
        d.push("#define VERTEXCOLOR")),
        r && (d.push("#define INSTANCES"),
        MaterialHelper.PushAttributesForInstances(_),
        t != null && t.hasThinInstances && d.push("#define THIN_INSTANCES")),
        t && t.useBones && t.computeBonesUsingShaders && t.skeleton) {
            _.push(VertexBuffer.MatricesIndicesKind),
            _.push(VertexBuffer.MatricesWeightsKind),
            t.numBoneInfluencers > 4 && (_.push(VertexBuffer.MatricesIndicesExtraKind),
            _.push(VertexBuffer.MatricesWeightsExtraKind));
            var A = t.skeleton;
            d.push("#define NUM_BONE_INFLUENCERS " + t.numBoneInfluencers),
            g.addCPUSkinningFallback(0, t),
            A.isUsingTextureForMatrices ? (d.push("#define BONETEXTURE"),
            this._options.uniforms.indexOf("boneTextureWidth") === -1 && this._options.uniforms.push("boneTextureWidth"),
            this._options.samplers.indexOf("boneSampler") === -1 && this._options.samplers.push("boneSampler")) : (d.push("#define BonesPerMesh " + (A.bones.length + 1)),
            this._options.uniforms.indexOf("mBones") === -1 && this._options.uniforms.push("mBones"))
        } else
            d.push("#define NUM_BONE_INFLUENCERS 0");
        var S = 0
          , P = t ? t.morphTargetManager : null;
        if (P) {
            var R = P.supportsUVs && d.indexOf("#define UV1") !== -1
              , M = P.supportsTangents && d.indexOf("#define TANGENT") !== -1
              , x = P.supportsNormals && d.indexOf("#define NORMAL") !== -1;
            S = P.numInfluencers,
            R && d.push("#define MORPHTARGETS_UV"),
            M && d.push("#define MORPHTARGETS_TANGENT"),
            x && d.push("#define MORPHTARGETS_NORMAL"),
            S > 0 && d.push("#define MORPHTARGETS"),
            P.isUsingTextureForTargets && (d.push("#define MORPHTARGETS_TEXTURE"),
            this._options.uniforms.indexOf("morphTargetTextureIndices") === -1 && this._options.uniforms.push("morphTargetTextureIndices"),
            this._options.samplers.indexOf("morphTargets") === -1 && this._options.samplers.push("morphTargets")),
            d.push("#define NUM_MORPH_INFLUENCERS " + S);
            for (var T = 0; T < S; T++)
                _.push(VertexBuffer.PositionKind + T),
                x && _.push(VertexBuffer.NormalKind + T),
                M && _.push(VertexBuffer.TangentKind + T),
                R && _.push(VertexBuffer.UVKind + "_" + T);
            S > 0 && (v = v.slice(),
            v.push("morphTargetInfluences"),
            v.push("morphTargetTextureInfo"),
            v.push("morphTargetTextureIndices"))
        } else
            d.push("#define NUM_MORPH_INFLUENCERS 0");
        if (t) {
            var I = t.bakedVertexAnimationManager;
            I && I.isEnabled && (d.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),
            this._options.uniforms.indexOf("bakedVertexAnimationSettings") === -1 && this._options.uniforms.push("bakedVertexAnimationSettings"),
            this._options.uniforms.indexOf("bakedVertexAnimationTextureSizeInverted") === -1 && this._options.uniforms.push("bakedVertexAnimationTextureSizeInverted"),
            this._options.uniforms.indexOf("bakedVertexAnimationTime") === -1 && this._options.uniforms.push("bakedVertexAnimationTime"),
            this._options.samplers.indexOf("bakedVertexAnimationTexture") === -1 && this._options.samplers.push("bakedVertexAnimationTexture")),
            MaterialHelper.PrepareAttributesForBakedVertexAnimation(_, t, d)
        }
        for (var w in this._textures)
            if (!this._textures[w].isReady())
                return !1;
        t && this._shouldTurnAlphaTestOn(t) && d.push("#define ALPHATEST"),
        (this._options.useClipPlane === null && !!h.clipPlane || this._options.useClipPlane) && (d.push("#define CLIPPLANE"),
        v.indexOf("vClipPlane") === -1 && v.push("vClipPlane")),
        (this._options.useClipPlane === null && !!h.clipPlane2 || this._options.useClipPlane) && (d.push("#define CLIPPLANE2"),
        v.indexOf("vClipPlane2") === -1 && v.push("vClipPlane2")),
        (this._options.useClipPlane === null && !!h.clipPlane3 || this._options.useClipPlane) && (d.push("#define CLIPPLANE3"),
        v.indexOf("vClipPlane3") === -1 && v.push("vClipPlane3")),
        (this._options.useClipPlane === null && !!h.clipPlane4 || this._options.useClipPlane) && (d.push("#define CLIPPLANE4"),
        v.indexOf("vClipPlane4") === -1 && v.push("vClipPlane4")),
        (this._options.useClipPlane === null && !!h.clipPlane5 || this._options.useClipPlane) && (d.push("#define CLIPPLANE5"),
        v.indexOf("vClipPlane5") === -1 && v.push("vClipPlane5")),
        (this._options.useClipPlane === null && !!h.clipPlane6 || this._options.useClipPlane) && (d.push("#define CLIPPLANE6"),
        v.indexOf("vClipPlane6") === -1 && v.push("vClipPlane6")),
        this.customShaderNameResolve && (v = v.slice(),
        y = y.slice(),
        b = b.slice(),
        m = this.customShaderNameResolve(m, v, y, b, d, _));
        var O = u ? n._getDrawWrapper() : this._drawWrapper
          , D = (o = O == null ? void 0 : O.effect) !== null && o !== void 0 ? o : null
          , F = (a = O == null ? void 0 : O.defines) !== null && a !== void 0 ? a : null
          , V = d.join(`
`)
          , N = D;
        return F !== V && (N = f.createEffect(m, {
            attributes: _,
            uniformsNames: v,
            uniformBuffersNames: y,
            samplers: b,
            defines: V,
            fallbacks: g,
            onCompiled: this.onCompiled,
            onError: this.onError,
            indexParameters: {
                maxSimultaneousMorphTargets: S
            },
            shaderLanguage: this._options.shaderLanguage
        }, f),
        u ? n.setEffect(N, V, this._materialContext) : O && O.setEffect(N, V),
        this._onEffectCreatedObservable && (onCreatedEffectParameters$3.effect = N,
        onCreatedEffectParameters$3.subMesh = (s = n != null ? n : t == null ? void 0 : t.subMeshes[0]) !== null && s !== void 0 ? s : null,
        this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters$3))),
        this._effectUsesInstances = !!r,
        !((l = !(N != null && N.isReady())) !== null && l !== void 0) || l ? !1 : (D !== N && h.resetCachedMaterial(),
        N._wasPreviouslyReady = !0,
        !0)
    }
    ,
    e.prototype.bindOnlyWorldMatrix = function(t, r) {
        var n = this.getScene()
          , o = r != null ? r : this.getEffect();
        !o || (this._options.uniforms.indexOf("world") !== -1 && o.setMatrix("world", t),
        this._options.uniforms.indexOf("worldView") !== -1 && (t.multiplyToRef(n.getViewMatrix(), this._cachedWorldViewMatrix),
        o.setMatrix("worldView", this._cachedWorldViewMatrix)),
        this._options.uniforms.indexOf("worldViewProjection") !== -1 && (t.multiplyToRef(n.getTransformMatrix(), this._cachedWorldViewProjectionMatrix),
        o.setMatrix("worldViewProjection", this._cachedWorldViewProjectionMatrix)))
    }
    ,
    e.prototype.bindForSubMesh = function(t, r, n) {
        var o;
        this.bind(t, r, (o = n._drawWrapperOverride) === null || o === void 0 ? void 0 : o.effect, n)
    }
    ,
    e.prototype.bind = function(t, r, n, o) {
        var a, s = o && this._storeEffectOnSubMeshes, l = n != null ? n : s ? o.effect : this.getEffect();
        if (!!l) {
            this._activeEffect = l,
            this.bindOnlyWorldMatrix(t, n);
            var u = this._options.uniformBuffers
              , c = !1;
            if (l && u && u.length > 0 && this.getScene().getEngine().supportsUniformBuffers)
                for (var h = 0; h < u.length; ++h) {
                    var f = u[h];
                    switch (f) {
                    case "Mesh":
                        r && (r.getMeshUniformBuffer().bindToEffect(l, "Mesh"),
                        r.transferToEffect(t));
                        break;
                    case "Scene":
                        MaterialHelper.BindSceneUniformBuffer(l, this.getScene().getSceneUniformBuffer()),
                        this.getScene().finalizeSceneUbo(),
                        c = !0;
                        break
                    }
                }
            var d = r && s ? this._mustRebind(this.getScene(), l, r.visibility) : this.getScene().getCachedMaterial() !== this;
            if (l && d) {
                !c && this._options.uniforms.indexOf("view") !== -1 && l.setMatrix("view", this.getScene().getViewMatrix()),
                !c && this._options.uniforms.indexOf("projection") !== -1 && l.setMatrix("projection", this.getScene().getProjectionMatrix()),
                !c && this._options.uniforms.indexOf("viewProjection") !== -1 && (l.setMatrix("viewProjection", this.getScene().getTransformMatrix()),
                this._multiview && l.setMatrix("viewProjectionR", this.getScene()._transformMatrixR)),
                this.getScene().activeCamera && this._options.uniforms.indexOf("cameraPosition") !== -1 && l.setVector3("cameraPosition", this.getScene().activeCamera.globalPosition),
                MaterialHelper.BindBonesParameters(r, l),
                MaterialHelper.BindClipPlane(l, this.getScene());
                var _;
                for (_ in this._textures)
                    l.setTexture(_, this._textures[_]);
                for (_ in this._textureArrays)
                    l.setTextureArray(_, this._textureArrays[_]);
                for (_ in this._externalTextures)
                    l.setExternalTexture(_, this._externalTextures[_]);
                for (_ in this._ints)
                    l.setInt(_, this._ints[_]);
                for (_ in this._floats)
                    l.setFloat(_, this._floats[_]);
                for (_ in this._floatsArrays)
                    l.setArray(_, this._floatsArrays[_]);
                for (_ in this._colors3)
                    l.setColor3(_, this._colors3[_]);
                for (_ in this._colors3Arrays)
                    l.setArray3(_, this._colors3Arrays[_]);
                for (_ in this._colors4) {
                    var g = this._colors4[_];
                    l.setFloat4(_, g.r, g.g, g.b, g.a)
                }
                for (_ in this._colors4Arrays)
                    l.setArray4(_, this._colors4Arrays[_]);
                for (_ in this._vectors2)
                    l.setVector2(_, this._vectors2[_]);
                for (_ in this._vectors3)
                    l.setVector3(_, this._vectors3[_]);
                for (_ in this._vectors4)
                    l.setVector4(_, this._vectors4[_]);
                for (_ in this._matrices)
                    l.setMatrix(_, this._matrices[_]);
                for (_ in this._matrixArrays)
                    l.setMatrices(_, this._matrixArrays[_]);
                for (_ in this._matrices3x3)
                    l.setMatrix3x3(_, this._matrices3x3[_]);
                for (_ in this._matrices2x2)
                    l.setMatrix2x2(_, this._matrices2x2[_]);
                for (_ in this._vectors2Arrays)
                    l.setArray2(_, this._vectors2Arrays[_]);
                for (_ in this._vectors3Arrays)
                    l.setArray3(_, this._vectors3Arrays[_]);
                for (_ in this._vectors4Arrays)
                    l.setArray4(_, this._vectors4Arrays[_]);
                for (_ in this._uniformBuffers) {
                    var m = this._uniformBuffers[_].getBuffer();
                    m && l.bindUniformBuffer(m, _)
                }
                for (_ in this._textureSamplers)
                    l.setTextureSampler(_, this._textureSamplers[_]);
                for (_ in this._storageBuffers)
                    l.setStorageBuffer(_, this._storageBuffers[_])
            }
            if (l && r && (d || !this.isFrozen)) {
                var v = r.morphTargetManager;
                v && v.numInfluencers > 0 && MaterialHelper.BindMorphTargetParameters(r, l);
                var y = r.bakedVertexAnimationManager;
                y && y.isEnabled && ((a = r.bakedVertexAnimationManager) === null || a === void 0 || a.bind(l, this._effectUsesInstances))
            }
            this._afterBind(r, l)
        }
    }
    ,
    e.prototype.getActiveTextures = function() {
        var t = i.prototype.getActiveTextures.call(this);
        for (var r in this._textures)
            t.push(this._textures[r]);
        for (var r in this._textureArrays)
            for (var n = this._textureArrays[r], o = 0; o < n.length; o++)
                t.push(n[o]);
        return t
    }
    ,
    e.prototype.hasTexture = function(t) {
        if (i.prototype.hasTexture.call(this, t))
            return !0;
        for (var r in this._textures)
            if (this._textures[r] === t)
                return !0;
        for (var r in this._textureArrays)
            for (var n = this._textureArrays[r], o = 0; o < n.length; o++)
                if (n[o] === t)
                    return !0;
        return !1
    }
    ,
    e.prototype.clone = function(t) {
        var r = this
          , n = SerializationHelper.Clone(function() {
            return new e(t,r.getScene(),r._shaderPath,r._options,r._storeEffectOnSubMeshes)
        }, this);
        n.name = t,
        n.id = t,
        typeof n._shaderPath == "object" && (n._shaderPath = __assign({}, n._shaderPath)),
        this._options = __assign({}, this._options),
        Object.keys(this._options).forEach(function(a) {
            var s = r._options[a];
            Array.isArray(s) && (r._options[a] = s.slice(0))
        }),
        this.stencil.copyTo(n.stencil);
        for (var o in this._textures)
            n.setTexture(o, this._textures[o]);
        for (var o in this._textureArrays)
            n.setTextureArray(o, this._textureArrays[o]);
        for (var o in this._externalTextures)
            n.setExternalTexture(o, this._externalTextures[o]);
        for (var o in this._ints)
            n.setInt(o, this._ints[o]);
        for (var o in this._floats)
            n.setFloat(o, this._floats[o]);
        for (var o in this._floatsArrays)
            n.setFloats(o, this._floatsArrays[o]);
        for (var o in this._colors3)
            n.setColor3(o, this._colors3[o]);
        for (var o in this._colors3Arrays)
            n._colors3Arrays[o] = this._colors3Arrays[o];
        for (var o in this._colors4)
            n.setColor4(o, this._colors4[o]);
        for (var o in this._colors4Arrays)
            n._colors4Arrays[o] = this._colors4Arrays[o];
        for (var o in this._vectors2)
            n.setVector2(o, this._vectors2[o]);
        for (var o in this._vectors3)
            n.setVector3(o, this._vectors3[o]);
        for (var o in this._vectors4)
            n.setVector4(o, this._vectors4[o]);
        for (var o in this._matrices)
            n.setMatrix(o, this._matrices[o]);
        for (var o in this._matrixArrays)
            n._matrixArrays[o] = this._matrixArrays[o].slice();
        for (var o in this._matrices3x3)
            n.setMatrix3x3(o, this._matrices3x3[o]);
        for (var o in this._matrices2x2)
            n.setMatrix2x2(o, this._matrices2x2[o]);
        for (var o in this._vectors2Arrays)
            n.setArray2(o, this._vectors2Arrays[o]);
        for (var o in this._vectors3Arrays)
            n.setArray3(o, this._vectors3Arrays[o]);
        for (var o in this._vectors4Arrays)
            n.setArray4(o, this._vectors4Arrays[o]);
        for (var o in this._uniformBuffers)
            n.setUniformBuffer(o, this._uniformBuffers[o]);
        for (var o in this._textureSamplers)
            n.setTextureSampler(o, this._textureSamplers[o]);
        for (var o in this._storageBuffers)
            n.setStorageBuffer(o, this._storageBuffers[o]);
        return n
    }
    ,
    e.prototype.dispose = function(t, r, n) {
        if (r) {
            var o;
            for (o in this._textures)
                this._textures[o].dispose();
            for (o in this._textureArrays)
                for (var a = this._textureArrays[o], s = 0; s < a.length; s++)
                    a[s].dispose()
        }
        this._textures = {},
        i.prototype.dispose.call(this, t, r, n)
    }
    ,
    e.prototype.serialize = function() {
        var t = SerializationHelper.Serialize(this);
        t.customType = "BABYLON.ShaderMaterial",
        t.options = this._options,
        t.shaderPath = this._shaderPath,
        t.storeEffectOnSubMeshes = this._storeEffectOnSubMeshes;
        var r;
        t.stencil = this.stencil.serialize(),
        t.textures = {};
        for (r in this._textures)
            t.textures[r] = this._textures[r].serialize();
        t.textureArrays = {};
        for (r in this._textureArrays) {
            t.textureArrays[r] = [];
            for (var n = this._textureArrays[r], o = 0; o < n.length; o++)
                t.textureArrays[r].push(n[o].serialize())
        }
        t.ints = {};
        for (r in this._ints)
            t.ints[r] = this._ints[r];
        t.floats = {};
        for (r in this._floats)
            t.floats[r] = this._floats[r];
        t.FloatArrays = {};
        for (r in this._floatsArrays)
            t.FloatArrays[r] = this._floatsArrays[r];
        t.colors3 = {};
        for (r in this._colors3)
            t.colors3[r] = this._colors3[r].asArray();
        t.colors3Arrays = {};
        for (r in this._colors3Arrays)
            t.colors3Arrays[r] = this._colors3Arrays[r];
        t.colors4 = {};
        for (r in this._colors4)
            t.colors4[r] = this._colors4[r].asArray();
        t.colors4Arrays = {};
        for (r in this._colors4Arrays)
            t.colors4Arrays[r] = this._colors4Arrays[r];
        t.vectors2 = {};
        for (r in this._vectors2)
            t.vectors2[r] = this._vectors2[r].asArray();
        t.vectors3 = {};
        for (r in this._vectors3)
            t.vectors3[r] = this._vectors3[r].asArray();
        t.vectors4 = {};
        for (r in this._vectors4)
            t.vectors4[r] = this._vectors4[r].asArray();
        t.matrices = {};
        for (r in this._matrices)
            t.matrices[r] = this._matrices[r].asArray();
        t.matrixArray = {};
        for (r in this._matrixArrays)
            t.matrixArray[r] = this._matrixArrays[r];
        t.matrices3x3 = {};
        for (r in this._matrices3x3)
            t.matrices3x3[r] = this._matrices3x3[r];
        t.matrices2x2 = {};
        for (r in this._matrices2x2)
            t.matrices2x2[r] = this._matrices2x2[r];
        t.vectors2Arrays = {};
        for (r in this._vectors2Arrays)
            t.vectors2Arrays[r] = this._vectors2Arrays[r];
        t.vectors3Arrays = {};
        for (r in this._vectors3Arrays)
            t.vectors3Arrays[r] = this._vectors3Arrays[r];
        t.vectors4Arrays = {};
        for (r in this._vectors4Arrays)
            t.vectors4Arrays[r] = this._vectors4Arrays[r];
        return t
    }
    ,
    e.Parse = function(t, r, n) {
        var o = SerializationHelper.Parse(function() {
            return new e(t.name,r,t.shaderPath,t.options,t.storeEffectOnSubMeshes)
        }, t, r, n), a;
        t.stencil && o.stencil.parse(t.stencil, r, n);
        for (a in t.textures)
            o.setTexture(a, Texture.Parse(t.textures[a], r, n));
        for (a in t.textureArrays) {
            for (var s = t.textureArrays[a], l = new Array, u = 0; u < s.length; u++)
                l.push(Texture.Parse(s[u], r, n));
            o.setTextureArray(a, l)
        }
        for (a in t.ints)
            o.setInt(a, t.ints[a]);
        for (a in t.floats)
            o.setFloat(a, t.floats[a]);
        for (a in t.floatsArrays)
            o.setFloats(a, t.floatsArrays[a]);
        for (a in t.colors3)
            o.setColor3(a, Color3.FromArray(t.colors3[a]));
        for (a in t.colors3Arrays) {
            var c = t.colors3Arrays[a].reduce(function(h, f, d) {
                return d % 3 === 0 ? h.push([f]) : h[h.length - 1].push(f),
                h
            }, []).map(function(h) {
                return Color3.FromArray(h)
            });
            o.setColor3Array(a, c)
        }
        for (a in t.colors4)
            o.setColor4(a, Color4.FromArray(t.colors4[a]));
        for (a in t.colors4Arrays) {
            var c = t.colors4Arrays[a].reduce(function(f, d, _) {
                return _ % 4 === 0 ? f.push([d]) : f[f.length - 1].push(d),
                f
            }, []).map(function(f) {
                return Color4.FromArray(f)
            });
            o.setColor4Array(a, c)
        }
        for (a in t.vectors2)
            o.setVector2(a, Vector2.FromArray(t.vectors2[a]));
        for (a in t.vectors3)
            o.setVector3(a, Vector3.FromArray(t.vectors3[a]));
        for (a in t.vectors4)
            o.setVector4(a, Vector4.FromArray(t.vectors4[a]));
        for (a in t.matrices)
            o.setMatrix(a, Matrix.FromArray(t.matrices[a]));
        for (a in t.matrixArray)
            o._matrixArrays[a] = new Float32Array(t.matrixArray[a]);
        for (a in t.matrices3x3)
            o.setMatrix3x3(a, t.matrices3x3[a]);
        for (a in t.matrices2x2)
            o.setMatrix2x2(a, t.matrices2x2[a]);
        for (a in t.vectors2Arrays)
            o.setArray2(a, t.vectors2Arrays[a]);
        for (a in t.vectors3Arrays)
            o.setArray3(a, t.vectors3Arrays[a]);
        for (a in t.vectors4Arrays)
            o.setArray4(a, t.vectors4Arrays[a]);
        return o
    }
    ,
    e.ParseFromFileAsync = function(t, r, n, o) {
        var a = this;
        return o === void 0 && (o = ""),
        new Promise(function(s, l) {
            var u = new WebRequest;
            u.addEventListener("readystatechange", function() {
                if (u.readyState == 4)
                    if (u.status == 200) {
                        var c = JSON.parse(u.responseText)
                          , h = a.Parse(c, n || Engine.LastCreatedScene, o);
                        t && (h.name = t),
                        s(h)
                    } else
                        l("Unable to load the ShaderMaterial")
            }),
            u.open("GET", r),
            u.send()
        }
        )
    }
    ,
    e.CreateFromSnippetAsync = function(t, r, n) {
        var o = this;
        return n === void 0 && (n = ""),
        new Promise(function(a, s) {
            var l = new WebRequest;
            l.addEventListener("readystatechange", function() {
                if (l.readyState == 4)
                    if (l.status == 200) {
                        var u = JSON.parse(JSON.parse(l.responseText).jsonPayload)
                          , c = JSON.parse(u.shaderMaterial)
                          , h = o.Parse(c, r || Engine.LastCreatedScene, n);
                        h.snippetId = t,
                        a(h)
                    } else
                        s("Unable to load the snippet " + t)
            }),
            l.open("GET", o.SnippetUrl + "/" + t.replace(/#/g, "/")),
            l.send()
        }
        )
    }
    ,
    e.SnippetUrl = "https://snippet.babylonjs.com",
    e
}(PushMaterial);
RegisterClass("BABYLON.ShaderMaterial", ShaderMaterial);
var PrePassConfiguration = function() {
    function i() {
        this.previousWorldMatrices = {},
        this.previousBones = {}
    }
    return i.AddUniforms = function(e) {
        e.push("previousWorld", "previousViewProjection", "mPreviousBones")
    }
    ,
    i.AddSamplers = function(e) {}
    ,
    i.prototype.bindForSubMesh = function(e, t, r, n, o) {
        if (t.prePassRenderer && t.prePassRenderer.enabled && t.prePassRenderer.currentRTisSceneRT && t.prePassRenderer.getIndex(2) !== -1) {
            this.previousWorldMatrices[r.uniqueId] || (this.previousWorldMatrices[r.uniqueId] = n.clone()),
            this.previousViewProjection || (this.previousViewProjection = t.getTransformMatrix().clone(),
            this.currentViewProjection = t.getTransformMatrix().clone());
            var a = t.getEngine();
            this.currentViewProjection.updateFlag !== t.getTransformMatrix().updateFlag ? (this._lastUpdateFrameId = a.frameId,
            this.previousViewProjection.copyFrom(this.currentViewProjection),
            this.currentViewProjection.copyFrom(t.getTransformMatrix())) : this._lastUpdateFrameId !== a.frameId && (this._lastUpdateFrameId = a.frameId,
            this.previousViewProjection.copyFrom(this.currentViewProjection)),
            e.setMatrix("previousWorld", this.previousWorldMatrices[r.uniqueId]),
            e.setMatrix("previousViewProjection", this.previousViewProjection),
            this.previousWorldMatrices[r.uniqueId] = n.clone()
        }
    }
    ,
    i
}()
  , MaterialFlags = function() {
    function i() {}
    return Object.defineProperty(i, "DiffuseTextureEnabled", {
        get: function() {
            return this._DiffuseTextureEnabled
        },
        set: function(e) {
            this._DiffuseTextureEnabled !== e && (this._DiffuseTextureEnabled = e,
            Engine.MarkAllMaterialsAsDirty(1))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i, "DetailTextureEnabled", {
        get: function() {
            return this._DetailTextureEnabled
        },
        set: function(e) {
            this._DetailTextureEnabled !== e && (this._DetailTextureEnabled = e,
            Engine.MarkAllMaterialsAsDirty(1))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i, "AmbientTextureEnabled", {
        get: function() {
            return this._AmbientTextureEnabled
        },
        set: function(e) {
            this._AmbientTextureEnabled !== e && (this._AmbientTextureEnabled = e,
            Engine.MarkAllMaterialsAsDirty(1))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i, "OpacityTextureEnabled", {
        get: function() {
            return this._OpacityTextureEnabled
        },
        set: function(e) {
            this._OpacityTextureEnabled !== e && (this._OpacityTextureEnabled = e,
            Engine.MarkAllMaterialsAsDirty(1))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i, "ReflectionTextureEnabled", {
        get: function() {
            return this._ReflectionTextureEnabled
        },
        set: function(e) {
            this._ReflectionTextureEnabled !== e && (this._ReflectionTextureEnabled = e,
            Engine.MarkAllMaterialsAsDirty(1))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i, "EmissiveTextureEnabled", {
        get: function() {
            return this._EmissiveTextureEnabled
        },
        set: function(e) {
            this._EmissiveTextureEnabled !== e && (this._EmissiveTextureEnabled = e,
            Engine.MarkAllMaterialsAsDirty(1))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i, "SpecularTextureEnabled", {
        get: function() {
            return this._SpecularTextureEnabled
        },
        set: function(e) {
            this._SpecularTextureEnabled !== e && (this._SpecularTextureEnabled = e,
            Engine.MarkAllMaterialsAsDirty(1))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i, "BumpTextureEnabled", {
        get: function() {
            return this._BumpTextureEnabled
        },
        set: function(e) {
            this._BumpTextureEnabled !== e && (this._BumpTextureEnabled = e,
            Engine.MarkAllMaterialsAsDirty(1))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i, "LightmapTextureEnabled", {
        get: function() {
            return this._LightmapTextureEnabled
        },
        set: function(e) {
            this._LightmapTextureEnabled !== e && (this._LightmapTextureEnabled = e,
            Engine.MarkAllMaterialsAsDirty(1))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i, "RefractionTextureEnabled", {
        get: function() {
            return this._RefractionTextureEnabled
        },
        set: function(e) {
            this._RefractionTextureEnabled !== e && (this._RefractionTextureEnabled = e,
            Engine.MarkAllMaterialsAsDirty(1))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i, "ColorGradingTextureEnabled", {
        get: function() {
            return this._ColorGradingTextureEnabled
        },
        set: function(e) {
            this._ColorGradingTextureEnabled !== e && (this._ColorGradingTextureEnabled = e,
            Engine.MarkAllMaterialsAsDirty(1))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i, "FresnelEnabled", {
        get: function() {
            return this._FresnelEnabled
        },
        set: function(e) {
            this._FresnelEnabled !== e && (this._FresnelEnabled = e,
            Engine.MarkAllMaterialsAsDirty(4))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i, "ClearCoatTextureEnabled", {
        get: function() {
            return this._ClearCoatTextureEnabled
        },
        set: function(e) {
            this._ClearCoatTextureEnabled !== e && (this._ClearCoatTextureEnabled = e,
            Engine.MarkAllMaterialsAsDirty(1))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i, "ClearCoatBumpTextureEnabled", {
        get: function() {
            return this._ClearCoatBumpTextureEnabled
        },
        set: function(e) {
            this._ClearCoatBumpTextureEnabled !== e && (this._ClearCoatBumpTextureEnabled = e,
            Engine.MarkAllMaterialsAsDirty(1))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i, "ClearCoatTintTextureEnabled", {
        get: function() {
            return this._ClearCoatTintTextureEnabled
        },
        set: function(e) {
            this._ClearCoatTintTextureEnabled !== e && (this._ClearCoatTintTextureEnabled = e,
            Engine.MarkAllMaterialsAsDirty(1))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i, "SheenTextureEnabled", {
        get: function() {
            return this._SheenTextureEnabled
        },
        set: function(e) {
            this._SheenTextureEnabled !== e && (this._SheenTextureEnabled = e,
            Engine.MarkAllMaterialsAsDirty(1))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i, "AnisotropicTextureEnabled", {
        get: function() {
            return this._AnisotropicTextureEnabled
        },
        set: function(e) {
            this._AnisotropicTextureEnabled !== e && (this._AnisotropicTextureEnabled = e,
            Engine.MarkAllMaterialsAsDirty(1))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i, "ThicknessTextureEnabled", {
        get: function() {
            return this._ThicknessTextureEnabled
        },
        set: function(e) {
            this._ThicknessTextureEnabled !== e && (this._ThicknessTextureEnabled = e,
            Engine.MarkAllMaterialsAsDirty(1))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i, "RefractionIntensityTextureEnabled", {
        get: function() {
            return this._ThicknessTextureEnabled
        },
        set: function(e) {
            this._RefractionIntensityTextureEnabled !== e && (this._RefractionIntensityTextureEnabled = e,
            Engine.MarkAllMaterialsAsDirty(1))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i, "TranslucencyIntensityTextureEnabled", {
        get: function() {
            return this._ThicknessTextureEnabled
        },
        set: function(e) {
            this._TranslucencyIntensityTextureEnabled !== e && (this._TranslucencyIntensityTextureEnabled = e,
            Engine.MarkAllMaterialsAsDirty(1))
        },
        enumerable: !1,
        configurable: !0
    }),
    i._DiffuseTextureEnabled = !0,
    i._DetailTextureEnabled = !0,
    i._AmbientTextureEnabled = !0,
    i._OpacityTextureEnabled = !0,
    i._ReflectionTextureEnabled = !0,
    i._EmissiveTextureEnabled = !0,
    i._SpecularTextureEnabled = !0,
    i._BumpTextureEnabled = !0,
    i._LightmapTextureEnabled = !0,
    i._RefractionTextureEnabled = !0,
    i._ColorGradingTextureEnabled = !0,
    i._FresnelEnabled = !0,
    i._ClearCoatTextureEnabled = !0,
    i._ClearCoatBumpTextureEnabled = !0,
    i._ClearCoatTintTextureEnabled = !0,
    i._SheenTextureEnabled = !0,
    i._AnisotropicTextureEnabled = !0,
    i._ThicknessTextureEnabled = !0,
    i._RefractionIntensityTextureEnabled = !0,
    i._TranslucencyIntensityTextureEnabled = !0,
    i
}()
  , name$2o = "defaultFragmentDeclaration"
  , shader$2o = `uniform vec4 vEyePosition;
uniform vec4 vDiffuseColor;
#ifdef SPECULARTERM
uniform vec4 vSpecularColor;
#endif
uniform vec3 vEmissiveColor;
uniform vec3 vAmbientColor;
uniform float visibility;

#ifdef DIFFUSE
uniform vec2 vDiffuseInfos;
#endif
#ifdef AMBIENT
uniform vec2 vAmbientInfos;
#endif
#ifdef OPACITY
uniform vec2 vOpacityInfos;
#endif
#ifdef EMISSIVE
uniform vec2 vEmissiveInfos;
#endif
#ifdef LIGHTMAP
uniform vec2 vLightmapInfos;
#endif
#ifdef BUMP
uniform vec3 vBumpInfos;
uniform vec2 vTangentSpaceParams;
#endif
#ifdef ALPHATEST
uniform float alphaCutOff;
#endif
#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)
uniform mat4 view;
#endif
#ifdef REFRACTION
uniform vec4 vRefractionInfos;
#ifndef REFRACTIONMAP_3D
uniform mat4 refractionMatrix;
#endif
#ifdef REFRACTIONFRESNEL
uniform vec4 refractionLeftColor;
uniform vec4 refractionRightColor;
#endif
#if defined(USE_LOCAL_REFRACTIONMAP_CUBIC) && defined(REFRACTIONMAP_3D)
uniform vec3 vRefractionPosition;
uniform vec3 vRefractionSize;
#endif
#endif
#if defined(SPECULAR) && defined(SPECULARTERM)
uniform vec2 vSpecularInfos;
#endif
#ifdef DIFFUSEFRESNEL
uniform vec4 diffuseLeftColor;
uniform vec4 diffuseRightColor;
#endif
#ifdef OPACITYFRESNEL
uniform vec4 opacityParts;
#endif
#ifdef EMISSIVEFRESNEL
uniform vec4 emissiveLeftColor;
uniform vec4 emissiveRightColor;
#endif

#ifdef REFLECTION
uniform vec2 vReflectionInfos;
#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION) || defined(REFLECTIONMAP_EQUIRECTANGULAR) || defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_SKYBOX)
uniform mat4 reflectionMatrix;
#endif
#ifndef REFLECTIONMAP_SKYBOX
#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)
uniform vec3 vReflectionPosition;
uniform vec3 vReflectionSize;
#endif
#endif
#ifdef REFLECTIONFRESNEL
uniform vec4 reflectionLeftColor;
uniform vec4 reflectionRightColor;
#endif
#endif
#ifdef DETAIL
uniform vec4 vDetailInfos;
#endif`;
ShaderStore.IncludesShadersStore[name$2o] = shader$2o;
var name$2n = "defaultUboDeclaration"
  , shader$2n = `layout(std140,column_major) uniform;
uniform Material
{
vec4 diffuseLeftColor;
vec4 diffuseRightColor;
vec4 opacityParts;
vec4 reflectionLeftColor;
vec4 reflectionRightColor;
vec4 refractionLeftColor;
vec4 refractionRightColor;
vec4 emissiveLeftColor;
vec4 emissiveRightColor;
vec2 vDiffuseInfos;
vec2 vAmbientInfos;
vec2 vOpacityInfos;
vec2 vReflectionInfos;
vec3 vReflectionPosition;
vec3 vReflectionSize;
vec2 vEmissiveInfos;
vec2 vLightmapInfos;
vec2 vSpecularInfos;
vec3 vBumpInfos;
mat4 diffuseMatrix;
mat4 ambientMatrix;
mat4 opacityMatrix;
mat4 reflectionMatrix;
mat4 emissiveMatrix;
mat4 lightmapMatrix;
mat4 specularMatrix;
mat4 bumpMatrix;
vec2 vTangentSpaceParams;
float pointSize;
float alphaCutOff;
mat4 refractionMatrix;
vec4 vRefractionInfos;
vec3 vRefractionPosition;
vec3 vRefractionSize;
vec4 vSpecularColor;
vec3 vEmissiveColor;
vec4 vDiffuseColor;
vec3 vAmbientColor;
vec4 vDetailInfos;
mat4 detailMatrix;
};
#include<sceneUboDeclaration>
#include<meshUboDeclaration>
`;
ShaderStore.IncludesShadersStore[name$2n] = shader$2n;
var name$2m = "prePassDeclaration"
  , shader$2m = `#ifdef PREPASS
#extension GL_EXT_draw_buffers : require
layout(location=0) out highp vec4 glFragData[{X}];
highp vec4 gl_FragColor;
#ifdef PREPASS_DEPTH
varying highp vec3 vViewPos;
#endif
#ifdef PREPASS_VELOCITY
varying highp vec4 vCurrentPosition;
varying highp vec4 vPreviousPosition;
#endif
#endif
`;
ShaderStore.IncludesShadersStore[name$2m] = shader$2m;
var name$2l = "oitDeclaration"
  , shader$2l = `#ifdef ORDER_INDEPENDENT_TRANSPARENCY
#extension GL_EXT_draw_buffers : require
layout(location=0) out vec2 depth;
layout(location=1) out vec4 frontColor;
layout(location=2) out vec4 backColor;
#define MAX_DEPTH 99999.0
highp vec4 gl_FragColor;
uniform sampler2D oitDepthSampler;
uniform sampler2D oitFrontColorSampler;
#endif
`;
ShaderStore.IncludesShadersStore[name$2l] = shader$2l;
var name$2k = "mainUVVaryingDeclaration"
  , shader$2k = `#ifdef MAINUV{X}
varying vec2 vMainUV{X};
#endif
`;
ShaderStore.IncludesShadersStore[name$2k] = shader$2k;
var name$2j = "lightFragmentDeclaration"
  , shader$2j = `#ifdef LIGHT{X}
uniform vec4 vLightData{X};
uniform vec4 vLightDiffuse{X};
#ifdef SPECULARTERM
uniform vec4 vLightSpecular{X};
#else
vec4 vLightSpecular{X}=vec4(0.);
#endif
#ifdef SHADOW{X}
#ifdef SHADOWCSM{X}
uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];
uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];
uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];
uniform float cascadeBlendFactor{X};
varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];
varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];
varying vec4 vPositionFromCamera{X};
#if defined(SHADOWPCSS{X})
uniform highp sampler2DArrayShadow shadowSampler{X};
uniform highp sampler2DArray depthSampler{X};
uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];
uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];
uniform float penumbraDarkness{X};
#elif defined(SHADOWPCF{X})
uniform highp sampler2DArrayShadow shadowSampler{X};
#else
uniform highp sampler2DArray shadowSampler{X};
#endif
#ifdef SHADOWCSMDEBUG{X}
const vec3 vCascadeColorsMultiplier{X}[8]=vec3[8]
(
vec3 ( 1.5,0.0,0.0 ),
vec3 ( 0.0,1.5,0.0 ),
vec3 ( 0.0,0.0,5.5 ),
vec3 ( 1.5,0.0,5.5 ),
vec3 ( 1.5,1.5,0.0 ),
vec3 ( 1.0,1.0,1.0 ),
vec3 ( 0.0,1.0,5.5 ),
vec3 ( 0.5,3.5,0.75 )
);
vec3 shadowDebug{X};
#endif
#ifdef SHADOWCSMUSESHADOWMAXZ{X}
int index{X}=-1;
#else
int index{X}=SHADOWCSMNUM_CASCADES{X}-1;
#endif
float diff{X}=0.;
#elif defined(SHADOWCUBE{X})
uniform samplerCube shadowSampler{X};
#else
varying vec4 vPositionFromLight{X};
varying float vDepthMetric{X};
#if defined(SHADOWPCSS{X})
uniform highp sampler2DShadow shadowSampler{X};
uniform highp sampler2D depthSampler{X};
#elif defined(SHADOWPCF{X})
uniform highp sampler2DShadow shadowSampler{X};
#else
uniform sampler2D shadowSampler{X};
#endif
uniform mat4 lightMatrix{X};
#endif
uniform vec4 shadowsInfo{X};
uniform vec2 depthValues{X};
#endif
#ifdef SPOTLIGHT{X}
uniform vec4 vLightDirection{X};
uniform vec4 vLightFalloff{X};
#elif defined(POINTLIGHT{X})
uniform vec4 vLightFalloff{X};
#elif defined(HEMILIGHT{X})
uniform vec3 vLightGround{X};
#endif
#ifdef PROJECTEDLIGHTTEXTURE{X}
uniform mat4 textureProjectionMatrix{X};
uniform sampler2D projectionLightSampler{X};
#endif
#endif`;
ShaderStore.IncludesShadersStore[name$2j] = shader$2j;
var name$2i = "lightUboDeclaration"
  , shader$2i = `#ifdef LIGHT{X}
uniform Light{X}
{
vec4 vLightData;
vec4 vLightDiffuse;
vec4 vLightSpecular;
#ifdef SPOTLIGHT{X}
vec4 vLightDirection;
vec4 vLightFalloff;
#elif defined(POINTLIGHT{X})
vec4 vLightFalloff;
#elif defined(HEMILIGHT{X})
vec3 vLightGround;
#endif
vec4 shadowsInfo;
vec2 depthValues;
} light{X};
#ifdef PROJECTEDLIGHTTEXTURE{X}
uniform mat4 textureProjectionMatrix{X};
uniform sampler2D projectionLightSampler{X};
#endif
#ifdef SHADOW{X}
#ifdef SHADOWCSM{X}
uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];
uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];
uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];
uniform float cascadeBlendFactor{X};
varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];
varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];
varying vec4 vPositionFromCamera{X};
#if defined(SHADOWPCSS{X})
uniform highp sampler2DArrayShadow shadowSampler{X};
uniform highp sampler2DArray depthSampler{X};
uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];
uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];
uniform float penumbraDarkness{X};
#elif defined(SHADOWPCF{X})
uniform highp sampler2DArrayShadow shadowSampler{X};
#else
uniform highp sampler2DArray shadowSampler{X};
#endif
#ifdef SHADOWCSMDEBUG{X}
const vec3 vCascadeColorsMultiplier{X}[8]=vec3[8]
(
vec3 ( 1.5,0.0,0.0 ),
vec3 ( 0.0,1.5,0.0 ),
vec3 ( 0.0,0.0,5.5 ),
vec3 ( 1.5,0.0,5.5 ),
vec3 ( 1.5,1.5,0.0 ),
vec3 ( 1.0,1.0,1.0 ),
vec3 ( 0.0,1.0,5.5 ),
vec3 ( 0.5,3.5,0.75 )
);
vec3 shadowDebug{X};
#endif
#ifdef SHADOWCSMUSESHADOWMAXZ{X}
int index{X}=-1;
#else
int index{X}=SHADOWCSMNUM_CASCADES{X}-1;
#endif
float diff{X}=0.;
#elif defined(SHADOWCUBE{X})
uniform samplerCube shadowSampler{X};
#else
varying vec4 vPositionFromLight{X};
varying float vDepthMetric{X};
#if defined(SHADOWPCSS{X})
uniform highp sampler2DShadow shadowSampler{X};
uniform highp sampler2D depthSampler{X};
#elif defined(SHADOWPCF{X})
uniform highp sampler2DShadow shadowSampler{X};
#else
uniform sampler2D shadowSampler{X};
#endif
uniform mat4 lightMatrix{X};
#endif
#endif
#endif`;
ShaderStore.IncludesShadersStore[name$2i] = shader$2i;
var name$2h = "lightsFragmentFunctions"
  , shader$2h = `
struct lightingInfo
{
vec3 diffuse;
#ifdef SPECULARTERM
vec3 specular;
#endif
#ifdef NDOTL
float ndl;
#endif
};
lightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {
lightingInfo result;
vec3 lightVectorW;
float attenuation=1.0;
if (lightData.w == 0.)
{
vec3 direction=lightData.xyz-vPositionW;
attenuation=max(0.,1.0-length(direction)/range);
lightVectorW=normalize(direction);
}
else
{
lightVectorW=normalize(-lightData.xyz);
}

float ndl=max(0.,dot(vNormal,lightVectorW));
#ifdef NDOTL
result.ndl=ndl;
#endif
result.diffuse=ndl*diffuseColor*attenuation;
#ifdef SPECULARTERM

vec3 angleW=normalize(viewDirectionW+lightVectorW);
float specComp=max(0.,dot(vNormal,angleW));
specComp=pow(specComp,max(1.,glossiness));
result.specular=specComp*specularColor*attenuation;
#endif
return result;
}
lightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {
lightingInfo result;
vec3 direction=lightData.xyz-vPositionW;
vec3 lightVectorW=normalize(direction);
float attenuation=max(0.,1.0-length(direction)/range);

float cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));
if (cosAngle>=lightDirection.w)
{
cosAngle=max(0.,pow(cosAngle,lightData.w));
attenuation*=cosAngle;

float ndl=max(0.,dot(vNormal,lightVectorW));
#ifdef NDOTL
result.ndl=ndl;
#endif
result.diffuse=ndl*diffuseColor*attenuation;
#ifdef SPECULARTERM

vec3 angleW=normalize(viewDirectionW+lightVectorW);
float specComp=max(0.,dot(vNormal,angleW));
specComp=pow(specComp,max(1.,glossiness));
result.specular=specComp*specularColor*attenuation;
#endif
return result;
}
result.diffuse=vec3(0.);
#ifdef SPECULARTERM
result.specular=vec3(0.);
#endif
#ifdef NDOTL
result.ndl=0.;
#endif
return result;
}
lightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {
lightingInfo result;

float ndl=dot(vNormal,lightData.xyz)*0.5+0.5;
#ifdef NDOTL
result.ndl=ndl;
#endif
result.diffuse=mix(groundColor,diffuseColor,ndl);
#ifdef SPECULARTERM

vec3 angleW=normalize(viewDirectionW+lightData.xyz);
float specComp=max(0.,dot(vNormal,angleW));
specComp=pow(specComp,max(1.,glossiness));
result.specular=specComp*specularColor;
#endif
return result;
}
#define inline
vec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){
vec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);
strq/=strq.w;
vec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;
return textureColor;
}`;
ShaderStore.IncludesShadersStore[name$2h] = shader$2h;
var name$2g = "shadowsFragmentFunctions"
  , shader$2g = `#ifdef SHADOWS
#ifndef SHADOWFLOAT

float unpack(vec4 color)
{
const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);
return dot(color,bit_shift);
}
#endif
float computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)
{
float mask=smoothstep(1.0-frustumEdgeFalloff,1.00000012,clamp(dot(clipSpace,clipSpace),0.,1.));
return mix(value,1.0,mask);
}
#define inline
float computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)
{
vec3 directionToLight=vPositionW-lightPosition;
float depth=length(directionToLight);
depth=(depth+depthValues.x)/(depthValues.y);
depth=clamp(depth,0.,1.0);
directionToLight=normalize(directionToLight);
directionToLight.y=-directionToLight.y;
#ifndef SHADOWFLOAT
float shadow=unpack(textureCube(shadowSampler,directionToLight));
#else
float shadow=textureCube(shadowSampler,directionToLight).x;
#endif
return depth>shadow ? darkness : 1.0;
}
#define inline
float computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)
{
vec3 directionToLight=vPositionW-lightPosition;
float depth=length(directionToLight);
depth=(depth+depthValues.x)/(depthValues.y);
depth=clamp(depth,0.,1.0);
directionToLight=normalize(directionToLight);
directionToLight.y=-directionToLight.y;
float visibility=1.;
vec3 poissonDisk[4];
poissonDisk[0]=vec3(-1.0,1.0,-1.0);
poissonDisk[1]=vec3(1.0,-1.0,-1.0);
poissonDisk[2]=vec3(-1.0,-1.0,-1.0);
poissonDisk[3]=vec3(1.0,-1.0,1.0);

#ifndef SHADOWFLOAT
if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;
if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;
if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;
if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;
#else
if (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;
if (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;
if (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;
if (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;
#endif
return min(1.0,visibility+darkness);
}
#define inline
float computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)
{
vec3 directionToLight=vPositionW-lightPosition;
float depth=length(directionToLight);
depth=(depth+depthValues.x)/(depthValues.y);
float shadowPixelDepth=clamp(depth,0.,1.0);
directionToLight=normalize(directionToLight);
directionToLight.y=-directionToLight.y;
#ifndef SHADOWFLOAT
float shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));
#else
float shadowMapSample=textureCube(shadowSampler,directionToLight).x;
#endif
float esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);
return esm;
}
#define inline
float computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)
{
vec3 directionToLight=vPositionW-lightPosition;
float depth=length(directionToLight);
depth=(depth+depthValues.x)/(depthValues.y);
float shadowPixelDepth=clamp(depth,0.,1.0);
directionToLight=normalize(directionToLight);
directionToLight.y=-directionToLight.y;
#ifndef SHADOWFLOAT
float shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));
#else
float shadowMapSample=textureCube(shadowSampler,directionToLight).x;
#endif
float esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);
return esm;
}
#if defined(WEBGL2) || defined(WEBGPU)
#define inline
float computeShadowCSM(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray shadowSampler,float darkness,float frustumEdgeFalloff)
{
vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;
vec2 uv=0.5*clipSpace.xy+vec2(0.5);
vec3 uvLayer=vec3(uv.x,uv.y,layer);
float shadowPixelDepth=clamp(depthMetric,0.,1.0);
#ifndef SHADOWFLOAT
float shadow=unpack(texture2D(shadowSampler,uvLayer));
#else
float shadow=texture2D(shadowSampler,uvLayer).x;
#endif
return shadowPixelDepth>shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;
}
#endif
#define inline
float computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)
{
vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;
vec2 uv=0.5*clipSpace.xy+vec2(0.5);
if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)
{
return 1.0;
}
else
{
float shadowPixelDepth=clamp(depthMetric,0.,1.0);
#ifndef SHADOWFLOAT
float shadow=unpack(texture2D(shadowSampler,uv));
#else
float shadow=texture2D(shadowSampler,uv).x;
#endif
return shadowPixelDepth>shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;
}
}
#define inline
float computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)
{
vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;
vec2 uv=0.5*clipSpace.xy+vec2(0.5);
if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)
{
return 1.0;
}
else
{
float shadowPixelDepth=clamp(depthMetric,0.,1.0);
float visibility=1.;
vec2 poissonDisk[4];
poissonDisk[0]=vec2(-0.94201624,-0.39906216);
poissonDisk[1]=vec2(0.94558609,-0.76890725);
poissonDisk[2]=vec2(-0.094184101,-0.92938870);
poissonDisk[3]=vec2(0.34495938,0.29387760);

#ifndef SHADOWFLOAT
if (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;
if (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;
if (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;
if (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;
#else
if (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;
if (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;
if (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;
if (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;
#endif
return computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);
}
}
#define inline
float computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)
{
vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;
vec2 uv=0.5*clipSpace.xy+vec2(0.5);
if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)
{
return 1.0;
}
else
{
float shadowPixelDepth=clamp(depthMetric,0.,1.0);
#ifndef SHADOWFLOAT
float shadowMapSample=unpack(texture2D(shadowSampler,uv));
#else
float shadowMapSample=texture2D(shadowSampler,uv).x;
#endif
float esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);
return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);
}
}
#define inline
float computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)
{
vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;
vec2 uv=0.5*clipSpace.xy+vec2(0.5);
if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)
{
return 1.0;
}
else
{
float shadowPixelDepth=clamp(depthMetric,0.,1.0);
#ifndef SHADOWFLOAT
float shadowMapSample=unpack(texture2D(shadowSampler,uv));
#else
float shadowMapSample=texture2D(shadowSampler,uv).x;
#endif
float esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);
return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);
}
}
#ifdef IS_NDC_HALF_ZRANGE
#define ZINCLIP clipSpace.z
#else
#define ZINCLIP uvDepth.z
#endif
#if defined(WEBGL2) || defined(WEBGPU)
#define GREATEST_LESS_THAN_ONE 0.99999994

#define inline
float computeShadowWithCSMPCF1(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,float darkness,float frustumEdgeFalloff)
{
vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;
vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));
uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);
vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);
float shadow=texture2D(shadowSampler,uvDepthLayer);
shadow=mix(darkness,1.,shadow);
return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);
}



#define inline
float computeShadowWithCSMPCF3(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)
{
vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;
vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));
uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);
vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x;
uv+=0.5;
vec2 st=fract(uv);
vec2 base_uv=floor(uv)-0.5;
base_uv*=shadowMapSizeAndInverse.y;




vec2 uvw0=3.-2.*st;
vec2 uvw1=1.+2.*st;
vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;
vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;
float shadow=0.;
shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));
shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));
shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));
shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));
shadow=shadow/16.;
shadow=mix(darkness,1.,shadow);
return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);
}



#define inline
float computeShadowWithCSMPCF5(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)
{
vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;
vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));
uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);
vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x;
uv+=0.5;
vec2 st=fract(uv);
vec2 base_uv=floor(uv)-0.5;
base_uv*=shadowMapSizeAndInverse.y;


vec2 uvw0=4.-3.*st;
vec2 uvw1=vec2(7.);
vec2 uvw2=1.+3.*st;
vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;
vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;
float shadow=0.;
shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));
shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));
shadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[0]),layer,uvDepth.z));
shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));
shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));
shadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[1]),layer,uvDepth.z));
shadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[2]),layer,uvDepth.z));
shadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[2]),layer,uvDepth.z));
shadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[2]),layer,uvDepth.z));
shadow=shadow/144.;
shadow=mix(darkness,1.,shadow);
return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);
}

#define inline
float computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)
{
if (depthMetric>1.0 || depthMetric<0.0) {
return 1.0;
}
else
{
vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;
vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));
uvDepth.z=ZINCLIP;
float shadow=texture2D(shadowSampler,uvDepth);
shadow=mix(darkness,1.,shadow);
return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);
}
}



#define inline
float computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)
{
if (depthMetric>1.0 || depthMetric<0.0) {
return 1.0;
}
else
{
vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;
vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));
uvDepth.z=ZINCLIP;
vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x;
uv+=0.5;
vec2 st=fract(uv);
vec2 base_uv=floor(uv)-0.5;
base_uv*=shadowMapSizeAndInverse.y;




vec2 uvw0=3.-2.*st;
vec2 uvw1=1.+2.*st;
vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;
vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;
float shadow=0.;
shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));
shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));
shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));
shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));
shadow=shadow/16.;
shadow=mix(darkness,1.,shadow);
return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);
}
}



#define inline
float computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)
{
if (depthMetric>1.0 || depthMetric<0.0) {
return 1.0;
}
else
{
vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;
vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));
uvDepth.z=ZINCLIP;
vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x;
uv+=0.5;
vec2 st=fract(uv);
vec2 base_uv=floor(uv)-0.5;
base_uv*=shadowMapSizeAndInverse.y;


vec2 uvw0=4.-3.*st;
vec2 uvw1=vec2(7.);
vec2 uvw2=1.+3.*st;
vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;
vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;
float shadow=0.;
shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));
shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));
shadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));
shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));
shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));
shadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));
shadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));
shadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));
shadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));
shadow=shadow/144.;
shadow=mix(darkness,1.,shadow);
return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);
}
}
const vec3 PoissonSamplers32[64]=vec3[64](
vec3(0.06407013,0.05409927,0.),
vec3(0.7366577,0.5789394,0.),
vec3(-0.6270542,-0.5320278,0.),
vec3(-0.4096107,0.8411095,0.),
vec3(0.6849564,-0.4990818,0.),
vec3(-0.874181,-0.04579735,0.),
vec3(0.9989998,0.0009880066,0.),
vec3(-0.004920578,-0.9151649,0.),
vec3(0.1805763,0.9747483,0.),
vec3(-0.2138451,0.2635818,0.),
vec3(0.109845,0.3884785,0.),
vec3(0.06876755,-0.3581074,0.),
vec3(0.374073,-0.7661266,0.),
vec3(0.3079132,-0.1216763,0.),
vec3(-0.3794335,-0.8271583,0.),
vec3(-0.203878,-0.07715034,0.),
vec3(0.5912697,0.1469799,0.),
vec3(-0.88069,0.3031784,0.),
vec3(0.5040108,0.8283722,0.),
vec3(-0.5844124,0.5494877,0.),
vec3(0.6017799,-0.1726654,0.),
vec3(-0.5554981,0.1559997,0.),
vec3(-0.3016369,-0.3900928,0.),
vec3(-0.5550632,-0.1723762,0.),
vec3(0.925029,0.2995041,0.),
vec3(-0.2473137,0.5538505,0.),
vec3(0.9183037,-0.2862392,0.),
vec3(0.2469421,0.6718712,0.),
vec3(0.3916397,-0.4328209,0.),
vec3(-0.03576927,-0.6220032,0.),
vec3(-0.04661255,0.7995201,0.),
vec3(0.4402924,0.3640312,0.),
vec3(0.,0.,0.),
vec3(0.,0.,0.),
vec3(0.,0.,0.),
vec3(0.,0.,0.),
vec3(0.,0.,0.),
vec3(0.,0.,0.),
vec3(0.,0.,0.),
vec3(0.,0.,0.),
vec3(0.,0.,0.),
vec3(0.,0.,0.),
vec3(0.,0.,0.),
vec3(0.,0.,0.),
vec3(0.,0.,0.),
vec3(0.,0.,0.),
vec3(0.,0.,0.),
vec3(0.,0.,0.),
vec3(0.,0.,0.),
vec3(0.,0.,0.),
vec3(0.,0.,0.),
vec3(0.,0.,0.),
vec3(0.,0.,0.),
vec3(0.,0.,0.),
vec3(0.,0.,0.),
vec3(0.,0.,0.),
vec3(0.,0.,0.),
vec3(0.,0.,0.),
vec3(0.,0.,0.),
vec3(0.,0.,0.),
vec3(0.,0.,0.),
vec3(0.,0.,0.),
vec3(0.,0.,0.),
vec3(0.,0.,0.)
);
const vec3 PoissonSamplers64[64]=vec3[64](
vec3(-0.613392,0.617481,0.),
vec3(0.170019,-0.040254,0.),
vec3(-0.299417,0.791925,0.),
vec3(0.645680,0.493210,0.),
vec3(-0.651784,0.717887,0.),
vec3(0.421003,0.027070,0.),
vec3(-0.817194,-0.271096,0.),
vec3(-0.705374,-0.668203,0.),
vec3(0.977050,-0.108615,0.),
vec3(0.063326,0.142369,0.),
vec3(0.203528,0.214331,0.),
vec3(-0.667531,0.326090,0.),
vec3(-0.098422,-0.295755,0.),
vec3(-0.885922,0.215369,0.),
vec3(0.566637,0.605213,0.),
vec3(0.039766,-0.396100,0.),
vec3(0.751946,0.453352,0.),
vec3(0.078707,-0.715323,0.),
vec3(-0.075838,-0.529344,0.),
vec3(0.724479,-0.580798,0.),
vec3(0.222999,-0.215125,0.),
vec3(-0.467574,-0.405438,0.),
vec3(-0.248268,-0.814753,0.),
vec3(0.354411,-0.887570,0.),
vec3(0.175817,0.382366,0.),
vec3(0.487472,-0.063082,0.),
vec3(-0.084078,0.898312,0.),
vec3(0.488876,-0.783441,0.),
vec3(0.470016,0.217933,0.),
vec3(-0.696890,-0.549791,0.),
vec3(-0.149693,0.605762,0.),
vec3(0.034211,0.979980,0.),
vec3(0.503098,-0.308878,0.),
vec3(-0.016205,-0.872921,0.),
vec3(0.385784,-0.393902,0.),
vec3(-0.146886,-0.859249,0.),
vec3(0.643361,0.164098,0.),
vec3(0.634388,-0.049471,0.),
vec3(-0.688894,0.007843,0.),
vec3(0.464034,-0.188818,0.),
vec3(-0.440840,0.137486,0.),
vec3(0.364483,0.511704,0.),
vec3(0.034028,0.325968,0.),
vec3(0.099094,-0.308023,0.),
vec3(0.693960,-0.366253,0.),
vec3(0.678884,-0.204688,0.),
vec3(0.001801,0.780328,0.),
vec3(0.145177,-0.898984,0.),
vec3(0.062655,-0.611866,0.),
vec3(0.315226,-0.604297,0.),
vec3(-0.780145,0.486251,0.),
vec3(-0.371868,0.882138,0.),
vec3(0.200476,0.494430,0.),
vec3(-0.494552,-0.711051,0.),
vec3(0.612476,0.705252,0.),
vec3(-0.578845,-0.768792,0.),
vec3(-0.772454,-0.090976,0.),
vec3(0.504440,0.372295,0.),
vec3(0.155736,0.065157,0.),
vec3(0.391522,0.849605,0.),
vec3(-0.620106,-0.328104,0.),
vec3(0.789239,-0.419965,0.),
vec3(-0.545396,0.538133,0.),
vec3(-0.178564,-0.596057,0.)
);





#define inline
float computeShadowWithCSMPCSS(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness)
{
vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;
vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));
uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);
vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);
float blockerDepth=0.0;
float sumBlockerDepth=0.0;
float numBlocker=0.0;
for (int i=0; i<searchTapCount; i ++) {
blockerDepth=texture2D(depthSampler,vec3(uvDepth.xy+(lightSizeUV*lightSizeUVCorrection*shadowMapSizeInverse*PoissonSamplers32[i].xy),layer)).r;
if (blockerDepth<depthMetric) {
sumBlockerDepth+=blockerDepth;
numBlocker++;
}
}
if (numBlocker<1.0) {
return 1.0;
}
else
{
float avgBlockerDepth=sumBlockerDepth/numBlocker;

float AAOffset=shadowMapSizeInverse*10.;


float penumbraRatio=((depthMetric-avgBlockerDepth)*depthCorrection+AAOffset);
vec4 filterRadius=vec4(penumbraRatio*lightSizeUV*lightSizeUVCorrection*shadowMapSizeInverse,0.,0.);
float random=getRand(vPositionFromLight.xy);
float rotationAngle=random*3.1415926;
vec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));
float shadow=0.;
for (int i=0; i<pcfTapCount; i++) {
vec4 offset=vec4(poissonSamplers[i],0.);

offset=vec4(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.,0.);
shadow+=texture2D(shadowSampler,uvDepthLayer+offset*filterRadius);
}
shadow/=float(pcfTapCount);

shadow=mix(shadow,1.,min((depthMetric-avgBlockerDepth)*depthCorrection*penumbraDarkness,1.));

shadow=mix(darkness,1.,shadow);

return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);
}
}





#define inline
float computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)
{
if (depthMetric>1.0 || depthMetric<0.0) {
return 1.0;
}
else
{
vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;
vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));
uvDepth.z=ZINCLIP;
float blockerDepth=0.0;
float sumBlockerDepth=0.0;
float numBlocker=0.0;
for (int i=0; i<searchTapCount; i ++) {
blockerDepth=texture2D(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;
if (blockerDepth<depthMetric) {
sumBlockerDepth+=blockerDepth;
numBlocker++;
}
}
if (numBlocker<1.0) {
return 1.0;
}
else
{
float avgBlockerDepth=sumBlockerDepth/numBlocker;

float AAOffset=shadowMapSizeInverse*10.;


float penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);
float filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;
float random=getRand(vPositionFromLight.xy);
float rotationAngle=random*3.1415926;
vec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));
float shadow=0.;
for (int i=0; i<pcfTapCount; i++) {
vec3 offset=poissonSamplers[i];

offset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);
shadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);
}
shadow/=float(pcfTapCount);

shadow=mix(shadow,1.,depthMetric-avgBlockerDepth);

shadow=mix(darkness,1.,shadow);

return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);
}
}
}
#define inline
float computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)
{
return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);
}
#define inline
float computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)
{
return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);
}
#define inline
float computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)
{
return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);
}
#define inline
float computeShadowWithCSMPCSS16(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness)
{
return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);
}
#define inline
float computeShadowWithCSMPCSS32(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness)
{
return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);
}
#define inline
float computeShadowWithCSMPCSS64(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness)
{
return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64,lightSizeUVCorrection,depthCorrection,penumbraDarkness);
}
#endif
#endif
`;
ShaderStore.IncludesShadersStore[name$2g] = shader$2g;
var name$2f = "samplerFragmentDeclaration"
  , shader$2f = `#ifdef _DEFINENAME_
#if _DEFINENAME_DIRECTUV == 1
#define v_VARYINGNAME_UV vMainUV1
#elif _DEFINENAME_DIRECTUV == 2
#define v_VARYINGNAME_UV vMainUV2
#elif _DEFINENAME_DIRECTUV == 3
#define v_VARYINGNAME_UV vMainUV3
#elif _DEFINENAME_DIRECTUV == 4
#define v_VARYINGNAME_UV vMainUV4
#elif _DEFINENAME_DIRECTUV == 5
#define v_VARYINGNAME_UV vMainUV5
#elif _DEFINENAME_DIRECTUV == 6
#define v_VARYINGNAME_UV vMainUV6
#else
varying vec2 v_VARYINGNAME_UV;
#endif
uniform sampler2D _SAMPLERNAME_Sampler;
#endif
`;
ShaderStore.IncludesShadersStore[name$2f] = shader$2f;
var name$2e = "fresnelFunction"
  , shader$2e = `#ifdef FRESNEL
float computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)
{
float fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);
return clamp(fresnelTerm,0.,1.);
}
#endif`;
ShaderStore.IncludesShadersStore[name$2e] = shader$2e;
var name$2d = "reflectionFunction"
  , shader$2d = `vec3 computeFixedEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 direction)
{
float lon=atan(direction.z,direction.x);
float lat=acos(direction.y);
vec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;
float s=sphereCoords.x*0.5+0.5;
float t=sphereCoords.y;
return vec3(s,t,0);
}
vec3 computeMirroredFixedEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 direction)
{
float lon=atan(direction.z,direction.x);
float lat=acos(direction.y);
vec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;
float s=sphereCoords.x*0.5+0.5;
float t=sphereCoords.y;
return vec3(1.0-s,t,0);
}
vec3 computeEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix)
{
vec3 cameraToVertex=normalize(worldPos.xyz-eyePosition);
vec3 r=normalize(reflect(cameraToVertex,worldNormal));
r=vec3(reflectionMatrix*vec4(r,0));
float lon=atan(r.z,r.x);
float lat=acos(r.y);
vec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;
float s=sphereCoords.x*0.5+0.5;
float t=sphereCoords.y;
return vec3(s,t,0);
}
vec3 computeSphericalCoords(vec4 worldPos,vec3 worldNormal,mat4 view,mat4 reflectionMatrix)
{
vec3 viewDir=normalize(vec3(view*worldPos));
vec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));
vec3 r=reflect(viewDir,viewNormal);
r=vec3(reflectionMatrix*vec4(r,0));
r.z=r.z-1.0;
float m=2.0*length(r);
return vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);
}
vec3 computePlanarCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix)
{
vec3 viewDir=worldPos.xyz-eyePosition;
vec3 coords=normalize(reflect(viewDir,worldNormal));
return vec3(reflectionMatrix*vec4(coords,1));
}
vec3 computeCubicCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix)
{
vec3 viewDir=normalize(worldPos.xyz-eyePosition);

vec3 coords=reflect(viewDir,worldNormal);
coords=vec3(reflectionMatrix*vec4(coords,0));
#ifdef INVERTCUBICMAP
coords.y*=-1.0;
#endif
return coords;
}
vec3 computeCubicLocalCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix,vec3 reflectionSize,vec3 reflectionPosition)
{
vec3 viewDir=normalize(worldPos.xyz-eyePosition);

vec3 coords=reflect(viewDir,worldNormal);
coords=parallaxCorrectNormal(worldPos.xyz,coords,reflectionSize,reflectionPosition);
coords=vec3(reflectionMatrix*vec4(coords,0));
#ifdef INVERTCUBICMAP
coords.y*=-1.0;
#endif
return coords;
}
vec3 computeProjectionCoords(vec4 worldPos,mat4 view,mat4 reflectionMatrix)
{
return vec3(reflectionMatrix*(view*worldPos));
}
vec3 computeSkyBoxCoords(vec3 positionW,mat4 reflectionMatrix)
{
return vec3(reflectionMatrix*vec4(positionW,1.));
}
#ifdef REFLECTION
vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)
{
#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED
vec3 direction=normalize(vDirectionW);
return computeMirroredFixedEquirectangularCoords(worldPos,worldNormal,direction);
#endif
#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED
vec3 direction=normalize(vDirectionW);
return computeFixedEquirectangularCoords(worldPos,worldNormal,direction);
#endif
#ifdef REFLECTIONMAP_EQUIRECTANGULAR
return computeEquirectangularCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix);
#endif
#ifdef REFLECTIONMAP_SPHERICAL
return computeSphericalCoords(worldPos,worldNormal,view,reflectionMatrix);
#endif
#ifdef REFLECTIONMAP_PLANAR
return computePlanarCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix);
#endif
#ifdef REFLECTIONMAP_CUBIC
#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC
return computeCubicLocalCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix,vReflectionSize,vReflectionPosition);
#else
return computeCubicCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix);
#endif
#endif
#ifdef REFLECTIONMAP_PROJECTION
return computeProjectionCoords(worldPos,view,reflectionMatrix);
#endif
#ifdef REFLECTIONMAP_SKYBOX
return computeSkyBoxCoords(vPositionUVW,reflectionMatrix);
#endif
#ifdef REFLECTIONMAP_EXPLICIT
return vec3(0,0,0);
#endif
}
#endif`;
ShaderStore.IncludesShadersStore[name$2d] = shader$2d;
var name$2c = "imageProcessingDeclaration"
  , shader$2c = `#ifdef EXPOSURE
uniform float exposureLinear;
#endif
#ifdef CONTRAST
uniform float contrast;
#endif
#ifdef VIGNETTE
uniform vec2 vInverseScreenSize;
uniform vec4 vignetteSettings1;
uniform vec4 vignetteSettings2;
#endif
#ifdef COLORCURVES
uniform vec4 vCameraColorCurveNegative;
uniform vec4 vCameraColorCurveNeutral;
uniform vec4 vCameraColorCurvePositive;
#endif
#ifdef COLORGRADING
#ifdef COLORGRADING3D
uniform highp sampler3D txColorTransform;
#else
uniform sampler2D txColorTransform;
#endif
uniform vec4 colorTransformSettings;
#endif`;
ShaderStore.IncludesShadersStore[name$2c] = shader$2c;
var name$2b = "imageProcessingFunctions"
  , shader$2b = `#if defined(COLORGRADING) && !defined(COLORGRADING3D)

#define inline
vec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)
{
float sliceSize=2.0*sampler3dSetting.x;
#ifdef SAMPLER3DGREENDEPTH
float sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;
#else
float sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;
#endif
float sliceInteger=floor(sliceContinuous);


float sliceFraction=sliceContinuous-sliceInteger;
#ifdef SAMPLER3DGREENDEPTH
vec2 sliceUV=color.rb;
#else
vec2 sliceUV=color.rg;
#endif
sliceUV.x*=sliceSize;
sliceUV.x+=sliceInteger*sliceSize;
sliceUV=saturate(sliceUV);
vec4 slice0Color=texture2D(colorTransform,sliceUV);
sliceUV.x+=sliceSize;
sliceUV=saturate(sliceUV);
vec4 slice1Color=texture2D(colorTransform,sliceUV);
vec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);
#ifdef SAMPLER3DBGRMAP
color.rgb=result.rgb;
#else
color.rgb=result.bgr;
#endif
return color;
}
#endif
#ifdef TONEMAPPING_ACES





const mat3 ACESInputMat=mat3(
vec3(0.59719,0.07600,0.02840),
vec3(0.35458,0.90834,0.13383),
vec3(0.04823,0.01566,0.83777)
);

const mat3 ACESOutputMat=mat3(
vec3( 1.60475,-0.10208,-0.00327),
vec3(-0.53108,1.10813,-0.07276),
vec3(-0.07367,-0.00605,1.07602)
);
vec3 RRTAndODTFit(vec3 v)
{
vec3 a=v*(v+0.0245786)-0.000090537;
vec3 b=v*(0.983729*v+0.4329510)+0.238081;
return a/b;
}
vec3 ACESFitted(vec3 color)
{
color=ACESInputMat*color;

color=RRTAndODTFit(color);
color=ACESOutputMat*color;

color=saturate(color);
return color;
}
#endif
vec4 applyImageProcessing(vec4 result) {
#ifdef EXPOSURE
result.rgb*=exposureLinear;
#endif
#ifdef VIGNETTE

vec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;
viewportXY=viewportXY*2.0-1.0;
vec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);
float vignetteTerm=dot(vignetteXY1,vignetteXY1);
float vignette=pow(vignetteTerm,vignetteSettings2.w);

vec3 vignetteColor=vignetteSettings2.rgb;
#ifdef VIGNETTEBLENDMODEMULTIPLY
vec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);
result.rgb*=vignetteColorMultiplier;
#endif
#ifdef VIGNETTEBLENDMODEOPAQUE
result.rgb=mix(vignetteColor,result.rgb,vignette);
#endif
#endif
#ifdef TONEMAPPING
#ifdef TONEMAPPING_ACES
result.rgb=ACESFitted(result.rgb);
#else
const float tonemappingCalibration=1.590579;
result.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);
#endif
#endif

result.rgb=toGammaSpace(result.rgb);
result.rgb=saturate(result.rgb);
#ifdef CONTRAST

vec3 resultHighContrast=result.rgb*result.rgb*(3.0-2.0*result.rgb);
if (contrast<1.0) {

result.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);
} else {

result.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);
}
#endif

#ifdef COLORGRADING
vec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;
#ifdef COLORGRADING3D
vec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;
#else
vec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;
#endif
result.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);
#endif
#ifdef COLORCURVES

float luma=getLuminance(result.rgb);
vec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));
vec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;
result.rgb*=colorCurve.rgb;
result.rgb=mix(vec3(luma),result.rgb,colorCurve.a);
#endif
return result;
}`;
ShaderStore.IncludesShadersStore[name$2b] = shader$2b;
var name$2a = "bumpFragmentMainFunctions"
  , shader$2a = `#if defined(BUMP) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) || defined(DETAIL)
#if defined(TANGENT) && defined(NORMAL)
varying mat3 vTBN;
#endif
#ifdef OBJECTSPACE_NORMALMAP
uniform mat4 normalMatrix;
#endif
vec3 perturbNormalBase(mat3 cotangentFrame,vec3 normal,float scale)
{
#ifdef NORMALXYSCALE
normal=normalize(normal*vec3(scale,scale,1.0));
#endif
return normalize(cotangentFrame*normal);
}
vec3 perturbNormal(mat3 cotangentFrame,vec3 textureSample,float scale)
{
return perturbNormalBase(cotangentFrame,textureSample*2.0-1.0,scale);
}

mat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv,vec2 tangentSpaceParams)
{

vec3 dp1=dFdx(p);
vec3 dp2=dFdy(p);
vec2 duv1=dFdx(uv);
vec2 duv2=dFdy(uv);

vec3 dp2perp=cross(dp2,normal);
vec3 dp1perp=cross(normal,dp1);
vec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;
vec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;

tangent*=tangentSpaceParams.x;
bitangent*=tangentSpaceParams.y;

float invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));
return mat3(tangent*invmax,bitangent*invmax,normal);
}
#endif
`;
ShaderStore.IncludesShadersStore[name$2a] = shader$2a;
var name$29 = "bumpFragmentFunctions"
  , shader$29 = `#if defined(BUMP)
#include<samplerFragmentDeclaration>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump)
#endif
#if defined(DETAIL)
#include<samplerFragmentDeclaration>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_SAMPLERNAME_,detail)
#endif
#if defined(BUMP) && defined(PARALLAX)
const float minSamples=4.;
const float maxSamples=15.;
const int iMaxSamples=15;

vec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {
float parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;
parallaxLimit*=parallaxScale;
vec2 vOffsetDir=normalize(vViewDirCoT.xy);
vec2 vMaxOffset=vOffsetDir*parallaxLimit;
float numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));
float stepSize=1.0/numSamples;

float currRayHeight=1.0;
vec2 vCurrOffset=vec2(0,0);
vec2 vLastOffset=vec2(0,0);
float lastSampledHeight=1.0;
float currSampledHeight=1.0;
for (int i=0; i<iMaxSamples; i++)
{
currSampledHeight=texture2D(bumpSampler,texCoord+vCurrOffset).w;

if (currSampledHeight>currRayHeight)
{
float delta1=currSampledHeight-currRayHeight;
float delta2=(currRayHeight+stepSize)-lastSampledHeight;
float ratio=delta1/(delta1+delta2);
vCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;

break;
}
else
{
currRayHeight-=stepSize;
vLastOffset=vCurrOffset;
vCurrOffset+=stepSize*vMaxOffset;
lastSampledHeight=currSampledHeight;
}
}
return vCurrOffset;
}
vec2 parallaxOffset(vec3 viewDir,float heightScale)
{

float height=texture2D(bumpSampler,vBumpUV).w;
vec2 texCoordOffset=heightScale*viewDir.xy*height;
return -texCoordOffset;
}
#endif
`;
ShaderStore.IncludesShadersStore[name$29] = shader$29;
var name$28 = "logDepthDeclaration"
  , shader$28 = `#ifdef LOGARITHMICDEPTH
uniform float logarithmicDepthConstant;
varying float vFragmentDepth;
#endif`;
ShaderStore.IncludesShadersStore[name$28] = shader$28;
var name$27 = "fogFragmentDeclaration"
  , shader$27 = `#ifdef FOG
#define FOGMODE_NONE 0.
#define FOGMODE_EXP 1.
#define FOGMODE_EXP2 2.
#define FOGMODE_LINEAR 3.
#define E 2.71828
uniform vec4 vFogInfos;
uniform vec3 vFogColor;
varying vec3 vFogDistance;
float CalcFogFactor()
{
float fogCoeff=1.0;
float fogStart=vFogInfos.y;
float fogEnd=vFogInfos.z;
float fogDensity=vFogInfos.w;
float fogDistance=length(vFogDistance);
if (FOGMODE_LINEAR == vFogInfos.x)
{
fogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);
}
else if (FOGMODE_EXP == vFogInfos.x)
{
fogCoeff=1.0/pow(E,fogDistance*fogDensity);
}
else if (FOGMODE_EXP2 == vFogInfos.x)
{
fogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);
}
return clamp(fogCoeff,0.0,1.0);
}
#endif`;
ShaderStore.IncludesShadersStore[name$27] = shader$27;
var name$26 = "oitFragment"
  , shader$26 = `#ifdef ORDER_INDEPENDENT_TRANSPARENCY



float fragDepth=gl_FragCoord.z;
#ifdef ORDER_INDEPENDENT_TRANSPARENCY_16BITS
uint halfFloat=packHalf2x16(vec2(fragDepth));
vec2 full=unpackHalf2x16(halfFloat);
fragDepth=full.x;
#endif
ivec2 fragCoord=ivec2(gl_FragCoord.xy);
vec2 lastDepth=texelFetch(oitDepthSampler,fragCoord,0).rg;
vec4 lastFrontColor=texelFetch(oitFrontColorSampler,fragCoord,0);


depth.rg=vec2(-MAX_DEPTH);


frontColor=lastFrontColor;

backColor=vec4(0.0);
#ifdef USE_REVERSE_DEPTHBUFFER
float furthestDepth=-lastDepth.x;
float nearestDepth=lastDepth.y;
#else
float nearestDepth=-lastDepth.x;
float furthestDepth=lastDepth.y;
#endif


float alphaMultiplier=1.0-lastFrontColor.a;
#ifdef USE_REVERSE_DEPTHBUFFER
if (fragDepth>nearestDepth || fragDepth<furthestDepth) {
#else
if (fragDepth<nearestDepth || fragDepth>furthestDepth) {
#endif

return;
}
#ifdef USE_REVERSE_DEPTHBUFFER
if (fragDepth<nearestDepth && fragDepth>furthestDepth) {
#else
if (fragDepth>nearestDepth && fragDepth<furthestDepth) {
#endif



depth.rg=vec2(-fragDepth,fragDepth);
return;
}



#endif`;
ShaderStore.IncludesShadersStore[name$26] = shader$26;
var name$25 = "bumpFragment"
  , shader$25 = `vec2 uvOffset=vec2(0.0,0.0);
#if defined(BUMP) || defined(PARALLAX) || defined(DETAIL)
#ifdef NORMALXYSCALE
float normalScale=1.0;
#elif defined(BUMP)
float normalScale=vBumpInfos.y;
#else
float normalScale=1.0;
#endif
#if defined(TANGENT) && defined(NORMAL)
mat3 TBN=vTBN;
#elif defined(BUMP)

vec2 TBNUV=gl_FrontFacing ? vBumpUV : -vBumpUV;
mat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vTangentSpaceParams);
#else

vec2 TBNUV=gl_FrontFacing ? vDetailUV : -vDetailUV;
mat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vec2(1.,1.));
#endif
#elif defined(ANISOTROPIC)
#if defined(TANGENT) && defined(NORMAL)
mat3 TBN=vTBN;
#else

vec2 TBNUV=gl_FrontFacing ? vMainUV1 : -vMainUV1;
mat3 TBN=cotangent_frame(normalW,vPositionW,TBNUV,vec2(1.,1.));
#endif
#endif
#ifdef PARALLAX
mat3 invTBN=transposeMat3(TBN);
#ifdef PARALLAXOCCLUSION
uvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);
#else
uvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);
#endif
#endif
#ifdef DETAIL
vec4 detailColor=texture2D(detailSampler,vDetailUV+uvOffset);
vec2 detailNormalRG=detailColor.wy*2.0-1.0;
float detailNormalB=sqrt(1.-saturate(dot(detailNormalRG,detailNormalRG)));
vec3 detailNormal=vec3(detailNormalRG,detailNormalB);
#endif
#ifdef BUMP
#ifdef OBJECTSPACE_NORMALMAP
normalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);
normalW=normalize(mat3(normalMatrix)*normalW);
#elif !defined(DETAIL)
normalW=perturbNormal(TBN,texture2D(bumpSampler,vBumpUV+uvOffset).xyz,vBumpInfos.y);
#else
vec3 bumpNormal=texture2D(bumpSampler,vBumpUV+uvOffset).xyz*2.0-1.0;

#if DETAIL_NORMALBLENDMETHOD == 0
detailNormal.xy*=vDetailInfos.z;
vec3 blendedNormal=normalize(vec3(bumpNormal.xy+detailNormal.xy,bumpNormal.z*detailNormal.z));
#elif DETAIL_NORMALBLENDMETHOD == 1
detailNormal.xy*=vDetailInfos.z;
bumpNormal+=vec3(0.0,0.0,1.0);
detailNormal*=vec3(-1.0,-1.0,1.0);
vec3 blendedNormal=bumpNormal*dot(bumpNormal,detailNormal)/bumpNormal.z-detailNormal;
#endif
normalW=perturbNormalBase(TBN,blendedNormal,vBumpInfos.y);
#endif
#elif defined(DETAIL)
detailNormal.xy*=vDetailInfos.z;
normalW=perturbNormalBase(TBN,detailNormal,vDetailInfos.z);
#endif
`;
ShaderStore.IncludesShadersStore[name$25] = shader$25;
var name$24 = "depthPrePass"
  , shader$24 = `#ifdef DEPTHPREPASS
gl_FragColor=vec4(0.,0.,0.,1.0);
return;
#endif`;
ShaderStore.IncludesShadersStore[name$24] = shader$24;
var name$23 = "lightFragment"
  , shader$23 = `#ifdef LIGHT{X}
#if defined(SHADOWONLY) || defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})

#else
#ifdef PBR

#ifdef SPOTLIGHT{X}
preInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);
#elif defined(POINTLIGHT{X})
preInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);
#elif defined(HEMILIGHT{X})
preInfo=computeHemisphericPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);
#elif defined(DIRLIGHT{X})
preInfo=computeDirectionalPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);
#endif
preInfo.NdotV=NdotV;

#ifdef SPOTLIGHT{X}
#ifdef LIGHT_FALLOFF_GLTF{X}
preInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y);
preInfo.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);
#elif defined(LIGHT_FALLOFF_PHYSICAL{X})
preInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared);
preInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w);
#elif defined(LIGHT_FALLOFF_STANDARD{X})
preInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x);
preInfo.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w);
#else
preInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);
preInfo.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);
#endif
#elif defined(POINTLIGHT{X})
#ifdef LIGHT_FALLOFF_GLTF{X}
preInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y);
#elif defined(LIGHT_FALLOFF_PHYSICAL{X})
preInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared);
#elif defined(LIGHT_FALLOFF_STANDARD{X})
preInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x);
#else
preInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);
#endif
#else
preInfo.attenuation=1.0;
#endif


#ifdef HEMILIGHT{X}
preInfo.roughness=roughness;
#else
preInfo.roughness=adjustRoughnessFromLightProperties(roughness,light{X}.vLightSpecular.a,preInfo.lightDistance);
#endif

#ifdef HEMILIGHT{X}
info.diffuse=computeHemisphericDiffuseLighting(preInfo,light{X}.vLightDiffuse.rgb,light{X}.vLightGround);
#elif defined(SS_TRANSLUCENCY)
info.diffuse=computeDiffuseAndTransmittedLighting(preInfo,light{X}.vLightDiffuse.rgb,subSurfaceOut.transmittance);
#else
info.diffuse=computeDiffuseLighting(preInfo,light{X}.vLightDiffuse.rgb);
#endif

#ifdef SPECULARTERM
#ifdef ANISOTROPIC
info.specular=computeAnisotropicSpecularLighting(preInfo,viewDirectionW,normalW,anisotropicOut.anisotropicTangent,anisotropicOut.anisotropicBitangent,anisotropicOut.anisotropy,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb);
#else
info.specular=computeSpecularLighting(preInfo,normalW,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb);
#endif
#endif

#ifdef SHEEN
#ifdef SHEEN_LINKWITHALBEDO

preInfo.roughness=sheenOut.sheenIntensity;
#else
#ifdef HEMILIGHT{X}
preInfo.roughness=sheenOut.sheenRoughness;
#else
preInfo.roughness=adjustRoughnessFromLightProperties(sheenOut.sheenRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance);
#endif
#endif
info.sheen=computeSheenLighting(preInfo,normalW,sheenOut.sheenColor,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb);
#endif

#ifdef CLEARCOAT

#ifdef HEMILIGHT{X}
preInfo.roughness=clearcoatOut.clearCoatRoughness;
#else
preInfo.roughness=adjustRoughnessFromLightProperties(clearcoatOut.clearCoatRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance);
#endif
info.clearCoat=computeClearCoatLighting(preInfo,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatAARoughnessFactors.x,clearcoatOut.clearCoatIntensity,light{X}.vLightDiffuse.rgb);
#ifdef CLEARCOAT_TINT

absorption=computeClearCoatLightingAbsorption(clearcoatOut.clearCoatNdotVRefract,preInfo.L,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatColor,clearcoatOut.clearCoatThickness,clearcoatOut.clearCoatIntensity);
info.diffuse*=absorption;
#ifdef SPECULARTERM
info.specular*=absorption;
#endif
#endif

info.diffuse*=info.clearCoat.w;
#ifdef SPECULARTERM
info.specular*=info.clearCoat.w;
#endif
#ifdef SHEEN
info.sheen*=info.clearCoat.w;
#endif
#endif
#else
#ifdef SPOTLIGHT{X}
info=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness);
#elif defined(HEMILIGHT{X})
info=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightGround,glossiness);
#elif defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})
info=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness);
#endif
#endif
#ifdef PROJECTEDLIGHTTEXTURE{X}
info.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});
#endif
#endif
#ifdef SHADOW{X}
#ifdef SHADOWCSM{X}
for (int i=0; i<SHADOWCSMNUM_CASCADES{X}; i++)
{
#ifdef SHADOWCSM_RIGHTHANDED{X}
diff{X}=viewFrustumZ{X}[i]+vPositionFromCamera{X}.z;
#else
diff{X}=viewFrustumZ{X}[i]-vPositionFromCamera{X}.z;
#endif
if (diff{X}>=0.) {
index{X}=i;
break;
}
}
#ifdef SHADOWCSMUSESHADOWMAXZ{X}
if (index{X}>=0)
#endif
{
#if defined(SHADOWPCF{X})
#if defined(SHADOWLOWQUALITY{X})
shadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#elif defined(SHADOWMEDIUMQUALITY{X})
shadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#else
shadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#endif
#elif defined(SHADOWPCSS{X})
#if defined(SHADOWLOWQUALITY{X})
shadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});
#elif defined(SHADOWMEDIUMQUALITY{X})
shadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});
#else
shadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});
#endif
#else
shadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#endif
#ifdef SHADOWCSMDEBUG{X}
shadowDebug{X}=vec3(shadow)*vCascadeColorsMultiplier{X}[index{X}];
#endif
#ifndef SHADOWCSMNOBLEND{X}
float frustumLength=frustumLengths{X}[index{X}];
float diffRatio=clamp(diff{X}/frustumLength,0.,1.)*cascadeBlendFactor{X};
if (index{X}<(SHADOWCSMNUM_CASCADES{X}-1) && diffRatio<1.)
{
index{X}+=1;
float nextShadow=0.;
#if defined(SHADOWPCF{X})
#if defined(SHADOWLOWQUALITY{X})
nextShadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#elif defined(SHADOWMEDIUMQUALITY{X})
nextShadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#else
nextShadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#endif
#elif defined(SHADOWPCSS{X})
#if defined(SHADOWLOWQUALITY{X})
nextShadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});
#elif defined(SHADOWMEDIUMQUALITY{X})
nextShadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});
#else
nextShadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});
#endif
#else
nextShadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#endif
shadow=mix(nextShadow,shadow,diffRatio);
#ifdef SHADOWCSMDEBUG{X}
shadowDebug{X}=mix(vec3(nextShadow)*vCascadeColorsMultiplier{X}[index{X}],shadowDebug{X},diffRatio);
#endif
}
#endif
}
#elif defined(SHADOWCLOSEESM{X})
#if defined(SHADOWCUBE{X})
shadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);
#else
shadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);
#endif
#elif defined(SHADOWESM{X})
#if defined(SHADOWCUBE{X})
shadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);
#else
shadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);
#endif
#elif defined(SHADOWPOISSON{X})
#if defined(SHADOWCUBE{X})
shadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);
#else
shadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#endif
#elif defined(SHADOWPCF{X})
#if defined(SHADOWLOWQUALITY{X})
shadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#elif defined(SHADOWMEDIUMQUALITY{X})
shadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#else
shadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#endif
#elif defined(SHADOWPCSS{X})
#if defined(SHADOWLOWQUALITY{X})
shadow=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);
#elif defined(SHADOWMEDIUMQUALITY{X})
shadow=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);
#else
shadow=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);
#endif
#else
#if defined(SHADOWCUBE{X})
shadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);
#else
shadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#endif
#endif
#ifdef SHADOWONLY
#ifndef SHADOWINUSE
#define SHADOWINUSE
#endif
globalShadow+=shadow;
shadowLightCount+=1.0;
#endif
#else
shadow=1.;
#endif
#ifndef SHADOWONLY
#ifdef CUSTOMUSERLIGHTING
diffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);
#ifdef SPECULARTERM
specularBase+=computeCustomSpecularLighting(info,specularBase,shadow);
#endif
#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})
diffuseBase+=lightmapColor.rgb*shadow;
#ifdef SPECULARTERM
#ifndef LIGHTMAPNOSPECULAR{X}
specularBase+=info.specular*shadow*lightmapColor.rgb;
#endif
#endif
#ifdef CLEARCOAT
#ifndef LIGHTMAPNOSPECULAR{X}
clearCoatBase+=info.clearCoat.rgb*shadow*lightmapColor.rgb;
#endif
#endif
#ifdef SHEEN
#ifndef LIGHTMAPNOSPECULAR{X}
sheenBase+=info.sheen.rgb*shadow;
#endif
#endif
#else
#ifdef SHADOWCSMDEBUG{X}
diffuseBase+=info.diffuse*shadowDebug{X};
#else
diffuseBase+=info.diffuse*shadow;
#endif
#ifdef SPECULARTERM
specularBase+=info.specular*shadow;
#endif
#ifdef CLEARCOAT
clearCoatBase+=info.clearCoat.rgb*shadow;
#endif
#ifdef SHEEN
sheenBase+=info.sheen.rgb*shadow;
#endif
#endif
#endif
#endif`;
ShaderStore.IncludesShadersStore[name$23] = shader$23;
var name$22 = "logDepthFragment"
  , shader$22 = `#ifdef LOGARITHMICDEPTH
gl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;
#endif`;
ShaderStore.IncludesShadersStore[name$22] = shader$22;
var name$21 = "fogFragment"
  , shader$21 = `#ifdef FOG
float fog=CalcFogFactor();
#ifdef PBR
fog=toLinearSpace(fog);
#endif
color.rgb=mix(vFogColor,color.rgb,fog);
#endif`;
ShaderStore.IncludesShadersStore[name$21] = shader$21;
var name$20 = "defaultPixelShader"
  , shader$20 = `#include<__decl__defaultFragment>
#if defined(BUMP) || !defined(NORMAL)
#extension GL_OES_standard_derivatives : enable
#endif
#include<prePassDeclaration>[SCENE_MRT_COUNT]
#include<oitDeclaration>
#define CUSTOM_FRAGMENT_BEGIN
#ifdef LOGARITHMICDEPTH
#extension GL_EXT_frag_depth : enable
#endif

#define RECIPROCAL_PI2 0.15915494

varying vec3 vPositionW;
#ifdef NORMAL
varying vec3 vNormalW;
#endif
#ifdef VERTEXCOLOR
varying vec4 vColor;
#endif
#include<mainUVVaryingDeclaration>[1..7]

#include<helperFunctions>

#include<__decl__lightFragment>[0..maxSimultaneousLights]
#include<lightsFragmentFunctions>
#include<shadowsFragmentFunctions>

#include<samplerFragmentDeclaration>(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_SAMPLERNAME_,diffuse)
#include<samplerFragmentDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient)
#include<samplerFragmentDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity)
#include<samplerFragmentDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive)
#include<samplerFragmentDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap)
#ifdef REFRACTION
#ifdef REFRACTIONMAP_3D
uniform samplerCube refractionCubeSampler;
#else
uniform sampler2D refraction2DSampler;
#endif
#endif
#if defined(SPECULARTERM)
#include<samplerFragmentDeclaration>(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_SAMPLERNAME_,specular)
#endif

#include<fresnelFunction>

#ifdef REFLECTION
#ifdef REFLECTIONMAP_3D
uniform samplerCube reflectionCubeSampler;
#else
uniform sampler2D reflection2DSampler;
#endif
#ifdef REFLECTIONMAP_SKYBOX
varying vec3 vPositionUVW;
#else
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
varying vec3 vDirectionW;
#endif
#endif
#include<reflectionFunction>
#endif
#include<imageProcessingDeclaration>
#include<imageProcessingFunctions>
#include<bumpFragmentMainFunctions>
#include<bumpFragmentFunctions>
#include<clipPlaneFragmentDeclaration>
#include<logDepthDeclaration>
#include<fogFragmentDeclaration>
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void) {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
#include<oitFragment>
#include<clipPlaneFragment>
vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);

vec4 baseColor=vec4(1.,1.,1.,1.);
vec3 diffuseColor=vDiffuseColor.rgb;

float alpha=vDiffuseColor.a;

#ifdef NORMAL
vec3 normalW=normalize(vNormalW);
#else
vec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));
#endif
#include<bumpFragment>
#ifdef TWOSIDEDLIGHTING
normalW=gl_FrontFacing ? normalW : -normalW;
#endif
#ifdef DIFFUSE
baseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);
#if defined(ALPHATEST) && !defined(ALPHATEST_AFTERALLALPHACOMPUTATIONS)
if (baseColor.a<alphaCutOff)
discard;
#endif
#ifdef ALPHAFROMDIFFUSE
alpha*=baseColor.a;
#endif
#define CUSTOM_FRAGMENT_UPDATE_ALPHA
baseColor.rgb*=vDiffuseInfos.y;
#endif
#include<depthPrePass>
#ifdef VERTEXCOLOR
baseColor.rgb*=vColor.rgb;
#endif
#ifdef DETAIL
baseColor.rgb=baseColor.rgb*2.0*mix(0.5,detailColor.r,vDetailInfos.y);
#endif
#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE

vec3 baseAmbientColor=vec3(1.,1.,1.);
#ifdef AMBIENT
baseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;
#endif
#define CUSTOM_FRAGMENT_BEFORE_LIGHTS

#ifdef SPECULARTERM
float glossiness=vSpecularColor.a;
vec3 specularColor=vSpecularColor.rgb;
#ifdef SPECULAR
vec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);
specularColor=specularMapColor.rgb;
#ifdef GLOSSINESS
glossiness=glossiness*specularMapColor.a;
#endif
#endif
#else
float glossiness=0.;
#endif

vec3 diffuseBase=vec3(0.,0.,0.);
lightingInfo info;
#ifdef SPECULARTERM
vec3 specularBase=vec3(0.,0.,0.);
#endif
float shadow=1.;
#ifdef LIGHTMAP
vec4 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset);
#ifdef RGBDLIGHTMAP
lightmapColor.rgb=fromRGBD(lightmapColor);
#endif
lightmapColor.rgb*=vLightmapInfos.y;
#endif
#include<lightFragment>[0..maxSimultaneousLights]

vec4 refractionColor=vec4(0.,0.,0.,1.);
#ifdef REFRACTION
vec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));
#ifdef REFRACTIONMAP_3D
#ifdef USE_LOCAL_REFRACTIONMAP_CUBIC
refractionVector=parallaxCorrectNormal(vPositionW,refractionVector,vRefractionSize,vRefractionPosition);
#endif
refractionVector.y=refractionVector.y*vRefractionInfos.w;
if (dot(refractionVector,viewDirectionW)<1.0) {
refractionColor=textureCube(refractionCubeSampler,refractionVector);
}
#else
vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));
vec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;
refractionCoords.y=1.0-refractionCoords.y;
refractionColor=texture2D(refraction2DSampler,refractionCoords);
#endif
#ifdef RGBDREFRACTION
refractionColor.rgb=fromRGBD(refractionColor);
#endif
#ifdef IS_REFRACTION_LINEAR
refractionColor.rgb=toGammaSpace(refractionColor.rgb);
#endif
refractionColor.rgb*=vRefractionInfos.x;
#endif

vec4 reflectionColor=vec4(0.,0.,0.,1.);
#ifdef REFLECTION
vec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);
#ifdef REFLECTIONMAP_OPPOSITEZ
vReflectionUVW.z*=-1.0;
#endif
#ifdef REFLECTIONMAP_3D
#ifdef ROUGHNESS
float bias=vReflectionInfos.y;
#ifdef SPECULARTERM
#ifdef SPECULAR
#ifdef GLOSSINESS
bias*=(1.0-specularMapColor.a);
#endif
#endif
#endif
reflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias);
#else
reflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW);
#endif
#else
vec2 coords=vReflectionUVW.xy;
#ifdef REFLECTIONMAP_PROJECTION
coords/=vReflectionUVW.z;
#endif
coords.y=1.0-coords.y;
reflectionColor=texture2D(reflection2DSampler,coords);
#endif
#ifdef RGBDREFLECTION
reflectionColor.rgb=fromRGBD(reflectionColor);
#endif
#ifdef IS_REFLECTION_LINEAR
reflectionColor.rgb=toGammaSpace(reflectionColor.rgb);
#endif
reflectionColor.rgb*=vReflectionInfos.x;
#ifdef REFLECTIONFRESNEL
float reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);
#ifdef REFLECTIONFRESNELFROMSPECULAR
#ifdef SPECULARTERM
reflectionColor.rgb*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;
#else
reflectionColor.rgb*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;
#endif
#else
reflectionColor.rgb*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;
#endif
#endif
#endif
#ifdef REFRACTIONFRESNEL
float refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);
refractionColor.rgb*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;
#endif
#ifdef OPACITY
vec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);
#ifdef OPACITYRGB
opacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);
alpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;
#else
alpha*=opacityMap.a*vOpacityInfos.y;
#endif
#endif
#ifdef VERTEXALPHA
alpha*=vColor.a;
#endif
#ifdef OPACITYFRESNEL
float opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);
alpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;
#endif
#ifdef ALPHATEST
#ifdef ALPHATEST_AFTERALLALPHACOMPUTATIONS
if (alpha<alphaCutOff)
discard;
#endif
#ifndef ALPHABLEND

alpha=1.0;
#endif
#endif

vec3 emissiveColor=vEmissiveColor;
#ifdef EMISSIVE
emissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;
#endif
#ifdef EMISSIVEFRESNEL
float emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);
emissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;
#endif

#ifdef DIFFUSEFRESNEL
float diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);
diffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;
#endif

#ifdef EMISSIVEASILLUMINATION
vec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;
#else
#ifdef LINKEMISSIVEWITHDIFFUSE
vec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;
#else
vec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;
#endif
#endif
#ifdef SPECULARTERM
vec3 finalSpecular=specularBase*specularColor;
#ifdef SPECULAROVERALPHA
alpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);
#endif
#else
vec3 finalSpecular=vec3(0.0);
#endif
#ifdef REFLECTIONOVERALPHA
alpha=clamp(alpha+dot(reflectionColor.rgb,vec3(0.3,0.59,0.11)),0.,1.);
#endif

#ifdef EMISSIVEASILLUMINATION
vec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor.rgb+emissiveColor+refractionColor.rgb,0.0,1.0),alpha);
#else
vec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor.rgb+refractionColor.rgb,alpha);
#endif

#ifdef LIGHTMAP
#ifndef LIGHTMAPEXCLUDED
#ifdef USELIGHTMAPASSHADOWMAP
color.rgb*=lightmapColor.rgb;
#else
color.rgb+=lightmapColor.rgb;
#endif
#endif
#endif
#define CUSTOM_FRAGMENT_BEFORE_FOG
color.rgb=max(color.rgb,0.);
#include<logDepthFragment>
#include<fogFragment>


#ifdef IMAGEPROCESSINGPOSTPROCESS
color.rgb=toLinearSpace(color.rgb);
#else
#ifdef IMAGEPROCESSING
color.rgb=toLinearSpace(color.rgb);
color=applyImageProcessing(color);
#endif
#endif
color.a*=visibility;
#ifdef PREMULTIPLYALPHA

color.rgb*=color.a;
#endif
#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR
#ifdef PREPASS
float writeGeometryInfo=color.a>0.4 ? 1.0 : 0.0;
gl_FragData[0]=color;
#ifdef PREPASS_POSITION
gl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo);
#endif
#ifdef PREPASS_VELOCITY
vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;
vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;
vec2 velocity=abs(a-b);
velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;
gl_FragData[PREPASS_VELOCITY_INDEX]=vec4(velocity,0.0,writeGeometryInfo);
#endif
#ifdef PREPASS_IRRADIANCE
gl_FragData[PREPASS_IRRADIANCE_INDEX]=vec4(0.0,0.0,0.0,writeGeometryInfo);
#endif
#ifdef PREPASS_DEPTH
gl_FragData[PREPASS_DEPTH_INDEX]=vec4(vViewPos.z,0.0,0.0,writeGeometryInfo);
#endif
#ifdef PREPASS_NORMAL
gl_FragData[PREPASS_NORMAL_INDEX]=vec4((view*vec4(normalW,0.0)).rgb,writeGeometryInfo);
#endif
#ifdef PREPASS_ALBEDO_SQRT
gl_FragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4(0.0,0.0,0.0,writeGeometryInfo);
#endif
#ifdef PREPASS_REFLECTIVITY
#if defined(SPECULAR)
gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(specularMapColor.rgb,specularMapColor.a*writeGeometryInfo);
#else
gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(0.0,0.0,0.0,writeGeometryInfo);
#endif
#endif
#endif
#if !defined(PREPASS) || defined(WEBGL2)
gl_FragColor=color;
#endif
#if ORDER_INDEPENDENT_TRANSPARENCY
if (fragDepth == nearestDepth) {
frontColor.rgb+=color.rgb*color.a*alphaMultiplier;
frontColor.a=1.0-alphaMultiplier*(1.0-color.a);
} else {
backColor+=color;
}
#endif
}
`;
ShaderStore.ShadersStore[name$20] = shader$20;
var name$1$ = "defaultVertexDeclaration"
  , shader$1$ = `
uniform mat4 viewProjection;
uniform mat4 view;
#ifdef DIFFUSE
uniform mat4 diffuseMatrix;
uniform vec2 vDiffuseInfos;
#endif
#ifdef AMBIENT
uniform mat4 ambientMatrix;
uniform vec2 vAmbientInfos;
#endif
#ifdef OPACITY
uniform mat4 opacityMatrix;
uniform vec2 vOpacityInfos;
#endif
#ifdef EMISSIVE
uniform vec2 vEmissiveInfos;
uniform mat4 emissiveMatrix;
#endif
#ifdef LIGHTMAP
uniform vec2 vLightmapInfos;
uniform mat4 lightmapMatrix;
#endif
#if defined(SPECULAR) && defined(SPECULARTERM)
uniform vec2 vSpecularInfos;
uniform mat4 specularMatrix;
#endif
#ifdef BUMP
uniform vec3 vBumpInfos;
uniform mat4 bumpMatrix;
#endif
#ifdef REFLECTION
uniform mat4 reflectionMatrix;
#endif
#ifdef POINTSIZE
uniform float pointSize;
#endif
#ifdef DETAIL
uniform vec4 vDetailInfos;
uniform mat4 detailMatrix;
#endif`;
ShaderStore.IncludesShadersStore[name$1$] = shader$1$;
var name$1_ = "uvAttributeDeclaration"
  , shader$1_ = `#ifdef UV{X}
attribute vec2 uv{X};
#endif
`;
ShaderStore.IncludesShadersStore[name$1_] = shader$1_;
var name$1Z = "instancesDeclaration"
  , shader$1Z = `#ifdef INSTANCES
attribute vec4 world0;
attribute vec4 world1;
attribute vec4 world2;
attribute vec4 world3;
#if defined(THIN_INSTANCES) && !defined(WORLD_UBO)
uniform mat4 world;
#endif
#if defined(VELOCITY) || defined(PREPASS_VELOCITY)
attribute vec4 previousWorld0;
attribute vec4 previousWorld1;
attribute vec4 previousWorld2;
attribute vec4 previousWorld3;
#ifdef THIN_INSTANCES
uniform mat4 previousWorld;
#endif
#endif
#else
#if !defined(WORLD_UBO)
uniform mat4 world;
#endif
#if defined(VELOCITY) || defined(PREPASS_VELOCITY)
uniform mat4 previousWorld;
#endif
#endif`;
ShaderStore.IncludesShadersStore[name$1Z] = shader$1Z;
var name$1Y = "prePassVertexDeclaration"
  , shader$1Y = `#ifdef PREPASS
#ifdef PREPASS_DEPTH
varying vec3 vViewPos;
#endif
#ifdef PREPASS_VELOCITY
uniform mat4 previousViewProjection;
varying vec4 vCurrentPosition;
varying vec4 vPreviousPosition;
#endif
#endif`;
ShaderStore.IncludesShadersStore[name$1Y] = shader$1Y;
var name$1X = "samplerVertexDeclaration"
  , shader$1X = `#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV == 0
varying vec2 v_VARYINGNAME_UV;
#endif
`;
ShaderStore.IncludesShadersStore[name$1X] = shader$1X;
var name$1W = "bumpVertexDeclaration"
  , shader$1W = `#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC)
#if defined(TANGENT) && defined(NORMAL)
varying mat3 vTBN;
#endif
#endif
`;
ShaderStore.IncludesShadersStore[name$1W] = shader$1W;
var name$1V = "fogVertexDeclaration"
  , shader$1V = `#ifdef FOG
varying vec3 vFogDistance;
#endif`;
ShaderStore.IncludesShadersStore[name$1V] = shader$1V;
var name$1U = "lightVxFragmentDeclaration"
  , shader$1U = `#ifdef LIGHT{X}
uniform vec4 vLightData{X};
uniform vec4 vLightDiffuse{X};
#ifdef SPECULARTERM
uniform vec4 vLightSpecular{X};
#else
vec4 vLightSpecular{X}=vec4(0.);
#endif
#ifdef SHADOW{X}
#ifdef SHADOWCSM{X}
uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];
varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];
varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];
varying vec4 vPositionFromCamera{X};
#elif defined(SHADOWCUBE{X})
#else
varying vec4 vPositionFromLight{X};
varying float vDepthMetric{X};
uniform mat4 lightMatrix{X};
#endif
uniform vec4 shadowsInfo{X};
uniform vec2 depthValues{X};
#endif
#ifdef SPOTLIGHT{X}
uniform vec4 vLightDirection{X};
uniform vec4 vLightFalloff{X};
#elif defined(POINTLIGHT{X})
uniform vec4 vLightFalloff{X};
#elif defined(HEMILIGHT{X})
uniform vec3 vLightGround{X};
#endif
#endif`;
ShaderStore.IncludesShadersStore[name$1U] = shader$1U;
var name$1T = "lightVxUboDeclaration"
  , shader$1T = `#ifdef LIGHT{X}
uniform Light{X}
{
vec4 vLightData;
vec4 vLightDiffuse;
vec4 vLightSpecular;
#ifdef SPOTLIGHT{X}
vec4 vLightDirection;
vec4 vLightFalloff;
#elif defined(POINTLIGHT{X})
vec4 vLightFalloff;
#elif defined(HEMILIGHT{X})
vec3 vLightGround;
#endif
vec4 shadowsInfo;
vec2 depthValues;
} light{X};
#ifdef SHADOW{X}
#ifdef SHADOWCSM{X}
uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];
varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];
varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];
varying vec4 vPositionFromCamera{X};
#elif defined(SHADOWCUBE{X})
#else
varying vec4 vPositionFromLight{X};
varying float vDepthMetric{X};
uniform mat4 lightMatrix{X};
#endif
#endif
#endif`;
ShaderStore.IncludesShadersStore[name$1T] = shader$1T;
var name$1S = "prePassVertex"
  , shader$1S = `#ifdef PREPASS_DEPTH
vViewPos=(view*worldPos).rgb;
#endif
#if defined(PREPASS_VELOCITY) && defined(BONES_VELOCITY_ENABLED)
vCurrentPosition=viewProjection*worldPos;
#if NUM_BONE_INFLUENCERS>0
mat4 previousInfluence;
previousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0];
#if NUM_BONE_INFLUENCERS>1
previousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1];
#endif
#if NUM_BONE_INFLUENCERS>2
previousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2];
#endif
#if NUM_BONE_INFLUENCERS>3
previousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3];
#endif
#if NUM_BONE_INFLUENCERS>4
previousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];
#endif
#if NUM_BONE_INFLUENCERS>5
previousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];
#endif
#if NUM_BONE_INFLUENCERS>6
previousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];
#endif
#if NUM_BONE_INFLUENCERS>7
previousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];
#endif
vPreviousPosition=previousViewProjection*previousWorld*previousInfluence*vec4(positionUpdated,1.0);
#else
vPreviousPosition=previousViewProjection*previousWorld*vec4(positionUpdated,1.0);
#endif
#endif`;
ShaderStore.IncludesShadersStore[name$1S] = shader$1S;
var name$1R = "uvVariableDeclaration"
  , shader$1R = `#if !defined(UV{X}) && defined(MAINUV{X})
vec2 uv{X}=vec2(0.,0.);
#endif
#ifdef MAINUV{X}
vMainUV{X}=uv{X};
#endif
`;
ShaderStore.IncludesShadersStore[name$1R] = shader$1R;
var name$1Q = "samplerVertexImplementation"
  , shader$1Q = `#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV == 0
if (v_INFONAME_ == 0.)
{
v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uvUpdated,1.0,0.0));
}
#ifdef UV2
else if (v_INFONAME_ == 1.)
{
v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv2,1.0,0.0));
}
#endif
#ifdef UV3
else if (v_INFONAME_ == 2.)
{
v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv3,1.0,0.0));
}
#endif
#ifdef UV4
else if (v_INFONAME_ == 3.)
{
v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv4,1.0,0.0));
}
#endif
#ifdef UV5
else if (v_INFONAME_ == 4.)
{
v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv5,1.0,0.0));
}
#endif
#ifdef UV6
else if (v_INFONAME_ == 5.)
{
v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv6,1.0,0.0));
}
#endif
#endif
`;
ShaderStore.IncludesShadersStore[name$1Q] = shader$1Q;
var name$1P = "bumpVertex"
  , shader$1P = `#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC)
#if defined(TANGENT) && defined(NORMAL)
vec3 tbnNormal=normalize(normalUpdated);
vec3 tbnTangent=normalize(tangentUpdated.xyz);
vec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;
vTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);
#endif
#endif`;
ShaderStore.IncludesShadersStore[name$1P] = shader$1P;
var name$1O = "fogVertex"
  , shader$1O = `#ifdef FOG
vFogDistance=(view*worldPos).xyz;
#endif`;
ShaderStore.IncludesShadersStore[name$1O] = shader$1O;
var name$1N = "shadowsVertex"
  , shader$1N = `#ifdef SHADOWS
#if defined(SHADOWCSM{X})
vPositionFromCamera{X}=view*worldPos;
for (int i=0; i<SHADOWCSMNUM_CASCADES{X}; i++) {
vPositionFromLight{X}[i]=lightMatrix{X}[i]*worldPos;
#ifdef USE_REVERSE_DEPTHBUFFER
vDepthMetric{X}[i]=(-vPositionFromLight{X}[i].z+light{X}.depthValues.x)/light{X}.depthValues.y;
#else
vDepthMetric{X}[i]=(vPositionFromLight{X}[i].z+light{X}.depthValues.x)/light{X}.depthValues.y;
#endif
}
#elif defined(SHADOW{X}) && !defined(SHADOWCUBE{X})
vPositionFromLight{X}=lightMatrix{X}*worldPos;
#ifdef USE_REVERSE_DEPTHBUFFER
vDepthMetric{X}=(-vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y;
#else
vDepthMetric{X}=(vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y;
#endif
#endif
#endif`;
ShaderStore.IncludesShadersStore[name$1N] = shader$1N;
var name$1M = "pointCloudVertex"
  , shader$1M = `#ifdef POINTSIZE
gl_PointSize=pointSize;
#endif`;
ShaderStore.IncludesShadersStore[name$1M] = shader$1M;
var name$1L = "logDepthVertex"
  , shader$1L = `#ifdef LOGARITHMICDEPTH
vFragmentDepth=1.0+gl_Position.w;
gl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;
#endif`;
ShaderStore.IncludesShadersStore[name$1L] = shader$1L;
var name$1K = "defaultVertexShader"
  , shader$1K = `#include<__decl__defaultVertex>

#define CUSTOM_VERTEX_BEGIN
attribute vec3 position;
#ifdef NORMAL
attribute vec3 normal;
#endif
#ifdef TANGENT
attribute vec4 tangent;
#endif
#ifdef UV1
attribute vec2 uv;
#endif
#include<uvAttributeDeclaration>[2..7]
#ifdef VERTEXCOLOR
attribute vec4 color;
#endif
#include<helperFunctions>
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>

#include<instancesDeclaration>
#include<prePassVertexDeclaration>
#include<mainUVVaryingDeclaration>[1..7]
#include<samplerVertexDeclaration>(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse)
#include<samplerVertexDeclaration>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail)
#include<samplerVertexDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient)
#include<samplerVertexDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity)
#include<samplerVertexDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive)
#include<samplerVertexDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap)
#if defined(SPECULARTERM)
#include<samplerVertexDeclaration>(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular)
#endif
#include<samplerVertexDeclaration>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump)

varying vec3 vPositionW;
#ifdef NORMAL
varying vec3 vNormalW;
#endif
#ifdef VERTEXCOLOR
varying vec4 vColor;
#endif
#include<bumpVertexDeclaration>
#include<clipPlaneVertexDeclaration>
#include<fogVertexDeclaration>
#include<__decl__lightVxFragment>[0..maxSimultaneousLights]
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
#ifdef REFLECTIONMAP_SKYBOX
varying vec3 vPositionUVW;
#endif
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
varying vec3 vDirectionW;
#endif
#include<logDepthDeclaration>
#define CUSTOM_VERTEX_DEFINITIONS
void main(void) {
#define CUSTOM_VERTEX_MAIN_BEGIN
vec3 positionUpdated=position;
#ifdef NORMAL
vec3 normalUpdated=normal;
#endif
#ifdef TANGENT
vec4 tangentUpdated=tangent;
#endif
#ifdef UV1
vec2 uvUpdated=uv;
#endif
#include<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
#ifdef REFLECTIONMAP_SKYBOX
vPositionUVW=positionUpdated;
#endif
#define CUSTOM_VERTEX_UPDATE_POSITION
#define CUSTOM_VERTEX_UPDATE_NORMAL
#include<instancesVertex>
#if defined(PREPASS) && defined(PREPASS_VELOCITY) && !defined(BONES_VELOCITY_ENABLED)

vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);
vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);
#endif
#include<bonesVertex>
#include<bakedVertexAnimation>
vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);
#ifdef NORMAL
mat3 normalWorld=mat3(finalWorld);
#if defined(INSTANCES) && defined(THIN_INSTANCES)
vNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));
vNormalW=normalize(normalWorld*vNormalW);
#else
#ifdef NONUNIFORMSCALING
normalWorld=transposeMat3(inverseMat3(normalWorld));
#endif
vNormalW=normalize(normalWorld*normalUpdated);
#endif
#endif
#define CUSTOM_VERTEX_UPDATE_WORLDPOS
#ifdef MULTIVIEW
if (gl_ViewID_OVR == 0u) {
gl_Position=viewProjection*worldPos;
} else {
gl_Position=viewProjectionR*worldPos;
}
#else
gl_Position=viewProjection*worldPos;
#endif
vPositionW=vec3(worldPos);
#include<prePassVertex>
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
vDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));
#endif

#ifndef UV1
vec2 uvUpdated=vec2(0.,0.);
#endif
#ifdef MAINUV1
vMainUV1=uvUpdated;
#endif
#include<uvVariableDeclaration>[2..7]
#include<samplerVertexImplementation>(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_MATRIXNAME_,diffuse,_INFONAME_,DiffuseInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x)
#if defined(SPECULARTERM)
#include<samplerVertexImplementation>(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_MATRIXNAME_,specular,_INFONAME_,SpecularInfos.x)
#endif
#include<samplerVertexImplementation>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x)
#include<bumpVertex>
#include<clipPlaneVertex>
#include<fogVertex>
#include<shadowsVertex>[0..maxSimultaneousLights]
#ifdef VERTEXCOLOR

vColor=color;
#endif
#include<pointCloudVertex>
#include<logDepthVertex>
#define CUSTOM_VERTEX_MAIN_END
}
`;
ShaderStore.ShadersStore[name$1K] = shader$1K;
var DetailMapConfiguration = function() {
    function i(e) {
        this._texture = null,
        this.diffuseBlendLevel = 1,
        this.roughnessBlendLevel = 1,
        this.bumpLevel = 1,
        this._normalBlendMethod = Material.MATERIAL_NORMALBLENDMETHOD_WHITEOUT,
        this._isEnabled = !1,
        this.isEnabled = !1,
        this._internalMarkAllSubMeshesAsTexturesDirty = e
    }
    return i.prototype._markAllSubMeshesAsTexturesDirty = function() {
        this._internalMarkAllSubMeshesAsTexturesDirty()
    }
    ,
    i.prototype.isReadyForSubMesh = function(e, t) {
        if (!this._isEnabled)
            return !0;
        var r = t.getEngine();
        return !(e._areTexturesDirty && t.texturesEnabled && r.getCaps().standardDerivatives && this._texture && MaterialFlags.DetailTextureEnabled && !this._texture.isReady())
    }
    ,
    i.prototype.prepareDefines = function(e, t) {
        if (this._isEnabled) {
            e.DETAIL_NORMALBLENDMETHOD = this._normalBlendMethod;
            var r = t.getEngine();
            e._areTexturesDirty && (r.getCaps().standardDerivatives && this._texture && MaterialFlags.DetailTextureEnabled && this._isEnabled ? (MaterialHelper.PrepareDefinesForMergedUV(this._texture, e, "DETAIL"),
            e.DETAIL_NORMALBLENDMETHOD = this._normalBlendMethod) : e.DETAIL = !1)
        } else
            e.DETAIL = !1
    }
    ,
    i.prototype.bindForSubMesh = function(e, t, r) {
        !this._isEnabled || ((!e.useUbo || !r || !e.isSync) && this._texture && MaterialFlags.DetailTextureEnabled && (e.updateFloat4("vDetailInfos", this._texture.coordinatesIndex, this.diffuseBlendLevel, this.bumpLevel, this.roughnessBlendLevel),
        MaterialHelper.BindTextureMatrix(this._texture, e, "detail")),
        t.texturesEnabled && this._texture && MaterialFlags.DetailTextureEnabled && e.setTexture("detailSampler", this._texture))
    }
    ,
    i.prototype.hasTexture = function(e) {
        return this._texture === e
    }
    ,
    i.prototype.getActiveTextures = function(e) {
        this._texture && e.push(this._texture)
    }
    ,
    i.prototype.getAnimatables = function(e) {
        this._texture && this._texture.animations && this._texture.animations.length > 0 && e.push(this._texture)
    }
    ,
    i.prototype.dispose = function(e) {
        var t;
        e && ((t = this._texture) === null || t === void 0 || t.dispose())
    }
    ,
    i.prototype.getClassName = function() {
        return "DetailMapConfiguration"
    }
    ,
    i.AddUniforms = function(e) {
        e.push("vDetailInfos"),
        e.push("detailMatrix")
    }
    ,
    i.AddSamplers = function(e) {
        e.push("detailSampler")
    }
    ,
    i.PrepareUniformBuffer = function(e) {
        e.addUniform("vDetailInfos", 4),
        e.addUniform("detailMatrix", 16)
    }
    ,
    i.prototype.copyTo = function(e) {
        SerializationHelper.Clone(function() {
            return e
        }, this)
    }
    ,
    i.prototype.serialize = function() {
        return SerializationHelper.Serialize(this)
    }
    ,
    i.prototype.parse = function(e, t, r) {
        var n = this;
        SerializationHelper.Parse(function() {
            return n
        }, e, t, r)
    }
    ,
    __decorate([serializeAsTexture("detailTexture"), expandToProperty("_markAllSubMeshesAsTexturesDirty")], i.prototype, "texture", void 0),
    __decorate([serialize()], i.prototype, "diffuseBlendLevel", void 0),
    __decorate([serialize()], i.prototype, "roughnessBlendLevel", void 0),
    __decorate([serialize()], i.prototype, "bumpLevel", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], i.prototype, "normalBlendMethod", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], i.prototype, "isEnabled", void 0),
    i
}()
  , onCreatedEffectParameters$2 = {
    effect: null,
    subMesh: null
}
  , StandardMaterialDefines = function(i) {
    __extends(e, i);
    function e() {
        var t = i.call(this) || this;
        return t.MAINUV1 = !1,
        t.MAINUV2 = !1,
        t.MAINUV3 = !1,
        t.MAINUV4 = !1,
        t.MAINUV5 = !1,
        t.MAINUV6 = !1,
        t.DIFFUSE = !1,
        t.DIFFUSEDIRECTUV = 0,
        t.DETAIL = !1,
        t.DETAILDIRECTUV = 0,
        t.DETAIL_NORMALBLENDMETHOD = 0,
        t.BAKED_VERTEX_ANIMATION_TEXTURE = !1,
        t.AMBIENT = !1,
        t.AMBIENTDIRECTUV = 0,
        t.OPACITY = !1,
        t.OPACITYDIRECTUV = 0,
        t.OPACITYRGB = !1,
        t.REFLECTION = !1,
        t.EMISSIVE = !1,
        t.EMISSIVEDIRECTUV = 0,
        t.SPECULAR = !1,
        t.SPECULARDIRECTUV = 0,
        t.BUMP = !1,
        t.BUMPDIRECTUV = 0,
        t.PARALLAX = !1,
        t.PARALLAXOCCLUSION = !1,
        t.SPECULAROVERALPHA = !1,
        t.CLIPPLANE = !1,
        t.CLIPPLANE2 = !1,
        t.CLIPPLANE3 = !1,
        t.CLIPPLANE4 = !1,
        t.CLIPPLANE5 = !1,
        t.CLIPPLANE6 = !1,
        t.ALPHATEST = !1,
        t.DEPTHPREPASS = !1,
        t.ALPHAFROMDIFFUSE = !1,
        t.POINTSIZE = !1,
        t.FOG = !1,
        t.SPECULARTERM = !1,
        t.DIFFUSEFRESNEL = !1,
        t.OPACITYFRESNEL = !1,
        t.REFLECTIONFRESNEL = !1,
        t.REFRACTIONFRESNEL = !1,
        t.EMISSIVEFRESNEL = !1,
        t.FRESNEL = !1,
        t.NORMAL = !1,
        t.TANGENT = !1,
        t.UV1 = !1,
        t.UV2 = !1,
        t.UV3 = !1,
        t.UV4 = !1,
        t.UV5 = !1,
        t.UV6 = !1,
        t.VERTEXCOLOR = !1,
        t.VERTEXALPHA = !1,
        t.NUM_BONE_INFLUENCERS = 0,
        t.BonesPerMesh = 0,
        t.BONETEXTURE = !1,
        t.BONES_VELOCITY_ENABLED = !1,
        t.INSTANCES = !1,
        t.THIN_INSTANCES = !1,
        t.GLOSSINESS = !1,
        t.ROUGHNESS = !1,
        t.EMISSIVEASILLUMINATION = !1,
        t.LINKEMISSIVEWITHDIFFUSE = !1,
        t.REFLECTIONFRESNELFROMSPECULAR = !1,
        t.LIGHTMAP = !1,
        t.LIGHTMAPDIRECTUV = 0,
        t.OBJECTSPACE_NORMALMAP = !1,
        t.USELIGHTMAPASSHADOWMAP = !1,
        t.REFLECTIONMAP_3D = !1,
        t.REFLECTIONMAP_SPHERICAL = !1,
        t.REFLECTIONMAP_PLANAR = !1,
        t.REFLECTIONMAP_CUBIC = !1,
        t.USE_LOCAL_REFLECTIONMAP_CUBIC = !1,
        t.USE_LOCAL_REFRACTIONMAP_CUBIC = !1,
        t.REFLECTIONMAP_PROJECTION = !1,
        t.REFLECTIONMAP_SKYBOX = !1,
        t.REFLECTIONMAP_EXPLICIT = !1,
        t.REFLECTIONMAP_EQUIRECTANGULAR = !1,
        t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = !1,
        t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = !1,
        t.REFLECTIONMAP_OPPOSITEZ = !1,
        t.INVERTCUBICMAP = !1,
        t.LOGARITHMICDEPTH = !1,
        t.REFRACTION = !1,
        t.REFRACTIONMAP_3D = !1,
        t.REFLECTIONOVERALPHA = !1,
        t.TWOSIDEDLIGHTING = !1,
        t.SHADOWFLOAT = !1,
        t.MORPHTARGETS = !1,
        t.MORPHTARGETS_NORMAL = !1,
        t.MORPHTARGETS_TANGENT = !1,
        t.MORPHTARGETS_UV = !1,
        t.NUM_MORPH_INFLUENCERS = 0,
        t.MORPHTARGETS_TEXTURE = !1,
        t.NONUNIFORMSCALING = !1,
        t.PREMULTIPLYALPHA = !1,
        t.ALPHATEST_AFTERALLALPHACOMPUTATIONS = !1,
        t.ALPHABLEND = !0,
        t.PREPASS = !1,
        t.PREPASS_IRRADIANCE = !1,
        t.PREPASS_IRRADIANCE_INDEX = -1,
        t.PREPASS_ALBEDO_SQRT = !1,
        t.PREPASS_ALBEDO_SQRT_INDEX = -1,
        t.PREPASS_DEPTH = !1,
        t.PREPASS_DEPTH_INDEX = -1,
        t.PREPASS_NORMAL = !1,
        t.PREPASS_NORMAL_INDEX = -1,
        t.PREPASS_POSITION = !1,
        t.PREPASS_POSITION_INDEX = -1,
        t.PREPASS_VELOCITY = !1,
        t.PREPASS_VELOCITY_INDEX = -1,
        t.PREPASS_REFLECTIVITY = !1,
        t.PREPASS_REFLECTIVITY_INDEX = -1,
        t.SCENE_MRT_COUNT = 0,
        t.RGBDLIGHTMAP = !1,
        t.RGBDREFLECTION = !1,
        t.RGBDREFRACTION = !1,
        t.IMAGEPROCESSING = !1,
        t.VIGNETTE = !1,
        t.VIGNETTEBLENDMODEMULTIPLY = !1,
        t.VIGNETTEBLENDMODEOPAQUE = !1,
        t.TONEMAPPING = !1,
        t.TONEMAPPING_ACES = !1,
        t.CONTRAST = !1,
        t.COLORCURVES = !1,
        t.COLORGRADING = !1,
        t.COLORGRADING3D = !1,
        t.SAMPLER3DGREENDEPTH = !1,
        t.SAMPLER3DBGRMAP = !1,
        t.IMAGEPROCESSINGPOSTPROCESS = !1,
        t.SKIPFINALCOLORCLAMP = !1,
        t.MULTIVIEW = !1,
        t.ORDER_INDEPENDENT_TRANSPARENCY = !1,
        t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS = !1,
        t.IS_REFLECTION_LINEAR = !1,
        t.IS_REFRACTION_LINEAR = !1,
        t.EXPOSURE = !1,
        t.rebuild(),
        t
    }
    return e.prototype.setReflectionMode = function(t) {
        for (var r = ["REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX", "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED", "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"], n = 0, o = r; n < o.length; n++) {
            var a = o[n];
            this[a] = a === t
        }
    }
    ,
    e
}(MaterialDefines)
  , StandardMaterial = function(i) {
    __extends(e, i);
    function e(t, r) {
        var n = i.call(this, t, r) || this;
        return n._diffuseTexture = null,
        n._ambientTexture = null,
        n._opacityTexture = null,
        n._reflectionTexture = null,
        n._emissiveTexture = null,
        n._specularTexture = null,
        n._bumpTexture = null,
        n._lightmapTexture = null,
        n._refractionTexture = null,
        n.ambientColor = new Color3(0,0,0),
        n.diffuseColor = new Color3(1,1,1),
        n.specularColor = new Color3(1,1,1),
        n.emissiveColor = new Color3(0,0,0),
        n.specularPower = 64,
        n._useAlphaFromDiffuseTexture = !1,
        n._useEmissiveAsIllumination = !1,
        n._linkEmissiveWithDiffuse = !1,
        n._useSpecularOverAlpha = !1,
        n._useReflectionOverAlpha = !1,
        n._disableLighting = !1,
        n._useObjectSpaceNormalMap = !1,
        n._useParallax = !1,
        n._useParallaxOcclusion = !1,
        n.parallaxScaleBias = .05,
        n._roughness = 0,
        n.indexOfRefraction = .98,
        n.invertRefractionY = !0,
        n.alphaCutOff = .4,
        n._useLightmapAsShadowmap = !1,
        n._useReflectionFresnelFromSpecular = !1,
        n._useGlossinessFromSpecularMapAlpha = !1,
        n._maxSimultaneousLights = 4,
        n._invertNormalMapX = !1,
        n._invertNormalMapY = !1,
        n._twoSidedLighting = !1,
        n.detailMap = new DetailMapConfiguration(n._markAllSubMeshesAsTexturesDirty.bind(n)),
        n._renderTargets = new SmartArray(16),
        n._worldViewProjectionMatrix = Matrix.Zero(),
        n._globalAmbientColor = new Color3(0,0,0),
        n.buildUniformLayout(),
        n._attachImageProcessingConfiguration(null),
        n.prePassConfiguration = new PrePassConfiguration,
        n.getRenderTargetTextures = function() {
            return n._renderTargets.reset(),
            e.ReflectionTextureEnabled && n._reflectionTexture && n._reflectionTexture.isRenderTarget && n._renderTargets.push(n._reflectionTexture),
            e.RefractionTextureEnabled && n._refractionTexture && n._refractionTexture.isRenderTarget && n._renderTargets.push(n._refractionTexture),
            n._renderTargets
        }
        ,
        n
    }
    return Object.defineProperty(e.prototype, "imageProcessingConfiguration", {
        get: function() {
            return this._imageProcessingConfiguration
        },
        set: function(t) {
            this._attachImageProcessingConfiguration(t),
            this._markAllSubMeshesAsTexturesDirty()
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._attachImageProcessingConfiguration = function(t) {
        var r = this;
        t !== this._imageProcessingConfiguration && (this._imageProcessingConfiguration && this._imageProcessingObserver && this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),
        t ? this._imageProcessingConfiguration = t : this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration,
        this._imageProcessingConfiguration && (this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function() {
            r._markAllSubMeshesAsImageProcessingDirty()
        })))
    }
    ,
    Object.defineProperty(e.prototype, "isPrePassCapable", {
        get: function() {
            return !this.disableDepthWrite
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cameraColorCurvesEnabled", {
        get: function() {
            return this.imageProcessingConfiguration.colorCurvesEnabled
        },
        set: function(t) {
            this.imageProcessingConfiguration.colorCurvesEnabled = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cameraColorGradingEnabled", {
        get: function() {
            return this.imageProcessingConfiguration.colorGradingEnabled
        },
        set: function(t) {
            this.imageProcessingConfiguration.colorGradingEnabled = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cameraToneMappingEnabled", {
        get: function() {
            return this._imageProcessingConfiguration.toneMappingEnabled
        },
        set: function(t) {
            this._imageProcessingConfiguration.toneMappingEnabled = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cameraExposure", {
        get: function() {
            return this._imageProcessingConfiguration.exposure
        },
        set: function(t) {
            this._imageProcessingConfiguration.exposure = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cameraContrast", {
        get: function() {
            return this._imageProcessingConfiguration.contrast
        },
        set: function(t) {
            this._imageProcessingConfiguration.contrast = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cameraColorGradingTexture", {
        get: function() {
            return this._imageProcessingConfiguration.colorGradingTexture
        },
        set: function(t) {
            this._imageProcessingConfiguration.colorGradingTexture = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cameraColorCurves", {
        get: function() {
            return this._imageProcessingConfiguration.colorCurves
        },
        set: function(t) {
            this._imageProcessingConfiguration.colorCurves = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "canRenderToMRT", {
        get: function() {
            return !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "hasRenderTargetTextures", {
        get: function() {
            return !!(e.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget || e.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget)
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getClassName = function() {
        return "StandardMaterial"
    }
    ,
    Object.defineProperty(e.prototype, "useLogarithmicDepth", {
        get: function() {
            return this._useLogarithmicDepth
        },
        set: function(t) {
            this._useLogarithmicDepth = t && this.getScene().getEngine().getCaps().fragmentDepthSupported,
            this._markAllSubMeshesAsMiscDirty()
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.needAlphaBlending = function() {
        return this._disableAlphaBlending ? !1 : this.alpha < 1 || this._opacityTexture != null || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled
    }
    ,
    e.prototype.needAlphaTesting = function() {
        return this._forceAlphaTest ? !0 : this._hasAlphaChannel() && (this._transparencyMode == null || this._transparencyMode === Material.MATERIAL_ALPHATEST)
    }
    ,
    e.prototype._shouldUseAlphaFromDiffuseTexture = function() {
        return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture && this._transparencyMode !== Material.MATERIAL_OPAQUE
    }
    ,
    e.prototype._hasAlphaChannel = function() {
        return this._diffuseTexture != null && this._diffuseTexture.hasAlpha || this._opacityTexture != null
    }
    ,
    e.prototype.getAlphaTestTexture = function() {
        return this._diffuseTexture
    }
    ,
    e.prototype.isReadyForSubMesh = function(t, r, n) {
        if (n === void 0 && (n = !1),
        r.effect && this.isFrozen && r.effect._wasPreviouslyReady)
            return !0;
        r.materialDefines || (r.materialDefines = new StandardMaterialDefines);
        var o = this.getScene()
          , a = r.materialDefines;
        if (this._isReadyForSubMesh(r))
            return !0;
        var s = o.getEngine();
        a._needNormals = MaterialHelper.PrepareDefinesForLights(o, t, a, !0, this._maxSimultaneousLights, this._disableLighting),
        MaterialHelper.PrepareDefinesForMultiview(o, a);
        var l = this.needAlphaBlendingForMesh(t) && this.getScene().useOrderIndependentTransparency;
        if (MaterialHelper.PrepareDefinesForPrePass(o, a, this.canRenderToMRT && !l),
        MaterialHelper.PrepareDefinesForOIT(o, a, l),
        a._areTexturesDirty) {
            a._needUVs = !1;
            for (var u = 1; u <= 6; ++u)
                a["MAINUV" + u] = !1;
            if (o.texturesEnabled) {
                if (this._diffuseTexture && e.DiffuseTextureEnabled)
                    if (this._diffuseTexture.isReadyOrNotBlocking())
                        MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, a, "DIFFUSE");
                    else
                        return !1;
                else
                    a.DIFFUSE = !1;
                if (this._ambientTexture && e.AmbientTextureEnabled)
                    if (this._ambientTexture.isReadyOrNotBlocking())
                        MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, a, "AMBIENT");
                    else
                        return !1;
                else
                    a.AMBIENT = !1;
                if (this._opacityTexture && e.OpacityTextureEnabled)
                    if (this._opacityTexture.isReadyOrNotBlocking())
                        MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, a, "OPACITY"),
                        a.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
                    else
                        return !1;
                else
                    a.OPACITY = !1;
                if (this._reflectionTexture && e.ReflectionTextureEnabled)
                    if (this._reflectionTexture.isReadyOrNotBlocking()) {
                        switch (a._needNormals = !0,
                        a.REFLECTION = !0,
                        a.ROUGHNESS = this._roughness > 0,
                        a.REFLECTIONOVERALPHA = this._useReflectionOverAlpha,
                        a.INVERTCUBICMAP = this._reflectionTexture.coordinatesMode === Texture.INVCUBIC_MODE,
                        a.REFLECTIONMAP_3D = this._reflectionTexture.isCube,
                        a.RGBDREFLECTION = this._reflectionTexture.isRGBD,
                        a.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !this._reflectionTexture.invertZ : this._reflectionTexture.invertZ,
                        this._reflectionTexture.coordinatesMode) {
                        case Texture.EXPLICIT_MODE:
                            a.setReflectionMode("REFLECTIONMAP_EXPLICIT");
                            break;
                        case Texture.PLANAR_MODE:
                            a.setReflectionMode("REFLECTIONMAP_PLANAR");
                            break;
                        case Texture.PROJECTION_MODE:
                            a.setReflectionMode("REFLECTIONMAP_PROJECTION");
                            break;
                        case Texture.SKYBOX_MODE:
                            a.setReflectionMode("REFLECTIONMAP_SKYBOX");
                            break;
                        case Texture.SPHERICAL_MODE:
                            a.setReflectionMode("REFLECTIONMAP_SPHERICAL");
                            break;
                        case Texture.EQUIRECTANGULAR_MODE:
                            a.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
                            break;
                        case Texture.FIXED_EQUIRECTANGULAR_MODE:
                            a.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
                            break;
                        case Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
                            a.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
                            break;
                        case Texture.CUBIC_MODE:
                        case Texture.INVCUBIC_MODE:
                        default:
                            a.setReflectionMode("REFLECTIONMAP_CUBIC");
                            break
                        }
                        a.USE_LOCAL_REFLECTIONMAP_CUBIC = !!this._reflectionTexture.boundingBoxSize
                    } else
                        return !1;
                else
                    a.REFLECTION = !1,
                    a.REFLECTIONMAP_OPPOSITEZ = !1;
                if (this._emissiveTexture && e.EmissiveTextureEnabled)
                    if (this._emissiveTexture.isReadyOrNotBlocking())
                        MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, a, "EMISSIVE");
                    else
                        return !1;
                else
                    a.EMISSIVE = !1;
                if (this._lightmapTexture && e.LightmapTextureEnabled)
                    if (this._lightmapTexture.isReadyOrNotBlocking())
                        MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, a, "LIGHTMAP"),
                        a.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap,
                        a.RGBDLIGHTMAP = this._lightmapTexture.isRGBD;
                    else
                        return !1;
                else
                    a.LIGHTMAP = !1;
                if (this._specularTexture && e.SpecularTextureEnabled)
                    if (this._specularTexture.isReadyOrNotBlocking())
                        MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, a, "SPECULAR"),
                        a.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
                    else
                        return !1;
                else
                    a.SPECULAR = !1;
                if (o.getEngine().getCaps().standardDerivatives && this._bumpTexture && e.BumpTextureEnabled) {
                    if (this._bumpTexture.isReady())
                        MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, a, "BUMP"),
                        a.PARALLAX = this._useParallax,
                        a.PARALLAXOCCLUSION = this._useParallaxOcclusion;
                    else
                        return !1;
                    a.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap
                } else
                    a.BUMP = !1;
                if (this._refractionTexture && e.RefractionTextureEnabled)
                    if (this._refractionTexture.isReadyOrNotBlocking())
                        a._needUVs = !0,
                        a.REFRACTION = !0,
                        a.REFRACTIONMAP_3D = this._refractionTexture.isCube,
                        a.RGBDREFRACTION = this._refractionTexture.isRGBD,
                        a.USE_LOCAL_REFRACTIONMAP_CUBIC = !!this._refractionTexture.boundingBoxSize;
                    else
                        return !1;
                else
                    a.REFRACTION = !1;
                a.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting
            } else
                a.DIFFUSE = !1,
                a.AMBIENT = !1,
                a.OPACITY = !1,
                a.REFLECTION = !1,
                a.EMISSIVE = !1,
                a.LIGHTMAP = !1,
                a.BUMP = !1,
                a.REFRACTION = !1;
            a.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture(),
            a.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination,
            a.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse,
            a.SPECULAROVERALPHA = this._useSpecularOverAlpha,
            a.PREMULTIPLYALPHA = this.alphaMode === 7 || this.alphaMode === 8,
            a.ALPHATEST_AFTERALLALPHACOMPUTATIONS = this.transparencyMode !== null,
            a.ALPHABLEND = this.transparencyMode === null || this.needAlphaBlendingForMesh(t)
        }
        if (!this.detailMap.isReadyForSubMesh(a, o))
            return !1;
        if (a._areImageProcessingDirty && this._imageProcessingConfiguration) {
            if (!this._imageProcessingConfiguration.isReady())
                return !1;
            this._imageProcessingConfiguration.prepareDefines(a),
            a.IS_REFLECTION_LINEAR = this.reflectionTexture != null && !this.reflectionTexture.gammaSpace,
            a.IS_REFRACTION_LINEAR = this.refractionTexture != null && !this.refractionTexture.gammaSpace
        }
        if (a._areFresnelDirty && (e.FresnelEnabled ? (this._diffuseFresnelParameters || this._opacityFresnelParameters || this._emissiveFresnelParameters || this._refractionFresnelParameters || this._reflectionFresnelParameters) && (a.DIFFUSEFRESNEL = this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled,
        a.OPACITYFRESNEL = this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled,
        a.REFLECTIONFRESNEL = this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled,
        a.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular,
        a.REFRACTIONFRESNEL = this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled,
        a.EMISSIVEFRESNEL = this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled,
        a._needNormals = !0,
        a.FRESNEL = !0) : a.FRESNEL = !1),
        MaterialHelper.PrepareDefinesForMisc(t, o, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(t) || this._forceAlphaTest, a),
        MaterialHelper.PrepareDefinesForAttributes(t, a, !0, !0, !0),
        MaterialHelper.PrepareDefinesForFrameBoundValues(o, s, a, n, null, r.getRenderingMesh().hasThinInstances),
        this.detailMap.prepareDefines(a, o),
        a.isDirty) {
            var c = a._areLightsDisposed;
            a.markAsProcessed();
            var h = new EffectFallbacks;
            a.REFLECTION && h.addFallback(0, "REFLECTION"),
            a.SPECULAR && h.addFallback(0, "SPECULAR"),
            a.BUMP && h.addFallback(0, "BUMP"),
            a.PARALLAX && h.addFallback(1, "PARALLAX"),
            a.PARALLAXOCCLUSION && h.addFallback(0, "PARALLAXOCCLUSION"),
            a.SPECULAROVERALPHA && h.addFallback(0, "SPECULAROVERALPHA"),
            a.FOG && h.addFallback(1, "FOG"),
            a.POINTSIZE && h.addFallback(0, "POINTSIZE"),
            a.LOGARITHMICDEPTH && h.addFallback(0, "LOGARITHMICDEPTH"),
            MaterialHelper.HandleFallbacksForShadows(a, h, this._maxSimultaneousLights),
            a.SPECULARTERM && h.addFallback(0, "SPECULARTERM"),
            a.DIFFUSEFRESNEL && h.addFallback(1, "DIFFUSEFRESNEL"),
            a.OPACITYFRESNEL && h.addFallback(2, "OPACITYFRESNEL"),
            a.REFLECTIONFRESNEL && h.addFallback(3, "REFLECTIONFRESNEL"),
            a.EMISSIVEFRESNEL && h.addFallback(4, "EMISSIVEFRESNEL"),
            a.FRESNEL && h.addFallback(4, "FRESNEL"),
            a.MULTIVIEW && h.addFallback(0, "MULTIVIEW");
            var f = [VertexBuffer.PositionKind];
            a.NORMAL && f.push(VertexBuffer.NormalKind),
            a.TANGENT && f.push(VertexBuffer.TangentKind);
            for (var u = 1; u <= 6; ++u)
                a["UV" + u] && f.push("uv" + (u === 1 ? "" : u));
            a.VERTEXCOLOR && f.push(VertexBuffer.ColorKind),
            MaterialHelper.PrepareAttributesForBones(f, t, a, h),
            MaterialHelper.PrepareAttributesForInstances(f, a),
            MaterialHelper.PrepareAttributesForMorphTargets(f, t, a),
            MaterialHelper.PrepareAttributesForBakedVertexAnimation(f, t, a);
            var d = "default"
              , _ = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor", "visibility", "vFogInfos", "vFogColor", "pointSize", "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos", "mBones", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "vClipPlane5", "vClipPlane6", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix", "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor", "vReflectionPosition", "vReflectionSize", "vRefractionPosition", "vRefractionSize", "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff", "boneTextureWidth", "morphTargetTextureInfo", "morphTargetTextureIndices"]
              , g = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler", "boneSampler", "morphTargets", "oitDepthSampler", "oitFrontColorSampler"]
              , m = ["Material", "Scene", "Mesh"];
            DetailMapConfiguration.AddUniforms(_),
            DetailMapConfiguration.AddSamplers(g),
            PrePassConfiguration.AddUniforms(_),
            PrePassConfiguration.AddSamplers(g),
            ImageProcessingConfiguration && (ImageProcessingConfiguration.PrepareUniforms(_, a),
            ImageProcessingConfiguration.PrepareSamplers(g, a)),
            MaterialHelper.PrepareUniformsAndSamplersList({
                uniformsNames: _,
                uniformBuffersNames: m,
                samplers: g,
                defines: a,
                maxSimultaneousLights: this._maxSimultaneousLights
            });
            var v = {};
            this.customShaderNameResolve && (d = this.customShaderNameResolve(d, _, m, g, a, f, v));
            var y = a.toString()
              , b = r.effect
              , T = o.getEngine().createEffect(d, {
                attributes: f,
                uniformsNames: _,
                uniformBuffersNames: m,
                samplers: g,
                defines: y,
                fallbacks: h,
                onCompiled: this.onCompiled,
                onError: this.onError,
                indexParameters: {
                    maxSimultaneousLights: this._maxSimultaneousLights,
                    maxSimultaneousMorphTargets: a.NUM_MORPH_INFLUENCERS
                },
                processFinalCode: v.processFinalCode,
                multiTarget: a.PREPASS
            }, s);
            if (T)
                if (this._onEffectCreatedObservable && (onCreatedEffectParameters$2.effect = T,
                onCreatedEffectParameters$2.subMesh = r,
                this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters$2)),
                this.allowShaderHotSwapping && b && !T.isReady()) {
                    if (T = b,
                    a.markAsUnprocessed(),
                    c)
                        return a._areLightsDisposed = !0,
                        !1
                } else
                    o.resetCachedMaterial(),
                    r.setEffect(T, a, this._materialContext)
        }
        return !r.effect || !r.effect.isReady() ? !1 : (a._renderId = o.getRenderId(),
        r.effect._wasPreviouslyReady = !0,
        !0)
    }
    ,
    e.prototype.buildUniformLayout = function() {
        var t = this._uniformBuffer;
        t.addUniform("diffuseLeftColor", 4),
        t.addUniform("diffuseRightColor", 4),
        t.addUniform("opacityParts", 4),
        t.addUniform("reflectionLeftColor", 4),
        t.addUniform("reflectionRightColor", 4),
        t.addUniform("refractionLeftColor", 4),
        t.addUniform("refractionRightColor", 4),
        t.addUniform("emissiveLeftColor", 4),
        t.addUniform("emissiveRightColor", 4),
        t.addUniform("vDiffuseInfos", 2),
        t.addUniform("vAmbientInfos", 2),
        t.addUniform("vOpacityInfos", 2),
        t.addUniform("vReflectionInfos", 2),
        t.addUniform("vReflectionPosition", 3),
        t.addUniform("vReflectionSize", 3),
        t.addUniform("vEmissiveInfos", 2),
        t.addUniform("vLightmapInfos", 2),
        t.addUniform("vSpecularInfos", 2),
        t.addUniform("vBumpInfos", 3),
        t.addUniform("diffuseMatrix", 16),
        t.addUniform("ambientMatrix", 16),
        t.addUniform("opacityMatrix", 16),
        t.addUniform("reflectionMatrix", 16),
        t.addUniform("emissiveMatrix", 16),
        t.addUniform("lightmapMatrix", 16),
        t.addUniform("specularMatrix", 16),
        t.addUniform("bumpMatrix", 16),
        t.addUniform("vTangentSpaceParams", 2),
        t.addUniform("pointSize", 1),
        t.addUniform("alphaCutOff", 1),
        t.addUniform("refractionMatrix", 16),
        t.addUniform("vRefractionInfos", 4),
        t.addUniform("vRefractionPosition", 3),
        t.addUniform("vRefractionSize", 3),
        t.addUniform("vSpecularColor", 4),
        t.addUniform("vEmissiveColor", 3),
        t.addUniform("vDiffuseColor", 4),
        t.addUniform("vAmbientColor", 3),
        DetailMapConfiguration.PrepareUniformBuffer(t),
        t.create()
    }
    ,
    e.prototype.unbind = function() {
        if (this._activeEffect && !this.getScene().getEngine()._features.needToAlwaysBindUniformBuffers) {
            var t = !1;
            this._reflectionTexture && this._reflectionTexture.isRenderTarget && (this._activeEffect.setTexture("reflection2DSampler", null),
            t = !0),
            this._refractionTexture && this._refractionTexture.isRenderTarget && (this._activeEffect.setTexture("refraction2DSampler", null),
            t = !0),
            t && this._markAllSubMeshesAsTexturesDirty()
        }
        i.prototype.unbind.call(this)
    }
    ,
    e.prototype.bindForSubMesh = function(t, r, n) {
        var o, a = this.getScene(), s = n.materialDefines;
        if (!!s) {
            var l = n.effect;
            if (!!l) {
                this._activeEffect = l,
                r.getMeshUniformBuffer().bindToEffect(l, "Mesh"),
                r.transferToEffect(t),
                this.prePassConfiguration.bindForSubMesh(this._activeEffect, a, r, t, this.isFrozen),
                s.OBJECTSPACE_NORMALMAP && (t.toNormalMatrix(this._normalMatrix),
                this.bindOnlyNormalMatrix(this._normalMatrix));
                var u = this._mustRebind(a, l, r.visibility);
                MaterialHelper.BindBonesParameters(r, l);
                var c = this._uniformBuffer;
                if (u) {
                    if (c.bindToEffect(l, "Material"),
                    this.bindViewProjection(l),
                    !c.useUbo || !this.isFrozen || !c.isSync) {
                        if (e.FresnelEnabled && s.FRESNEL && (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled && (c.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power),
                        c.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias)),
                        this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled && c.updateColor4("opacityParts", new Color3(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power),
                        this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled && (c.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power),
                        c.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias)),
                        this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled && (c.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power),
                        c.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias)),
                        this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled && (c.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power),
                        c.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias))),
                        a.texturesEnabled) {
                            if (this._diffuseTexture && e.DiffuseTextureEnabled && (c.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level),
                            MaterialHelper.BindTextureMatrix(this._diffuseTexture, c, "diffuse")),
                            this._ambientTexture && e.AmbientTextureEnabled && (c.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level),
                            MaterialHelper.BindTextureMatrix(this._ambientTexture, c, "ambient")),
                            this._opacityTexture && e.OpacityTextureEnabled && (c.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level),
                            MaterialHelper.BindTextureMatrix(this._opacityTexture, c, "opacity")),
                            this._hasAlphaChannel() && c.updateFloat("alphaCutOff", this.alphaCutOff),
                            this._reflectionTexture && e.ReflectionTextureEnabled && (c.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness),
                            c.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix()),
                            this._reflectionTexture.boundingBoxSize)) {
                                var h = this._reflectionTexture;
                                c.updateVector3("vReflectionPosition", h.boundingBoxPosition),
                                c.updateVector3("vReflectionSize", h.boundingBoxSize)
                            }
                            if (this._emissiveTexture && e.EmissiveTextureEnabled && (c.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level),
                            MaterialHelper.BindTextureMatrix(this._emissiveTexture, c, "emissive")),
                            this._lightmapTexture && e.LightmapTextureEnabled && (c.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level),
                            MaterialHelper.BindTextureMatrix(this._lightmapTexture, c, "lightmap")),
                            this._specularTexture && e.SpecularTextureEnabled && (c.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level),
                            MaterialHelper.BindTextureMatrix(this._specularTexture, c, "specular")),
                            this._bumpTexture && a.getEngine().getCaps().standardDerivatives && e.BumpTextureEnabled && (c.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1 / this._bumpTexture.level, this.parallaxScaleBias),
                            MaterialHelper.BindTextureMatrix(this._bumpTexture, c, "bump"),
                            a._mirroredCameraPosition ? c.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1 : -1, this._invertNormalMapY ? 1 : -1) : c.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1 : 1, this._invertNormalMapY ? -1 : 1)),
                            this._refractionTexture && e.RefractionTextureEnabled) {
                                var f = 1;
                                if (this._refractionTexture.isCube || (c.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix()),
                                this._refractionTexture.depth && (f = this._refractionTexture.depth)),
                                c.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, f, this.invertRefractionY ? -1 : 1),
                                this._refractionTexture.boundingBoxSize) {
                                    var h = this._refractionTexture;
                                    c.updateVector3("vRefractionPosition", h.boundingBoxPosition),
                                    c.updateVector3("vRefractionSize", h.boundingBoxSize)
                                }
                            }
                        }
                        this.pointsCloud && c.updateFloat("pointSize", this.pointSize),
                        s.SPECULARTERM && c.updateColor4("vSpecularColor", this.specularColor, this.specularPower),
                        c.updateColor3("vEmissiveColor", e.EmissiveTextureEnabled ? this.emissiveColor : Color3.BlackReadOnly),
                        c.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha),
                        a.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor),
                        c.updateColor3("vAmbientColor", this._globalAmbientColor)
                    }
                    if (a.texturesEnabled && (this._diffuseTexture && e.DiffuseTextureEnabled && l.setTexture("diffuseSampler", this._diffuseTexture),
                    this._ambientTexture && e.AmbientTextureEnabled && l.setTexture("ambientSampler", this._ambientTexture),
                    this._opacityTexture && e.OpacityTextureEnabled && l.setTexture("opacitySampler", this._opacityTexture),
                    this._reflectionTexture && e.ReflectionTextureEnabled && (this._reflectionTexture.isCube ? l.setTexture("reflectionCubeSampler", this._reflectionTexture) : l.setTexture("reflection2DSampler", this._reflectionTexture)),
                    this._emissiveTexture && e.EmissiveTextureEnabled && l.setTexture("emissiveSampler", this._emissiveTexture),
                    this._lightmapTexture && e.LightmapTextureEnabled && l.setTexture("lightmapSampler", this._lightmapTexture),
                    this._specularTexture && e.SpecularTextureEnabled && l.setTexture("specularSampler", this._specularTexture),
                    this._bumpTexture && a.getEngine().getCaps().standardDerivatives && e.BumpTextureEnabled && l.setTexture("bumpSampler", this._bumpTexture),
                    this._refractionTexture && e.RefractionTextureEnabled)) {
                        var f = 1;
                        this._refractionTexture.isCube ? l.setTexture("refractionCubeSampler", this._refractionTexture) : l.setTexture("refraction2DSampler", this._refractionTexture)
                    }
                    this.getScene().useOrderIndependentTransparency && this.needAlphaBlendingForMesh(r) && this.getScene().depthPeelingRenderer.bind(l),
                    this.detailMap.bindForSubMesh(c, a, this.isFrozen),
                    MaterialHelper.BindClipPlane(l, a),
                    this.bindEyePosition(l)
                } else
                    a.getEngine()._features.needToAlwaysBindUniformBuffers && (c.bindToEffect(l, "Material"),
                    this._needToBindSceneUbo = !0);
                (u || !this.isFrozen) && (a.lightsEnabled && !this._disableLighting && MaterialHelper.BindLights(a, r, l, s, this._maxSimultaneousLights),
                (a.fogEnabled && r.applyFog && a.fogMode !== Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture || r.receiveShadows) && this.bindView(l),
                MaterialHelper.BindFogParameters(a, r, l),
                s.NUM_MORPH_INFLUENCERS && MaterialHelper.BindMorphTargetParameters(r, l),
                s.BAKED_VERTEX_ANIMATION_TEXTURE && ((o = r.bakedVertexAnimationManager) === null || o === void 0 || o.bind(l, s.INSTANCES)),
                this.useLogarithmicDepth && MaterialHelper.BindLogDepth(s, l, a),
                this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess && this._imageProcessingConfiguration.bind(this._activeEffect)),
                this._afterBind(r, this._activeEffect),
                c.update()
            }
        }
    }
    ,
    e.prototype.getAnimatables = function() {
        var t = [];
        return this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0 && t.push(this._diffuseTexture),
        this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0 && t.push(this._ambientTexture),
        this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0 && t.push(this._opacityTexture),
        this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0 && t.push(this._reflectionTexture),
        this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0 && t.push(this._emissiveTexture),
        this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0 && t.push(this._specularTexture),
        this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0 && t.push(this._bumpTexture),
        this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0 && t.push(this._lightmapTexture),
        this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0 && t.push(this._refractionTexture),
        this.detailMap.getAnimatables(t),
        t
    }
    ,
    e.prototype.getActiveTextures = function() {
        var t = i.prototype.getActiveTextures.call(this);
        return this._diffuseTexture && t.push(this._diffuseTexture),
        this._ambientTexture && t.push(this._ambientTexture),
        this._opacityTexture && t.push(this._opacityTexture),
        this._reflectionTexture && t.push(this._reflectionTexture),
        this._emissiveTexture && t.push(this._emissiveTexture),
        this._specularTexture && t.push(this._specularTexture),
        this._bumpTexture && t.push(this._bumpTexture),
        this._lightmapTexture && t.push(this._lightmapTexture),
        this._refractionTexture && t.push(this._refractionTexture),
        this.detailMap.getActiveTextures(t),
        t
    }
    ,
    e.prototype.hasTexture = function(t) {
        return !!(i.prototype.hasTexture.call(this, t) || this._diffuseTexture === t || this._ambientTexture === t || this._opacityTexture === t || this._reflectionTexture === t || this._emissiveTexture === t || this._specularTexture === t || this._bumpTexture === t || this._lightmapTexture === t || this._refractionTexture === t || this.detailMap.hasTexture(t))
    }
    ,
    e.prototype.dispose = function(t, r) {
        var n, o, a, s, l, u, c, h, f;
        r && ((n = this._diffuseTexture) === null || n === void 0 || n.dispose(),
        (o = this._ambientTexture) === null || o === void 0 || o.dispose(),
        (a = this._opacityTexture) === null || a === void 0 || a.dispose(),
        (s = this._reflectionTexture) === null || s === void 0 || s.dispose(),
        (l = this._emissiveTexture) === null || l === void 0 || l.dispose(),
        (u = this._specularTexture) === null || u === void 0 || u.dispose(),
        (c = this._bumpTexture) === null || c === void 0 || c.dispose(),
        (h = this._lightmapTexture) === null || h === void 0 || h.dispose(),
        (f = this._refractionTexture) === null || f === void 0 || f.dispose()),
        this.detailMap.dispose(r),
        this._imageProcessingConfiguration && this._imageProcessingObserver && this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),
        i.prototype.dispose.call(this, t, r)
    }
    ,
    e.prototype.clone = function(t) {
        var r = this
          , n = SerializationHelper.Clone(function() {
            return new e(t,r.getScene())
        }, this);
        return n.name = t,
        n.id = t,
        this.stencil.copyTo(n.stencil),
        n
    }
    ,
    e.prototype.serialize = function() {
        var t = SerializationHelper.Serialize(this);
        return t.stencil = this.stencil.serialize(),
        t
    }
    ,
    e.Parse = function(t, r, n) {
        var o = SerializationHelper.Parse(function() {
            return new e(t.name,r)
        }, t, r, n);
        return t.stencil && o.stencil.parse(t.stencil, r, n),
        o
    }
    ,
    Object.defineProperty(e, "DiffuseTextureEnabled", {
        get: function() {
            return MaterialFlags.DiffuseTextureEnabled
        },
        set: function(t) {
            MaterialFlags.DiffuseTextureEnabled = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e, "DetailTextureEnabled", {
        get: function() {
            return MaterialFlags.DetailTextureEnabled
        },
        set: function(t) {
            MaterialFlags.DetailTextureEnabled = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e, "AmbientTextureEnabled", {
        get: function() {
            return MaterialFlags.AmbientTextureEnabled
        },
        set: function(t) {
            MaterialFlags.AmbientTextureEnabled = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e, "OpacityTextureEnabled", {
        get: function() {
            return MaterialFlags.OpacityTextureEnabled
        },
        set: function(t) {
            MaterialFlags.OpacityTextureEnabled = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e, "ReflectionTextureEnabled", {
        get: function() {
            return MaterialFlags.ReflectionTextureEnabled
        },
        set: function(t) {
            MaterialFlags.ReflectionTextureEnabled = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e, "EmissiveTextureEnabled", {
        get: function() {
            return MaterialFlags.EmissiveTextureEnabled
        },
        set: function(t) {
            MaterialFlags.EmissiveTextureEnabled = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e, "SpecularTextureEnabled", {
        get: function() {
            return MaterialFlags.SpecularTextureEnabled
        },
        set: function(t) {
            MaterialFlags.SpecularTextureEnabled = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e, "BumpTextureEnabled", {
        get: function() {
            return MaterialFlags.BumpTextureEnabled
        },
        set: function(t) {
            MaterialFlags.BumpTextureEnabled = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e, "LightmapTextureEnabled", {
        get: function() {
            return MaterialFlags.LightmapTextureEnabled
        },
        set: function(t) {
            MaterialFlags.LightmapTextureEnabled = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e, "RefractionTextureEnabled", {
        get: function() {
            return MaterialFlags.RefractionTextureEnabled
        },
        set: function(t) {
            MaterialFlags.RefractionTextureEnabled = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e, "ColorGradingTextureEnabled", {
        get: function() {
            return MaterialFlags.ColorGradingTextureEnabled
        },
        set: function(t) {
            MaterialFlags.ColorGradingTextureEnabled = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e, "FresnelEnabled", {
        get: function() {
            return MaterialFlags.FresnelEnabled
        },
        set: function(t) {
            MaterialFlags.FresnelEnabled = t
        },
        enumerable: !1,
        configurable: !0
    }),
    __decorate([serializeAsTexture("diffuseTexture")], e.prototype, "_diffuseTexture", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")], e.prototype, "diffuseTexture", void 0),
    __decorate([serializeAsTexture("ambientTexture")], e.prototype, "_ambientTexture", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "ambientTexture", void 0),
    __decorate([serializeAsTexture("opacityTexture")], e.prototype, "_opacityTexture", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")], e.prototype, "opacityTexture", void 0),
    __decorate([serializeAsTexture("reflectionTexture")], e.prototype, "_reflectionTexture", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "reflectionTexture", void 0),
    __decorate([serializeAsTexture("emissiveTexture")], e.prototype, "_emissiveTexture", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "emissiveTexture", void 0),
    __decorate([serializeAsTexture("specularTexture")], e.prototype, "_specularTexture", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "specularTexture", void 0),
    __decorate([serializeAsTexture("bumpTexture")], e.prototype, "_bumpTexture", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "bumpTexture", void 0),
    __decorate([serializeAsTexture("lightmapTexture")], e.prototype, "_lightmapTexture", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "lightmapTexture", void 0),
    __decorate([serializeAsTexture("refractionTexture")], e.prototype, "_refractionTexture", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "refractionTexture", void 0),
    __decorate([serializeAsColor3("ambient")], e.prototype, "ambientColor", void 0),
    __decorate([serializeAsColor3("diffuse")], e.prototype, "diffuseColor", void 0),
    __decorate([serializeAsColor3("specular")], e.prototype, "specularColor", void 0),
    __decorate([serializeAsColor3("emissive")], e.prototype, "emissiveColor", void 0),
    __decorate([serialize()], e.prototype, "specularPower", void 0),
    __decorate([serialize("useAlphaFromDiffuseTexture")], e.prototype, "_useAlphaFromDiffuseTexture", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")], e.prototype, "useAlphaFromDiffuseTexture", void 0),
    __decorate([serialize("useEmissiveAsIllumination")], e.prototype, "_useEmissiveAsIllumination", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "useEmissiveAsIllumination", void 0),
    __decorate([serialize("linkEmissiveWithDiffuse")], e.prototype, "_linkEmissiveWithDiffuse", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "linkEmissiveWithDiffuse", void 0),
    __decorate([serialize("useSpecularOverAlpha")], e.prototype, "_useSpecularOverAlpha", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "useSpecularOverAlpha", void 0),
    __decorate([serialize("useReflectionOverAlpha")], e.prototype, "_useReflectionOverAlpha", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "useReflectionOverAlpha", void 0),
    __decorate([serialize("disableLighting")], e.prototype, "_disableLighting", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsLightsDirty")], e.prototype, "disableLighting", void 0),
    __decorate([serialize("useObjectSpaceNormalMap")], e.prototype, "_useObjectSpaceNormalMap", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "useObjectSpaceNormalMap", void 0),
    __decorate([serialize("useParallax")], e.prototype, "_useParallax", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "useParallax", void 0),
    __decorate([serialize("useParallaxOcclusion")], e.prototype, "_useParallaxOcclusion", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "useParallaxOcclusion", void 0),
    __decorate([serialize()], e.prototype, "parallaxScaleBias", void 0),
    __decorate([serialize("roughness")], e.prototype, "_roughness", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "roughness", void 0),
    __decorate([serialize()], e.prototype, "indexOfRefraction", void 0),
    __decorate([serialize()], e.prototype, "invertRefractionY", void 0),
    __decorate([serialize()], e.prototype, "alphaCutOff", void 0),
    __decorate([serialize("useLightmapAsShadowmap")], e.prototype, "_useLightmapAsShadowmap", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "useLightmapAsShadowmap", void 0),
    __decorate([serializeAsFresnelParameters("diffuseFresnelParameters")], e.prototype, "_diffuseFresnelParameters", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsFresnelDirty")], e.prototype, "diffuseFresnelParameters", void 0),
    __decorate([serializeAsFresnelParameters("opacityFresnelParameters")], e.prototype, "_opacityFresnelParameters", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")], e.prototype, "opacityFresnelParameters", void 0),
    __decorate([serializeAsFresnelParameters("reflectionFresnelParameters")], e.prototype, "_reflectionFresnelParameters", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsFresnelDirty")], e.prototype, "reflectionFresnelParameters", void 0),
    __decorate([serializeAsFresnelParameters("refractionFresnelParameters")], e.prototype, "_refractionFresnelParameters", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsFresnelDirty")], e.prototype, "refractionFresnelParameters", void 0),
    __decorate([serializeAsFresnelParameters("emissiveFresnelParameters")], e.prototype, "_emissiveFresnelParameters", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsFresnelDirty")], e.prototype, "emissiveFresnelParameters", void 0),
    __decorate([serialize("useReflectionFresnelFromSpecular")], e.prototype, "_useReflectionFresnelFromSpecular", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsFresnelDirty")], e.prototype, "useReflectionFresnelFromSpecular", void 0),
    __decorate([serialize("useGlossinessFromSpecularMapAlpha")], e.prototype, "_useGlossinessFromSpecularMapAlpha", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "useGlossinessFromSpecularMapAlpha", void 0),
    __decorate([serialize("maxSimultaneousLights")], e.prototype, "_maxSimultaneousLights", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsLightsDirty")], e.prototype, "maxSimultaneousLights", void 0),
    __decorate([serialize("invertNormalMapX")], e.prototype, "_invertNormalMapX", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "invertNormalMapX", void 0),
    __decorate([serialize("invertNormalMapY")], e.prototype, "_invertNormalMapY", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "invertNormalMapY", void 0),
    __decorate([serialize("twoSidedLighting")], e.prototype, "_twoSidedLighting", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "twoSidedLighting", void 0),
    __decorate([serialize()], e.prototype, "useLogarithmicDepth", null),
    e
}(PushMaterial);
RegisterClass("BABYLON.StandardMaterial", StandardMaterial);
Scene.DefaultMaterialFactory = function(i) {
    return new StandardMaterial("default material",i)
}
;
ThinEngine.prototype._createDepthStencilCubeTexture = function(i, e, t) {
    var r = new InternalTexture(this,InternalTextureSource.DepthStencil);
    if (r.isCube = !0,
    this.webGLVersion === 1)
        return Logger$2.Error("Depth cube texture is not supported by WebGL 1."),
        r;
    var n = __assign({
        bilinearFiltering: !1,
        comparisonFunction: 0,
        generateStencil: !1
    }, e)
      , o = this._gl;
    this._bindTextureDirectly(o.TEXTURE_CUBE_MAP, r, !0),
    this._setupDepthStencilTexture(r, i, n.generateStencil, n.bilinearFiltering, n.comparisonFunction),
    t._depthStencilTexture = r,
    t._depthStencilTextureWithStencil = n.generateStencil;
    for (var a = 0; a < 6; a++)
        n.generateStencil ? o.texImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X + a, 0, o.DEPTH24_STENCIL8, i, i, 0, o.DEPTH_STENCIL, o.UNSIGNED_INT_24_8, null) : o.texImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X + a, 0, o.DEPTH_COMPONENT24, i, i, 0, o.DEPTH_COMPONENT, o.UNSIGNED_INT, null);
    return this._bindTextureDirectly(o.TEXTURE_CUBE_MAP, null),
    this._internalTexturesCache.push(r),
    r
}
;
ThinEngine.prototype._partialLoadFile = function(i, e, t, r, n) {
    n === void 0 && (n = null);
    var o = function(s) {
        t[e] = s,
        t._internalCount++,
        t._internalCount === 6 && r(t)
    }
      , a = function(s, l) {
        n && s && n(s.status + " " + s.statusText, l)
    };
    this._loadFile(i, o, void 0, void 0, !0, a)
}
;
ThinEngine.prototype._cascadeLoadFiles = function(i, e, t, r) {
    r === void 0 && (r = null);
    var n = [];
    n._internalCount = 0;
    for (var o = 0; o < 6; o++)
        this._partialLoadFile(t[o], o, n, e, r)
}
;
ThinEngine.prototype._cascadeLoadImgs = function(i, e, t, r, n, o) {
    n === void 0 && (n = null);
    var a = [];
    a._internalCount = 0;
    for (var s = 0; s < 6; s++)
        this._partialLoadImg(r[s], s, a, i, e, t, n, o)
}
;
ThinEngine.prototype._partialLoadImg = function(i, e, t, r, n, o, a, s) {
    a === void 0 && (a = null);
    var l = RandomGUID()
      , u = function(h) {
        t[e] = h,
        t._internalCount++,
        r && r._removePendingData(l),
        t._internalCount === 6 && o && o(n, t)
    }
      , c = function(h, f) {
        r && r._removePendingData(l),
        a && a(h, f)
    };
    LoadImage(i, u, c, r ? r.offlineProvider : null, s),
    r && r._addPendingData(l)
}
;
ThinEngine.prototype._setCubeMapTextureParams = function(i, e) {
    var t = this._gl;
    t.texParameteri(t.TEXTURE_CUBE_MAP, t.TEXTURE_MAG_FILTER, t.LINEAR),
    t.texParameteri(t.TEXTURE_CUBE_MAP, t.TEXTURE_MIN_FILTER, e ? t.LINEAR_MIPMAP_LINEAR : t.LINEAR),
    t.texParameteri(t.TEXTURE_CUBE_MAP, t.TEXTURE_WRAP_S, t.CLAMP_TO_EDGE),
    t.texParameteri(t.TEXTURE_CUBE_MAP, t.TEXTURE_WRAP_T, t.CLAMP_TO_EDGE),
    i.samplingMode = e ? 3 : 2,
    this._bindTextureDirectly(t.TEXTURE_CUBE_MAP, null)
}
;
ThinEngine.prototype.createCubeTextureBase = function(i, e, t, r, n, o, a, s, l, u, c, h, f, d, _) {
    var g = this;
    n === void 0 && (n = null),
    o === void 0 && (o = null),
    s === void 0 && (s = null),
    l === void 0 && (l = !1),
    u === void 0 && (u = 0),
    c === void 0 && (c = 0),
    h === void 0 && (h = null),
    f === void 0 && (f = null),
    d === void 0 && (d = null),
    _ === void 0 && (_ = !1);
    var m = h || new InternalTexture(this,InternalTextureSource.Cube);
    m.isCube = !0,
    m.url = i,
    m.generateMipMaps = !r,
    m._lodGenerationScale = u,
    m._lodGenerationOffset = c,
    m._useSRGBBuffer = !!_ && this._caps.supportSRGBBuffers && (this.webGLVersion > 1 || this.isWebGPU || !!r),
    this._doNotHandleContextLost || (m._extension = s,
    m._files = t);
    var v = i;
    this._transformTextureUrl && !h && (i = this._transformTextureUrl(i));
    for (var y = i.lastIndexOf("."), b = s || (y > -1 ? i.substring(y).toLowerCase() : ""), T = null, C = 0, A = ThinEngine._TextureLoaders; C < A.length; C++) {
        var S = A[C];
        if (S.canLoad(b)) {
            T = S;
            break
        }
    }
    var P = function(M, x) {
        i === v ? o && M && o(M.status + " " + M.statusText, x) : (Logger$2.Warn("Failed to load " + i + ", falling back to the " + v),
        g.createCubeTextureBase(v, e, t, !!r, n, o, a, s, l, u, c, m, f, d, _))
    };
    if (T) {
        var R = function(M) {
            f && f(m, M),
            T.loadCubeData(M, m, l, n, o)
        };
        t && t.length === 6 ? T.supportCascades ? this._cascadeLoadFiles(e, function(M) {
            return R(M.map(function(x) {
                return new Uint8Array(x)
            }))
        }, t, o) : o ? o("Textures type does not support cascades.") : Logger$2.Warn("Texture loader does not support cascades.") : this._loadFile(i, function(M) {
            return R(new Uint8Array(M))
        }, void 0, void 0, !0, P)
    } else {
        if (!t)
            throw new Error("Cannot load cubemap because files were not defined");
        this._cascadeLoadImgs(e, m, function(M, x) {
            d && d(M, x)
        }, t, o)
    }
    return this._internalTexturesCache.push(m),
    m
}
;
ThinEngine.prototype.createCubeTexture = function(i, e, t, r, n, o, a, s, l, u, c, h, f, d) {
    var _ = this;
    n === void 0 && (n = null),
    o === void 0 && (o = null),
    s === void 0 && (s = null),
    l === void 0 && (l = !1),
    u === void 0 && (u = 0),
    c === void 0 && (c = 0),
    h === void 0 && (h = null),
    d === void 0 && (d = !1);
    var g = this._gl;
    return this.createCubeTextureBase(i, e, t, !!r, n, o, a, s, l, u, c, h, function(m, v) {
        return _._bindTextureDirectly(g.TEXTURE_CUBE_MAP, m, !0)
    }, function(m, v) {
        var y = _.needPOTTextures ? ThinEngine.GetExponentOfTwo(v[0].width, _._caps.maxCubemapTextureSize) : v[0].width
          , b = y
          , T = [g.TEXTURE_CUBE_MAP_POSITIVE_X, g.TEXTURE_CUBE_MAP_POSITIVE_Y, g.TEXTURE_CUBE_MAP_POSITIVE_Z, g.TEXTURE_CUBE_MAP_NEGATIVE_X, g.TEXTURE_CUBE_MAP_NEGATIVE_Y, g.TEXTURE_CUBE_MAP_NEGATIVE_Z];
        _._bindTextureDirectly(g.TEXTURE_CUBE_MAP, m, !0),
        _._unpackFlipY(!1);
        var C = a ? _._getInternalFormat(a, m._useSRGBBuffer) : m._useSRGBBuffer ? g.SRGB8_ALPHA8 : g.RGBA
          , A = a ? _._getInternalFormat(a) : g.RGBA;
        m._useSRGBBuffer && _.webGLVersion === 1 && (A = C);
        for (var S = 0; S < T.length; S++)
            if (v[S].width !== y || v[S].height !== b) {
                if (_._prepareWorkingCanvas(),
                !_._workingCanvas || !_._workingContext) {
                    Logger$2.Warn("Cannot create canvas to resize texture.");
                    return
                }
                _._workingCanvas.width = y,
                _._workingCanvas.height = b,
                _._workingContext.drawImage(v[S], 0, 0, v[S].width, v[S].height, 0, 0, y, b),
                g.texImage2D(T[S], 0, C, A, g.UNSIGNED_BYTE, _._workingCanvas)
            } else
                g.texImage2D(T[S], 0, C, A, g.UNSIGNED_BYTE, v[S]);
        r || g.generateMipmap(g.TEXTURE_CUBE_MAP),
        _._setCubeMapTextureParams(m, !r),
        m.width = y,
        m.height = b,
        m.isReady = !0,
        a && (m.format = a),
        m.onLoadedObservable.notifyObservers(m),
        m.onLoadedObservable.clear(),
        n && n()
    }, !!d)
}
;
var CubeTexture = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a, s, l, u, c, h, f, d, _, g, m) {
        n === void 0 && (n = null),
        o === void 0 && (o = !1),
        a === void 0 && (a = null),
        s === void 0 && (s = null),
        l === void 0 && (l = null),
        u === void 0 && (u = 5),
        c === void 0 && (c = !1),
        h === void 0 && (h = null),
        f === void 0 && (f = !1),
        d === void 0 && (d = .8),
        _ === void 0 && (_ = 0);
        var v, y = i.call(this, r) || this;
        return y._lodScale = .8,
        y._lodOffset = 0,
        y.onLoadObservable = new Observable,
        y.boundingBoxPosition = Vector3.Zero(),
        y._rotationY = 0,
        y._files = null,
        y._forcedExtension = null,
        y._extensions = null,
        y.name = t,
        y.url = t,
        y._noMipmap = o,
        y.hasAlpha = !1,
        y._format = u,
        y.isCube = !0,
        y._textureMatrix = Matrix.Identity(),
        y._createPolynomials = f,
        y.coordinatesMode = Texture.CUBIC_MODE,
        y._extensions = n,
        y._files = a,
        y._forcedExtension = h,
        y._loaderOptions = g,
        y._useSRGBBuffer = m,
        y._lodScale = d,
        y._lodOffset = _,
        !t && !a || y.updateURL(t, h, s, c, l, n, (v = y.getScene()) === null || v === void 0 ? void 0 : v.useDelayedTextureLoading, a),
        y
    }
    return Object.defineProperty(e.prototype, "boundingBoxSize", {
        get: function() {
            return this._boundingBoxSize
        },
        set: function(t) {
            if (!(this._boundingBoxSize && this._boundingBoxSize.equals(t))) {
                this._boundingBoxSize = t;
                var r = this.getScene();
                r && r.markAllMaterialsAsDirty(1)
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "rotationY", {
        get: function() {
            return this._rotationY
        },
        set: function(t) {
            this._rotationY = t,
            this.setReflectionTextureMatrix(Matrix.RotationY(this._rotationY))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "noMipmap", {
        get: function() {
            return this._noMipmap
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "forcedExtension", {
        get: function() {
            return this._forcedExtension
        },
        enumerable: !1,
        configurable: !0
    }),
    e.CreateFromImages = function(t, r, n) {
        var o = "";
        return t.forEach(function(a) {
            return o += a
        }),
        new e(o,r,null,n,t)
    }
    ,
    e.CreateFromPrefilteredData = function(t, r, n, o) {
        n === void 0 && (n = null),
        o === void 0 && (o = !0);
        var a = r.useDelayedTextureLoading;
        r.useDelayedTextureLoading = !1;
        var s = new e(t,r,null,!1,null,null,null,void 0,!0,n,o);
        return r.useDelayedTextureLoading = a,
        s
    }
    ,
    e.prototype.getClassName = function() {
        return "CubeTexture"
    }
    ,
    e.prototype.updateURL = function(t, r, n, o, a, s, l, u) {
        n === void 0 && (n = null),
        o === void 0 && (o = !1),
        a === void 0 && (a = null),
        s === void 0 && (s = null),
        l === void 0 && (l = !1),
        u === void 0 && (u = null),
        (!this.name || StartsWith(this.name, "data:")) && (this.name = t),
        this.url = t;
        var c = t.lastIndexOf(".")
          , h = r || (c > -1 ? t.substring(c).toLowerCase() : "")
          , f = h.indexOf(".dds") === 0
          , d = h.indexOf(".env") === 0;
        if (d ? (this.gammaSpace = !1,
        this._prefiltered = !1,
        this.anisotropicFilteringLevel = 1) : (this._prefiltered = o,
        o && (this.gammaSpace = !1,
        this.anisotropicFilteringLevel = 1)),
        u)
            this._files = u;
        else if (!d && !f && !s && (s = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"]),
        this._files = this._files || [],
        this._files.length = 0,
        s) {
            for (var _ = 0; _ < s.length; _++)
                this._files.push(t + s[_]);
            this._extensions = s
        }
        l ? (this.delayLoadState = 4,
        this._delayedOnLoad = n,
        this._delayedOnError = a) : this._loadTexture(n, a)
    }
    ,
    e.prototype.delayLoad = function(t) {
        this.delayLoadState === 4 && (t && (this._forcedExtension = t),
        this.delayLoadState = 1,
        this._loadTexture(this._delayedOnLoad, this._delayedOnError))
    }
    ,
    e.prototype.getReflectionTextureMatrix = function() {
        return this._textureMatrix
    }
    ,
    e.prototype.setReflectionTextureMatrix = function(t) {
        var r = this, n;
        t.updateFlag !== this._textureMatrix.updateFlag && (t.isIdentity() !== this._textureMatrix.isIdentity() && ((n = this.getScene()) === null || n === void 0 || n.markAllMaterialsAsDirty(1, function(o) {
            return o.getActiveTextures().indexOf(r) !== -1
        })),
        this._textureMatrix = t)
    }
    ,
    e.prototype._loadTexture = function(t, r) {
        var n = this, o;
        t === void 0 && (t = null),
        r === void 0 && (r = null);
        var a = this.getScene()
          , s = this._texture;
        this._texture = this._getFromCache(this.url, this._noMipmap, void 0, void 0, this._useSRGBBuffer);
        var l = function() {
            var c;
            n.onLoadObservable.notifyObservers(n),
            s && (s.dispose(),
            (c = n.getScene()) === null || c === void 0 || c.markAllMaterialsAsDirty(1)),
            t && t()
        }
          , u = function(c, h) {
            n._loadingError = !0,
            n._errorObject = {
                message: c,
                exception: h
            },
            r && r(c, h),
            Texture.OnTextureLoadErrorObservable.notifyObservers(n)
        };
        this._texture ? this._texture.isReady ? Tools.SetImmediate(function() {
            return l()
        }) : this._texture.onLoadedObservable.add(function() {
            return l()
        }) : (this._prefiltered ? this._texture = this._getEngine().createPrefilteredCubeTexture(this.url, a, this._lodScale, this._lodOffset, t, u, this._format, this._forcedExtension, this._createPolynomials) : this._texture = this._getEngine().createCubeTexture(this.url, a, this._files, this._noMipmap, t, u, this._format, this._forcedExtension, !1, this._lodScale, this._lodOffset, null, this._loaderOptions, !!this._useSRGBBuffer),
        (o = this._texture) === null || o === void 0 || o.onLoadedObservable.add(function() {
            return n.onLoadObservable.notifyObservers(n)
        }))
    }
    ,
    e.Parse = function(t, r, n) {
        var o = SerializationHelper.Parse(function() {
            var u = !1;
            return t.prefiltered && (u = t.prefiltered),
            new e(n + t.name,r,t.extensions,!1,t.files || null,null,null,void 0,u,t.forcedExtension)
        }, t, r);
        if (t.boundingBoxPosition && (o.boundingBoxPosition = Vector3.FromArray(t.boundingBoxPosition)),
        t.boundingBoxSize && (o.boundingBoxSize = Vector3.FromArray(t.boundingBoxSize)),
        t.animations)
            for (var a = 0; a < t.animations.length; a++) {
                var s = t.animations[a]
                  , l = GetClass("BABYLON.Animation");
                l && o.animations.push(l.Parse(s))
            }
        return o
    }
    ,
    e.prototype.clone = function() {
        var t = this
          , r = 0
          , n = SerializationHelper.Clone(function() {
            var o = new e(t.url,t.getScene() || t._getEngine(),t._extensions,t._noMipmap,t._files);
            return r = o.uniqueId,
            o
        }, this);
        return n.uniqueId = r,
        n
    }
    ,
    __decorate([serialize()], e.prototype, "url", void 0),
    __decorate([serialize("rotationY")], e.prototype, "rotationY", null),
    __decorate([serialize("files")], e.prototype, "_files", void 0),
    __decorate([serialize("forcedExtension")], e.prototype, "_forcedExtension", void 0),
    __decorate([serialize("extensions")], e.prototype, "_extensions", void 0),
    __decorate([serializeAsMatrix("textureMatrix")], e.prototype, "_textureMatrix", void 0),
    e
}(BaseTexture);
Texture._CubeTextureParser = CubeTexture.Parse;
RegisterClass("BABYLON.CubeTexture", CubeTexture);
ThinEngine.prototype.createDynamicTexture = function(i, e, t, r) {
    var n = new InternalTexture(this,InternalTextureSource.Dynamic);
    return n.baseWidth = i,
    n.baseHeight = e,
    t && (i = this.needPOTTextures ? ThinEngine.GetExponentOfTwo(i, this._caps.maxTextureSize) : i,
    e = this.needPOTTextures ? ThinEngine.GetExponentOfTwo(e, this._caps.maxTextureSize) : e),
    n.width = i,
    n.height = e,
    n.isReady = !1,
    n.generateMipMaps = t,
    n.samplingMode = r,
    this.updateTextureSamplingMode(r, n),
    this._internalTexturesCache.push(n),
    n
}
;
ThinEngine.prototype.updateDynamicTexture = function(i, e, t, r, n, o, a) {
    if (r === void 0 && (r = !1),
    o === void 0 && (o = !1),
    !!i) {
        var s = this._gl
          , l = s.TEXTURE_2D
          , u = this._bindTextureDirectly(l, i, !0, o);
        this._unpackFlipY(t === void 0 ? i.invertY : t),
        r && s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
        var c = this._getWebGLTextureType(i.type)
          , h = this._getInternalFormat(n || i.format)
          , f = this._getRGBABufferInternalSizedFormat(i.type, h);
        s.texImage2D(l, 0, f, h, c, e),
        i.generateMipMaps && s.generateMipmap(l),
        u || this._bindTextureDirectly(l, null),
        r && s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0),
        i.isReady = !0
    }
}
;
var DynamicTexture = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a, s, l) {
        n === void 0 && (n = null),
        o === void 0 && (o = !1),
        a === void 0 && (a = 3),
        s === void 0 && (s = 5);
        var u = i.call(this, null, n, !o, l, a, void 0, void 0, void 0, void 0, s) || this;
        u.name = t,
        u.wrapU = Texture.CLAMP_ADDRESSMODE,
        u.wrapV = Texture.CLAMP_ADDRESSMODE,
        u._generateMipMaps = o;
        var c = u._getEngine();
        if (!c)
            return u;
        r.getContext ? (u._canvas = r,
        u._texture = c.createDynamicTexture(r.width, r.height, o, a)) : (u._canvas = c.createCanvas(1, 1),
        r.width || r.width === 0 ? u._texture = c.createDynamicTexture(r.width, r.height, o, a) : u._texture = c.createDynamicTexture(r, r, o, a));
        var h = u.getSize();
        return u._canvas.width !== h.width && (u._canvas.width = h.width),
        u._canvas.height !== h.height && (u._canvas.height = h.height),
        u._context = u._canvas.getContext("2d"),
        u
    }
    return e.prototype.getClassName = function() {
        return "DynamicTexture"
    }
    ,
    Object.defineProperty(e.prototype, "canRescale", {
        get: function() {
            return !0
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._recreate = function(t) {
        this._canvas.width = t.width,
        this._canvas.height = t.height,
        this.releaseInternalTexture(),
        this._texture = this._getEngine().createDynamicTexture(t.width, t.height, this._generateMipMaps, this.samplingMode)
    }
    ,
    e.prototype.scale = function(t) {
        var r = this.getSize();
        r.width *= t,
        r.height *= t,
        this._recreate(r)
    }
    ,
    e.prototype.scaleTo = function(t, r) {
        var n = this.getSize();
        n.width = t,
        n.height = r,
        this._recreate(n)
    }
    ,
    e.prototype.getContext = function() {
        return this._context
    }
    ,
    e.prototype.clear = function() {
        var t = this.getSize();
        this._context.fillRect(0, 0, t.width, t.height)
    }
    ,
    e.prototype.update = function(t, r, n) {
        r === void 0 && (r = !1),
        n === void 0 && (n = !1),
        this._getEngine().updateDynamicTexture(this._texture, this._canvas, t === void 0 ? !0 : t, r, this._format || void 0, void 0, n)
    }
    ,
    e.prototype.drawText = function(t, r, n, o, a, s, l, u) {
        u === void 0 && (u = !0);
        var c = this.getSize();
        if (s && (this._context.fillStyle = s,
        this._context.fillRect(0, 0, c.width, c.height)),
        this._context.font = o,
        r == null) {
            var h = this._context.measureText(t);
            r = (c.width - h.width) / 2
        }
        if (n == null) {
            var f = parseInt(o.replace(/\D/g, ""));
            n = c.height / 2 + f / 3.65
        }
        this._context.fillStyle = a || "",
        this._context.fillText(t, r, n),
        u && this.update(l)
    }
    ,
    e.prototype.clone = function() {
        var t = this.getScene();
        if (!t)
            return this;
        var r = this.getSize()
          , n = new e(this.name,r,t,this._generateMipMaps);
        return n.hasAlpha = this.hasAlpha,
        n.level = this.level,
        n.wrapU = this.wrapU,
        n.wrapV = this.wrapV,
        n
    }
    ,
    e.prototype.serialize = function() {
        var t = this.getScene();
        t && !t.isReady() && Logger$2.Warn("The scene must be ready before serializing the dynamic texture");
        var r = i.prototype.serialize.call(this);
        return this._IsCanvasElement(this._canvas) && (r.base64String = this._canvas.toDataURL()),
        r.invertY = this._invertY,
        r.samplingMode = this.samplingMode,
        r
    }
    ,
    e.prototype._IsCanvasElement = function(t) {
        return t.toDataURL !== void 0
    }
    ,
    e.prototype._rebuild = function() {
        this.update()
    }
    ,
    e
}(Texture);
ThinEngine.prototype.updateVideoTexture = function(i, e, t) {
    if (!(!i || i._isDisabled)) {
        var r = this._bindTextureDirectly(this._gl.TEXTURE_2D, i, !0);
        this._unpackFlipY(!t);
        try {
            if (this._videoTextureSupported === void 0 && (this._gl.getError(),
            this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, e),
            this._gl.getError() !== 0 ? this._videoTextureSupported = !1 : this._videoTextureSupported = !0),
            this._videoTextureSupported)
                this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, e);
            else {
                if (!i._workingCanvas) {
                    i._workingCanvas = this.createCanvas(i.width, i.height);
                    var n = i._workingCanvas.getContext("2d");
                    if (!n)
                        throw new Error("Unable to get 2d context");
                    i._workingContext = n,
                    i._workingCanvas.width = i.width,
                    i._workingCanvas.height = i.height
                }
                i._workingContext.clearRect(0, 0, i.width, i.height),
                i._workingContext.drawImage(e, 0, 0, e.videoWidth, e.videoHeight, 0, 0, i.width, i.height),
                this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, i._workingCanvas)
            }
            i.generateMipMaps && this._gl.generateMipmap(this._gl.TEXTURE_2D),
            r || this._bindTextureDirectly(this._gl.TEXTURE_2D, null),
            i.isReady = !0
        } catch {
            i._isDisabled = !0
        }
    }
}
;
var VideoTexture = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a, s, l, u) {
        o === void 0 && (o = !1),
        a === void 0 && (a = !1),
        s === void 0 && (s = Texture.TRILINEAR_SAMPLINGMODE);
        var c = i.call(this, null, n, !o, a) || this;
        c._onUserActionRequestedObservable = null,
        c._stillImageCaptured = !1,
        c._displayingPosterTexture = !1,
        c._frameId = -1,
        c._currentSrc = null,
        c._errorFound = !1,
        c._createInternalTexture = function() {
            if (c._texture != null)
                if (c._displayingPosterTexture)
                    c._texture.dispose(),
                    c._displayingPosterTexture = !1;
                else
                    return;
            if (!c._getEngine().needPOTTextures || Tools.IsExponentOfTwo(c.video.videoWidth) && Tools.IsExponentOfTwo(c.video.videoHeight) ? (c.wrapU = Texture.WRAP_ADDRESSMODE,
            c.wrapV = Texture.WRAP_ADDRESSMODE) : (c.wrapU = Texture.CLAMP_ADDRESSMODE,
            c.wrapV = Texture.CLAMP_ADDRESSMODE,
            c._generateMipMaps = !1),
            c._texture = c._getEngine().createDynamicTexture(c.video.videoWidth, c.video.videoHeight, c._generateMipMaps, c.samplingMode),
            !c.video.autoplay && !c._settings.poster) {
                var f = c.video.onplaying
                  , d = c.video.muted;
                c.video.muted = !0,
                c.video.onplaying = function() {
                    c.video.muted = d,
                    c.video.onplaying = f,
                    c._updateInternalTexture(),
                    c._errorFound || c.video.pause(),
                    c.onLoadObservable.hasObservers() && c.onLoadObservable.notifyObservers(c)
                }
                ,
                c._handlePlay()
            } else
                c._updateInternalTexture(),
                c.onLoadObservable.hasObservers() && c.onLoadObservable.notifyObservers(c)
        }
        ,
        c.reset = function() {
            c._texture != null && (c._displayingPosterTexture || (c._texture.dispose(),
            c._texture = null))
        }
        ,
        c._updateInternalTexture = function() {
            if (c._texture != null && !(c.video.readyState < c.video.HAVE_CURRENT_DATA) && !c._displayingPosterTexture) {
                var f = c.getScene().getFrameId();
                c._frameId !== f && (c._frameId = f,
                c._getEngine().updateVideoTexture(c._texture, c.video, c._invertY))
            }
        }
        ,
        l || (l = {
            autoPlay: !0,
            loop: !0,
            autoUpdateTexture: !0
        }),
        c._onError = u,
        c._generateMipMaps = o,
        c._initialSamplingMode = s,
        c.autoUpdateTexture = l.autoUpdateTexture,
        c._currentSrc = r,
        c.name = t || c._getName(r),
        c.video = c._getVideo(r),
        c._settings = l,
        l.poster && (c.video.poster = l.poster),
        l.autoPlay !== void 0 && (c.video.autoplay = l.autoPlay),
        l.loop !== void 0 && (c.video.loop = l.loop),
        l.muted !== void 0 && (c.video.muted = l.muted),
        c.video.setAttribute("playsinline", ""),
        c.video.addEventListener("paused", c._updateInternalTexture),
        c.video.addEventListener("seeked", c._updateInternalTexture),
        c.video.addEventListener("emptied", c.reset),
        c._createInternalTextureOnEvent = l.poster && !l.autoPlay ? "play" : "canplay",
        c.video.addEventListener(c._createInternalTextureOnEvent, c._createInternalTexture),
        l.autoPlay && c._handlePlay();
        var h = c.video.readyState >= c.video.HAVE_CURRENT_DATA;
        return l.poster && (!l.autoPlay || !h) ? (c._texture = c._getEngine().createTexture(l.poster, !1, !c.invertY, n),
        c._displayingPosterTexture = !0) : h && c._createInternalTexture(),
        c
    }
    return Object.defineProperty(e.prototype, "onUserActionRequestedObservable", {
        get: function() {
            return this._onUserActionRequestedObservable || (this._onUserActionRequestedObservable = new Observable),
            this._onUserActionRequestedObservable
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._processError = function(t) {
        this._errorFound = !0,
        this._onError ? this._onError(t == null ? void 0 : t.message) : Logger$2.Error(t == null ? void 0 : t.message)
    }
    ,
    e.prototype._handlePlay = function() {
        var t = this;
        this._errorFound = !1,
        this.video.play().catch(function(r) {
            if ((r == null ? void 0 : r.name) === "NotAllowedError") {
                if (t._onUserActionRequestedObservable && t._onUserActionRequestedObservable.hasObservers()) {
                    t._onUserActionRequestedObservable.notifyObservers(t);
                    return
                } else if (!t.video.muted) {
                    Logger$2.Warn("Unable to autoplay a video with sound. Trying again with muted turned true"),
                    t.video.muted = !0,
                    t._errorFound = !1,
                    t.video.play().catch(function(n) {
                        t._processError(n)
                    });
                    return
                }
            }
            t._processError(r)
        })
    }
    ,
    e.prototype.getClassName = function() {
        return "VideoTexture"
    }
    ,
    e.prototype._getName = function(t) {
        return t instanceof HTMLVideoElement ? t.currentSrc : typeof t == "object" ? t.toString() : t
    }
    ,
    e.prototype._getVideo = function(t) {
        if (t.isNative)
            return t;
        if (t instanceof HTMLVideoElement)
            return Tools.SetCorsBehavior(t.currentSrc, t),
            t;
        var r = document.createElement("video");
        return typeof t == "string" ? (Tools.SetCorsBehavior(t, r),
        r.src = t) : (Tools.SetCorsBehavior(t[0], r),
        t.forEach(function(n) {
            var o = document.createElement("source");
            o.src = n,
            r.appendChild(o)
        })),
        r
    }
    ,
    e.prototype._rebuild = function() {
        this.update()
    }
    ,
    e.prototype.update = function() {
        !this.autoUpdateTexture || this.updateTexture(!0)
    }
    ,
    e.prototype.updateTexture = function(t) {
        !t || this.video.paused && this._stillImageCaptured || (this._stillImageCaptured = !0,
        this._updateInternalTexture())
    }
    ,
    e.prototype.updateURL = function(t) {
        this.video.src = t,
        this._currentSrc = t
    }
    ,
    e.prototype.clone = function() {
        return new e(this.name,this._currentSrc,this.getScene(),this._generateMipMaps,this.invertY,this.samplingMode,this._settings)
    }
    ,
    e.prototype.dispose = function() {
        i.prototype.dispose.call(this),
        this._currentSrc = null,
        this._onUserActionRequestedObservable && (this._onUserActionRequestedObservable.clear(),
        this._onUserActionRequestedObservable = null),
        this.video.removeEventListener(this._createInternalTextureOnEvent, this._createInternalTexture),
        this.video.removeEventListener("paused", this._updateInternalTexture),
        this.video.removeEventListener("seeked", this._updateInternalTexture),
        this.video.removeEventListener("emptied", this.reset),
        this.video.pause()
    }
    ,
    e.CreateFromStreamAsync = function(t, r, n, o) {
        o === void 0 && (o = !0);
        var a = t.getEngine().createVideoElement(n);
        return t.getEngine()._badOS && (document.body.appendChild(a),
        a.style.transform = "scale(0.0001, 0.0001)",
        a.style.opacity = "0",
        a.style.position = "fixed",
        a.style.bottom = "0px",
        a.style.right = "0px"),
        a.setAttribute("autoplay", ""),
        a.setAttribute("muted", "true"),
        a.setAttribute("playsinline", ""),
        a.muted = !0,
        a.mozSrcObject !== void 0 ? a.mozSrcObject = r : typeof a.srcObject == "object" ? a.srcObject = r : (window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL,
        a.src = window.URL && window.URL.createObjectURL(r)),
        new Promise(function(s) {
            var l = function() {
                s(new e("video",a,t,!0,o)),
                a.removeEventListener("playing", l)
            };
            a.addEventListener("playing", l),
            a.play()
        }
        )
    }
    ,
    e.CreateFromWebCamAsync = function(t, r, n, o) {
        var a = this;
        n === void 0 && (n = !1),
        o === void 0 && (o = !0);
        var s;
        if (r && r.deviceId && (s = {
            exact: r.deviceId
        }),
        navigator.mediaDevices)
            return navigator.mediaDevices.getUserMedia({
                video: r,
                audio: n
            }).then(function(u) {
                return a.CreateFromStreamAsync(t, u, r, o)
            });
        var l = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
        return l && l({
            video: {
                deviceId: s,
                width: {
                    min: r && r.minWidth || 256,
                    max: r && r.maxWidth || 640
                },
                height: {
                    min: r && r.minHeight || 256,
                    max: r && r.maxHeight || 480
                }
            },
            audio: n
        }, function(u) {
            return a.CreateFromStreamAsync(t, u, r, o)
        }, function(u) {
            Logger$2.Error(u.name)
        }),
        Promise.reject("No support for userMedia on this device")
    }
    ,
    e.CreateFromWebCam = function(t, r, n, o, a) {
        o === void 0 && (o = !1),
        a === void 0 && (a = !0),
        this.CreateFromWebCamAsync(t, n, o, a).then(function(s) {
            r && r(s)
        }).catch(function(s) {
            Logger$2.Error(s.name)
        })
    }
    ,
    e
}(Texture)
  , Action = function() {
    function i(e, t) {
        this.triggerOptions = e,
        this.onBeforeExecuteObservable = new Observable,
        e.parameter ? (this.trigger = e.trigger,
        this._triggerParameter = e.parameter) : e.trigger ? this.trigger = e.trigger : this.trigger = e,
        this._nextActiveAction = this,
        this._condition = t
    }
    return i.prototype._prepare = function() {}
    ,
    i.prototype.getTriggerParameter = function() {
        return this._triggerParameter
    }
    ,
    i.prototype.setTriggerParameter = function(e) {
        this._triggerParameter = e
    }
    ,
    i.prototype._evaluateConditionForCurrentFrame = function() {
        var e = this._condition;
        if (!e)
            return !0;
        var t = this._actionManager.getScene().getRenderId();
        return e._evaluationId !== t && (e._evaluationId = t,
        e._currentResult = e.isValid()),
        e._currentResult
    }
    ,
    i.prototype._executeCurrent = function(e) {
        var t = this._evaluateConditionForCurrentFrame();
        !t || (this.onBeforeExecuteObservable.notifyObservers(this),
        this._nextActiveAction.execute(e),
        this.skipToNextActiveAction())
    }
    ,
    i.prototype.execute = function(e) {}
    ,
    i.prototype.skipToNextActiveAction = function() {
        this._nextActiveAction._child ? (this._nextActiveAction._child._actionManager || (this._nextActiveAction._child._actionManager = this._actionManager),
        this._nextActiveAction = this._nextActiveAction._child) : this._nextActiveAction = this
    }
    ,
    i.prototype.then = function(e) {
        return this._child = e,
        e._actionManager = this._actionManager,
        e._prepare(),
        e
    }
    ,
    i.prototype._getProperty = function(e) {
        return this._actionManager._getProperty(e)
    }
    ,
    i.prototype._getEffectiveTarget = function(e, t) {
        return this._actionManager._getEffectiveTarget(e, t)
    }
    ,
    i.prototype.serialize = function(e) {}
    ,
    i.prototype._serialize = function(e, t) {
        var r = {
            type: 1,
            children: [],
            name: e.name,
            properties: e.properties || []
        };
        if (this._child && this._child.serialize(r),
        this._condition) {
            var n = this._condition.serialize();
            return n.children.push(r),
            t && t.children.push(n),
            n
        }
        return t && t.children.push(r),
        r
    }
    ,
    i._SerializeValueAsString = function(e) {
        return typeof e == "number" ? e.toString() : typeof e == "boolean" ? e ? "true" : "false" : e instanceof Vector2 ? e.x + ", " + e.y : e instanceof Vector3 ? e.x + ", " + e.y + ", " + e.z : e instanceof Color3 ? e.r + ", " + e.g + ", " + e.b : e instanceof Color4 ? e.r + ", " + e.g + ", " + e.b + ", " + e.a : e
    }
    ,
    i._GetTargetProperty = function(e) {
        return {
            name: "target",
            targetType: e._isMesh ? "MeshProperties" : e._isLight ? "LightProperties" : e._isCamera ? "CameraProperties" : "SceneProperties",
            value: e._isScene ? "Scene" : e.name
        }
    }
    ,
    i
}();
RegisterClass("BABYLON.Action", Action);
var Condition = function() {
    function i(e) {
        this._actionManager = e
    }
    return i.prototype.isValid = function() {
        return !0
    }
    ,
    i.prototype._getProperty = function(e) {
        return this._actionManager._getProperty(e)
    }
    ,
    i.prototype._getEffectiveTarget = function(e, t) {
        return this._actionManager._getEffectiveTarget(e, t)
    }
    ,
    i.prototype.serialize = function() {}
    ,
    i.prototype._serialize = function(e) {
        return {
            type: 2,
            children: [],
            name: e.name,
            properties: e.properties
        }
    }
    ,
    i
}()
  , ValueCondition = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a) {
        a === void 0 && (a = e.IsEqual);
        var s = i.call(this, t) || this;
        return s.propertyPath = n,
        s.value = o,
        s.operator = a,
        s._target = r,
        s._effectiveTarget = s._getEffectiveTarget(r, s.propertyPath),
        s._property = s._getProperty(s.propertyPath),
        s
    }
    return Object.defineProperty(e, "IsEqual", {
        get: function() {
            return e._IsEqual
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e, "IsDifferent", {
        get: function() {
            return e._IsDifferent
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e, "IsGreater", {
        get: function() {
            return e._IsGreater
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e, "IsLesser", {
        get: function() {
            return e._IsLesser
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.isValid = function() {
        switch (this.operator) {
        case e.IsGreater:
            return this._effectiveTarget[this._property] > this.value;
        case e.IsLesser:
            return this._effectiveTarget[this._property] < this.value;
        case e.IsEqual:
        case e.IsDifferent:
            var t;
            return this.value.equals ? t = this.value.equals(this._effectiveTarget[this._property]) : t = this.value === this._effectiveTarget[this._property],
            this.operator === e.IsEqual ? t : !t
        }
        return !1
    }
    ,
    e.prototype.serialize = function() {
        return this._serialize({
            name: "ValueCondition",
            properties: [Action._GetTargetProperty(this._target), {
                name: "propertyPath",
                value: this.propertyPath
            }, {
                name: "value",
                value: Action._SerializeValueAsString(this.value)
            }, {
                name: "operator",
                value: e.GetOperatorName(this.operator)
            }]
        })
    }
    ,
    e.GetOperatorName = function(t) {
        switch (t) {
        case e._IsEqual:
            return "IsEqual";
        case e._IsDifferent:
            return "IsDifferent";
        case e._IsGreater:
            return "IsGreater";
        case e._IsLesser:
            return "IsLesser";
        default:
            return ""
        }
    }
    ,
    e._IsEqual = 0,
    e._IsDifferent = 1,
    e._IsGreater = 2,
    e._IsLesser = 3,
    e
}(Condition)
  , PredicateCondition = function(i) {
    __extends(e, i);
    function e(t, r) {
        var n = i.call(this, t) || this;
        return n.predicate = r,
        n
    }
    return e.prototype.isValid = function() {
        return this.predicate()
    }
    ,
    e
}(Condition)
  , StateCondition = function(i) {
    __extends(e, i);
    function e(t, r, n) {
        var o = i.call(this, t) || this;
        return o.value = n,
        o._target = r,
        o
    }
    return e.prototype.isValid = function() {
        return this._target.state === this.value
    }
    ,
    e.prototype.serialize = function() {
        return this._serialize({
            name: "StateCondition",
            properties: [Action._GetTargetProperty(this._target), {
                name: "value",
                value: this.value
            }]
        })
    }
    ,
    e
}(Condition);
RegisterClass("BABYLON.ValueCondition", ValueCondition);
RegisterClass("BABYLON.PredicateCondition", PredicateCondition);
RegisterClass("BABYLON.StateCondition", StateCondition);
(function(i) {
    __extends(e, i);
    function e(t, r, n, o) {
        var a = i.call(this, t, o) || this;
        return a.propertyPath = n,
        a._target = a._effectiveTarget = r,
        a
    }
    return e.prototype._prepare = function() {
        this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath),
        this._property = this._getProperty(this.propertyPath)
    }
    ,
    e.prototype.execute = function() {
        this._effectiveTarget[this._property] = !this._effectiveTarget[this._property]
    }
    ,
    e.prototype.serialize = function(t) {
        return i.prototype._serialize.call(this, {
            name: "SwitchBooleanAction",
            properties: [Action._GetTargetProperty(this._target), {
                name: "propertyPath",
                value: this.propertyPath
            }]
        }, t)
    }
    ,
    e
}
)(Action);
var SetStateAction = function(i) {
    __extends(e, i);
    function e(t, r, n, o) {
        var a = i.call(this, t, o) || this;
        return a.value = n,
        a._target = r,
        a
    }
    return e.prototype.execute = function() {
        this._target.state = this.value
    }
    ,
    e.prototype.serialize = function(t) {
        return i.prototype._serialize.call(this, {
            name: "SetStateAction",
            properties: [Action._GetTargetProperty(this._target), {
                name: "value",
                value: this.value
            }]
        }, t)
    }
    ,
    e
}(Action)
  , SetValueAction = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a) {
        var s = i.call(this, t, a) || this;
        return s.propertyPath = n,
        s.value = o,
        s._target = s._effectiveTarget = r,
        s
    }
    return e.prototype._prepare = function() {
        this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath),
        this._property = this._getProperty(this.propertyPath)
    }
    ,
    e.prototype.execute = function() {
        this._effectiveTarget[this._property] = this.value,
        this._target.markAsDirty && this._target.markAsDirty(this._property)
    }
    ,
    e.prototype.serialize = function(t) {
        return i.prototype._serialize.call(this, {
            name: "SetValueAction",
            properties: [Action._GetTargetProperty(this._target), {
                name: "propertyPath",
                value: this.propertyPath
            }, {
                name: "value",
                value: Action._SerializeValueAsString(this.value)
            }]
        }, t)
    }
    ,
    e
}(Action)
  , IncrementValueAction = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a) {
        var s = i.call(this, t, a) || this;
        return s.propertyPath = n,
        s.value = o,
        s._target = s._effectiveTarget = r,
        s
    }
    return e.prototype._prepare = function() {
        this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath),
        this._property = this._getProperty(this.propertyPath),
        typeof this._effectiveTarget[this._property] != "number" && Logger$2.Warn("Warning: IncrementValueAction can only be used with number values")
    }
    ,
    e.prototype.execute = function() {
        this._effectiveTarget[this._property] += this.value,
        this._target.markAsDirty && this._target.markAsDirty(this._property)
    }
    ,
    e.prototype.serialize = function(t) {
        return i.prototype._serialize.call(this, {
            name: "IncrementValueAction",
            properties: [Action._GetTargetProperty(this._target), {
                name: "propertyPath",
                value: this.propertyPath
            }, {
                name: "value",
                value: Action._SerializeValueAsString(this.value)
            }]
        }, t)
    }
    ,
    e
}(Action)
  , PlayAnimationAction = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a, s) {
        var l = i.call(this, t, s) || this;
        return l.from = n,
        l.to = o,
        l.loop = a,
        l._target = r,
        l
    }
    return e.prototype._prepare = function() {}
    ,
    e.prototype.execute = function() {
        var t = this._actionManager.getScene();
        t.beginAnimation(this._target, this.from, this.to, this.loop)
    }
    ,
    e.prototype.serialize = function(t) {
        return i.prototype._serialize.call(this, {
            name: "PlayAnimationAction",
            properties: [Action._GetTargetProperty(this._target), {
                name: "from",
                value: String(this.from)
            }, {
                name: "to",
                value: String(this.to)
            }, {
                name: "loop",
                value: Action._SerializeValueAsString(this.loop) || !1
            }]
        }, t)
    }
    ,
    e
}(Action)
  , StopAnimationAction = function(i) {
    __extends(e, i);
    function e(t, r, n) {
        var o = i.call(this, t, n) || this;
        return o._target = r,
        o
    }
    return e.prototype._prepare = function() {}
    ,
    e.prototype.execute = function() {
        var t = this._actionManager.getScene();
        t.stopAnimation(this._target)
    }
    ,
    e.prototype.serialize = function(t) {
        return i.prototype._serialize.call(this, {
            name: "StopAnimationAction",
            properties: [Action._GetTargetProperty(this._target)]
        }, t)
    }
    ,
    e
}(Action)
  , DoNothingAction = function(i) {
    __extends(e, i);
    function e(t, r) {
        return t === void 0 && (t = 0),
        i.call(this, t, r) || this
    }
    return e.prototype.execute = function() {}
    ,
    e.prototype.serialize = function(t) {
        return i.prototype._serialize.call(this, {
            name: "DoNothingAction",
            properties: []
        }, t)
    }
    ,
    e
}(Action);
(function(i) {
    __extends(e, i);
    function e(t, r, n, o) {
        o === void 0 && (o = !0);
        var a = i.call(this, t, n) || this;
        return a.children = r,
        a.enableChildrenConditions = o,
        a
    }
    return e.prototype._prepare = function() {
        for (var t = 0; t < this.children.length; t++)
            this.children[t]._actionManager = this._actionManager,
            this.children[t]._prepare()
    }
    ,
    e.prototype.execute = function(t) {
        for (var r = 0, n = this.children; r < n.length; r++) {
            var o = n[r];
            (!this.enableChildrenConditions || o._evaluateConditionForCurrentFrame()) && o.execute(t)
        }
    }
    ,
    e.prototype.serialize = function(t) {
        for (var r = i.prototype._serialize.call(this, {
            name: "CombineAction",
            properties: [],
            combine: []
        }, t), n = 0; n < this.children.length; n++)
            r.combine.push(this.children[n].serialize(null));
        return r
    }
    ,
    e
}
)(Action);
var ExecuteCodeAction = function(i) {
    __extends(e, i);
    function e(t, r, n) {
        var o = i.call(this, t, n) || this;
        return o.func = r,
        o
    }
    return e.prototype.execute = function(t) {
        this.func(t)
    }
    ,
    e
}(Action)
  , SetParentAction = function(i) {
    __extends(e, i);
    function e(t, r, n, o) {
        var a = i.call(this, t, o) || this;
        return a._target = r,
        a._parent = n,
        a
    }
    return e.prototype._prepare = function() {}
    ,
    e.prototype.execute = function() {
        if (this._target.parent !== this._parent) {
            var t = this._parent.getWorldMatrix().clone();
            t.invert(),
            this._target.position = Vector3.TransformCoordinates(this._target.position, t),
            this._target.parent = this._parent
        }
    }
    ,
    e.prototype.serialize = function(t) {
        return i.prototype._serialize.call(this, {
            name: "SetParentAction",
            properties: [Action._GetTargetProperty(this._target), Action._GetTargetProperty(this._parent)]
        }, t)
    }
    ,
    e
}(Action);
RegisterClass("BABYLON.SetParentAction", SetParentAction);
RegisterClass("BABYLON.ExecuteCodeAction", ExecuteCodeAction);
RegisterClass("BABYLON.DoNothingAction", DoNothingAction);
RegisterClass("BABYLON.StopAnimationAction", StopAnimationAction);
RegisterClass("BABYLON.PlayAnimationAction", PlayAnimationAction);
RegisterClass("BABYLON.IncrementValueAction", IncrementValueAction);
RegisterClass("BABYLON.SetValueAction", SetValueAction);
RegisterClass("BABYLON.SetStateAction", SetStateAction);
RegisterClass("BABYLON.SetParentAction", SetParentAction);
var ActionManager = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this) || this;
        return r._scene = t || EngineStore.LastCreatedScene,
        t.actionManagers.push(r),
        r
    }
    return e.prototype.dispose = function() {
        for (var t = this._scene.actionManagers.indexOf(this), r = 0; r < this.actions.length; r++) {
            var n = this.actions[r];
            e.Triggers[n.trigger]--,
            e.Triggers[n.trigger] === 0 && delete e.Triggers[n.trigger]
        }
        t > -1 && this._scene.actionManagers.splice(t, 1)
    }
    ,
    e.prototype.getScene = function() {
        return this._scene
    }
    ,
    e.prototype.hasSpecificTriggers = function(t) {
        for (var r = 0; r < this.actions.length; r++) {
            var n = this.actions[r];
            if (t.indexOf(n.trigger) > -1)
                return !0
        }
        return !1
    }
    ,
    e.prototype.hasSpecificTriggers2 = function(t, r) {
        for (var n = 0; n < this.actions.length; n++) {
            var o = this.actions[n];
            if (t == o.trigger || r == o.trigger)
                return !0
        }
        return !1
    }
    ,
    e.prototype.hasSpecificTrigger = function(t, r) {
        for (var n = 0; n < this.actions.length; n++) {
            var o = this.actions[n];
            if (o.trigger === t)
                if (r) {
                    if (r(o.getTriggerParameter()))
                        return !0
                } else
                    return !0
        }
        return !1
    }
    ,
    Object.defineProperty(e.prototype, "hasPointerTriggers", {
        get: function() {
            for (var t = 0; t < this.actions.length; t++) {
                var r = this.actions[t];
                if (r.trigger >= e.OnPickTrigger && r.trigger <= e.OnPointerOutTrigger)
                    return !0
            }
            return !1
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "hasPickTriggers", {
        get: function() {
            for (var t = 0; t < this.actions.length; t++) {
                var r = this.actions[t];
                if (r.trigger >= e.OnPickTrigger && r.trigger <= e.OnPickUpTrigger)
                    return !0
            }
            return !1
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.registerAction = function(t) {
        return t.trigger === e.OnEveryFrameTrigger && this.getScene().actionManager !== this ? (Logger$2.Warn("OnEveryFrameTrigger can only be used with scene.actionManager"),
        null) : (this.actions.push(t),
        e.Triggers[t.trigger] ? e.Triggers[t.trigger]++ : e.Triggers[t.trigger] = 1,
        t._actionManager = this,
        t._prepare(),
        t)
    }
    ,
    e.prototype.unregisterAction = function(t) {
        var r = this.actions.indexOf(t);
        return r !== -1 ? (this.actions.splice(r, 1),
        e.Triggers[t.trigger] -= 1,
        e.Triggers[t.trigger] === 0 && delete e.Triggers[t.trigger],
        t._actionManager = null,
        !0) : !1
    }
    ,
    e.prototype.processTrigger = function(t, r) {
        for (var n = 0; n < this.actions.length; n++) {
            var o = this.actions[n];
            if (o.trigger === t) {
                if (r && (t === e.OnKeyUpTrigger || t === e.OnKeyDownTrigger)) {
                    var a = o.getTriggerParameter();
                    if (a && a !== r.sourceEvent.keyCode) {
                        if (!a.toLowerCase)
                            continue;
                        var s = a.toLowerCase();
                        if (s !== r.sourceEvent.key) {
                            var l = r.sourceEvent.charCode ? r.sourceEvent.charCode : r.sourceEvent.keyCode
                              , u = String.fromCharCode(l).toLowerCase();
                            if (u !== s)
                                continue
                        }
                    }
                }
                o._executeCurrent(r)
            }
        }
    }
    ,
    e.prototype._getEffectiveTarget = function(t, r) {
        for (var n = r.split("."), o = 0; o < n.length - 1; o++)
            t = t[n[o]];
        return t
    }
    ,
    e.prototype._getProperty = function(t) {
        var r = t.split(".");
        return r[r.length - 1]
    }
    ,
    e.prototype.serialize = function(t) {
        for (var r = {
            children: new Array,
            name: t,
            type: 3,
            properties: new Array
        }, n = 0; n < this.actions.length; n++) {
            var o = {
                type: 0,
                children: new Array,
                name: e.GetTriggerName(this.actions[n].trigger),
                properties: new Array
            }
              , a = this.actions[n].triggerOptions;
            if (a && typeof a != "number")
                if (a.parameter instanceof Node)
                    o.properties.push(Action._GetTargetProperty(a.parameter));
                else {
                    var s = {};
                    DeepCopier.DeepCopy(a.parameter, s, ["mesh"]),
                    a.parameter && a.parameter.mesh && (s._meshId = a.parameter.mesh.id),
                    o.properties.push({
                        name: "parameter",
                        targetType: null,
                        value: s
                    })
                }
            this.actions[n].serialize(o),
            r.children.push(o)
        }
        return r
    }
    ,
    e.Parse = function(t, r, n) {
        var o = new e(n);
        r === null ? n.actionManager = o : r.actionManager = o;
        for (var a = function(g, m) {
            var v = GetClass("BABYLON." + g);
            if (v) {
                var y = Object.create(v.prototype);
                return y.constructor.apply(y, m),
                y
            }
        }, s = function(g, m, v, y) {
            if (y === null) {
                var b = parseFloat(m);
                return m === "true" || m === "false" ? m === "true" : isNaN(b) ? m : b
            }
            for (var T = y.split("."), C = m.split(","), A = 0; A < T.length; A++)
                v = v[T[A]];
            if (typeof v == "boolean")
                return C[0] === "true";
            if (typeof v == "string")
                return C[0];
            for (var S = new Array, A = 0; A < C.length; A++)
                S.push(parseFloat(C[A]));
            return v instanceof Vector3 ? Vector3.FromArray(S) : v instanceof Vector4 ? Vector4.FromArray(S) : v instanceof Color3 ? Color3.FromArray(S) : v instanceof Color4 ? Color4.FromArray(S) : parseFloat(C[0])
        }, l = function(g, m, v, y, b) {
            if (b === void 0 && (b = null),
            !g.detached) {
                var T = new Array
                  , C = null
                  , A = null
                  , S = g.combine && g.combine.length > 0;
                if (g.type === 2 ? T.push(o) : T.push(m),
                S) {
                    for (var P = new Array, R = 0; R < g.combine.length; R++)
                        l(g.combine[R], e.NothingTrigger, v, y, P);
                    T.push(P)
                } else
                    for (var M = 0; M < g.properties.length; M++) {
                        var x = g.properties[M].value
                          , I = g.properties[M].name
                          , w = g.properties[M].targetType;
                        I === "target" ? w !== null && w === "SceneProperties" ? x = C = n : x = C = n.getNodeByName(x) : I === "parent" ? x = n.getNodeByName(x) : I === "sound" ? n.getSoundByName && (x = n.getSoundByName(x)) : I !== "propertyPath" ? g.type === 2 && I === "operator" ? x = ValueCondition[x] : x = s(I, x, C, I === "value" ? A : null) : A = x,
                        T.push(x)
                    }
                if (b === null ? T.push(v) : T.push(null),
                g.name === "InterpolateValueAction") {
                    var O = T[T.length - 2];
                    T[T.length - 1] = O,
                    T[T.length - 2] = v
                }
                var D = a(g.name, T);
                if (D instanceof Condition && v !== null) {
                    var F = new DoNothingAction(m,v);
                    y ? y.then(F) : o.registerAction(F),
                    y = F
                }
                b === null ? D instanceof Condition ? (v = D,
                D = y) : (v = null,
                y ? y.then(D) : o.registerAction(D)) : b.push(D);
                for (var M = 0; M < g.children.length; M++)
                    l(g.children[M], m, v, D, null)
            }
        }, u = 0; u < t.children.length; u++) {
            var c, h = t.children[u];
            if (h.properties.length > 0) {
                var f = h.properties[0].value
                  , d = h.properties[0].targetType === null ? f : n.getMeshByName(f);
                d._meshId && (d.mesh = n.getMeshById(d._meshId)),
                c = {
                    trigger: e[h.name],
                    parameter: d
                }
            } else
                c = e[h.name];
            for (var _ = 0; _ < h.children.length; _++)
                h.detached || l(h.children[_], c, null, null)
        }
    }
    ,
    e.GetTriggerName = function(t) {
        switch (t) {
        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 ""
        }
    }
    ,
    e.NothingTrigger = 0,
    e.OnPickTrigger = 1,
    e.OnLeftPickTrigger = 2,
    e.OnRightPickTrigger = 3,
    e.OnCenterPickTrigger = 4,
    e.OnPickDownTrigger = 5,
    e.OnDoublePickTrigger = 6,
    e.OnPickUpTrigger = 7,
    e.OnPickOutTrigger = 16,
    e.OnLongPressTrigger = 8,
    e.OnPointerOverTrigger = 9,
    e.OnPointerOutTrigger = 10,
    e.OnEveryFrameTrigger = 11,
    e.OnIntersectionEnterTrigger = 12,
    e.OnIntersectionExitTrigger = 13,
    e.OnKeyDownTrigger = 14,
    e.OnKeyUpTrigger = 15,
    e
}(AbstractActionManager);
Node$2.AddNodeConstructor("Light_Type_0", function(i, e) {
    return function() {
        return new PointLight(i,Vector3.Zero(),e)
    }
});
var PointLight = function(i) {
    __extends(e, i);
    function e(t, r, n) {
        var o = i.call(this, t, n) || this;
        return o._shadowAngle = Math.PI / 2,
        o.position = r,
        o
    }
    return Object.defineProperty(e.prototype, "shadowAngle", {
        get: function() {
            return this._shadowAngle
        },
        set: function(t) {
            this._shadowAngle = t,
            this.forceProjectionMatrixCompute()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "direction", {
        get: function() {
            return this._direction
        },
        set: function(t) {
            var r = this.needCube();
            this._direction = t,
            this.needCube() !== r && this._shadowGenerator && this._shadowGenerator.recreateShadowMap()
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getClassName = function() {
        return "PointLight"
    }
    ,
    e.prototype.getTypeID = function() {
        return Light.LIGHTTYPEID_POINTLIGHT
    }
    ,
    e.prototype.needCube = function() {
        return !this.direction
    }
    ,
    e.prototype.getShadowDirection = function(t) {
        if (this.direction)
            return i.prototype.getShadowDirection.call(this, t);
        switch (t) {
        case 0:
            return new Vector3(1,0,0);
        case 1:
            return new Vector3(-1,0,0);
        case 2:
            return new Vector3(0,-1,0);
        case 3:
            return new Vector3(0,1,0);
        case 4:
            return new Vector3(0,0,1);
        case 5:
            return new Vector3(0,0,-1)
        }
        return Vector3.Zero()
    }
    ,
    e.prototype._setDefaultShadowProjectionMatrix = function(t, r, n) {
        var o = this.getScene().activeCamera;
        if (!!o) {
            var a = this.shadowMinZ !== void 0 ? this.shadowMinZ : o.minZ
              , s = this.shadowMaxZ !== void 0 ? this.shadowMaxZ : o.maxZ
              , l = this.getScene().getEngine().useReverseDepthBuffer;
            Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1, l ? s : a, l ? a : s, t, !0, this._scene.getEngine().isNDCHalfZRange, void 0, l)
        }
    }
    ,
    e.prototype._buildUniformLayout = function() {
        this._uniformBuffer.addUniform("vLightData", 4),
        this._uniformBuffer.addUniform("vLightDiffuse", 4),
        this._uniformBuffer.addUniform("vLightSpecular", 4),
        this._uniformBuffer.addUniform("vLightFalloff", 4),
        this._uniformBuffer.addUniform("shadowsInfo", 3),
        this._uniformBuffer.addUniform("depthValues", 2),
        this._uniformBuffer.create()
    }
    ,
    e.prototype.transferToEffect = function(t, r) {
        return this.computeTransformedInformation() ? this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0, r) : this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, r),
        this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, r),
        this
    }
    ,
    e.prototype.transferToNodeMaterialEffect = function(t, r) {
        return this.computeTransformedInformation() ? t.setFloat3(r, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z) : t.setFloat3(r, this.position.x, this.position.y, this.position.z),
        this
    }
    ,
    e.prototype.prepareLightSpecificDefines = function(t, r) {
        t["POINTLIGHT" + r] = !0
    }
    ,
    __decorate([serialize()], e.prototype, "shadowAngle", null),
    e
}(ShadowLight);
function CreateRibbonVertexData(i) {
    var e = i.pathArray
      , t = i.closeArray || !1
      , r = i.closePath || !1
      , n = i.invertUV || !1
      , o = Math.floor(e[0].length / 2)
      , a = i.offset || o;
    a = a > o ? o : Math.floor(a);
    var s = i.sideOrientation === 0 ? 0 : i.sideOrientation || VertexData.DEFAULTSIDE, l = i.uvs, u = i.colors, c = [], h = [], f = [], d = [], _ = [], g = [], m = [], v = [], y, b = [], T = [], C, A, S;
    if (e.length < 2) {
        var P = []
          , R = [];
        for (A = 0; A < e[0].length - a; A++)
            P.push(e[0][A]),
            R.push(e[0][A + a]);
        e = [P, R]
    }
    var M = 0, x = r ? 1 : 0, I, w;
    y = e[0].length;
    var O, D;
    for (C = 0; C < e.length; C++) {
        for (m[C] = 0,
        _[C] = [0],
        I = e[C],
        w = I.length,
        y = y < w ? y : w,
        S = 0; S < w; )
            c.push(I[S].x, I[S].y, I[S].z),
            S > 0 && (O = I[S].subtract(I[S - 1]).length(),
            D = O + m[C],
            _[C].push(D),
            m[C] = D),
            S++;
        r && (S--,
        c.push(I[0].x, I[0].y, I[0].z),
        O = I[S].subtract(I[0]).length(),
        D = O + m[C],
        _[C].push(D),
        m[C] = D),
        b[C] = w + x,
        T[C] = M,
        M += w + x
    }
    var F, V, N = null, L = null;
    for (A = 0; A < y + x; A++) {
        for (v[A] = 0,
        g[A] = [0],
        C = 0; C < e.length - 1; C++)
            F = e[C],
            V = e[C + 1],
            A === y ? (N = F[0],
            L = V[0]) : (N = F[A],
            L = V[A]),
            O = L.subtract(N).length(),
            D = O + v[A],
            g[A].push(D),
            v[A] = D;
        t && L && N && (F = e[C],
        V = e[0],
        A === y && (L = V[0]),
        O = L.subtract(N).length(),
        D = O + v[A],
        v[A] = D)
    }
    var k, U;
    if (l)
        for (C = 0; C < l.length; C++)
            d.push(l[C].x, l[C].y);
    else
        for (C = 0; C < e.length; C++)
            for (A = 0; A < y + x; A++)
                k = m[C] != 0 ? _[C][A] / m[C] : 0,
                U = v[A] != 0 ? g[A][C] / v[A] : 0,
                n ? d.push(U, k) : d.push(k, U);
    C = 0;
    for (var z = 0, H = b[C] - 1, G = b[C + 1] - 1, W = H < G ? H : G, j = T[1] - T[0], B = t ? b.length : b.length - 1; z <= W && C < B; )
        h.push(z, z + j, z + 1),
        h.push(z + j + 1, z + 1, z + j),
        z += 1,
        z === W && (C++,
        C === b.length - 1 ? (j = T[0] - T[C],
        H = b[C] - 1,
        G = b[0] - 1) : (j = T[C + 1] - T[C],
        H = b[C] - 1,
        G = b[C + 1] - 1),
        z = T[C],
        W = H < G ? H + z : G + z);
    if (VertexData.ComputeNormals(c, h, f),
    r) {
        var X = 0
          , $ = 0;
        for (C = 0; C < e.length; C++)
            X = T[C] * 3,
            C + 1 < e.length ? $ = (T[C + 1] - 1) * 3 : $ = f.length - 3,
            f[X] = (f[X] + f[$]) * .5,
            f[X + 1] = (f[X + 1] + f[$ + 1]) * .5,
            f[X + 2] = (f[X + 2] + f[$ + 2]) * .5,
            f[$] = f[X],
            f[$ + 1] = f[X + 1],
            f[$ + 2] = f[X + 2]
    }
    VertexData._ComputeSides(s, c, h, f, d, i.frontUVs, i.backUVs);
    var Y = null;
    if (u) {
        Y = new Float32Array(u.length * 4);
        for (var K = 0; K < u.length; K++)
            Y[K * 4] = u[K].r,
            Y[K * 4 + 1] = u[K].g,
            Y[K * 4 + 2] = u[K].b,
            Y[K * 4 + 3] = u[K].a
    }
    var Z = new VertexData
      , q = new Float32Array(c)
      , J = new Float32Array(f)
      , Q = new Float32Array(d);
    return Z.indices = h,
    Z.positions = q,
    Z.normals = J,
    Z.uvs = Q,
    Y && Z.set(Y, VertexBuffer.ColorKind),
    r && (Z._idx = T),
    Z
}
function CreateRibbon(i, e, t) {
    t === void 0 && (t = null);
    var r = e.pathArray
      , n = e.closeArray
      , o = e.closePath
      , a = Mesh._GetDefaultSideOrientation(e.sideOrientation)
      , s = e.instance
      , l = e.updatable;
    if (s) {
        var u = TmpVectors.Vector3[0].setAll(Number.MAX_VALUE)
          , c = TmpVectors.Vector3[1].setAll(-Number.MAX_VALUE)
          , h = function(x) {
            for (var I = r[0].length, w = s, O = 0, D = w._originalBuilderSideOrientation === Mesh.DOUBLESIDE ? 2 : 1, F = 1; F <= D; ++F)
                for (var V = 0; V < r.length; ++V) {
                    var N = r[V]
                      , L = N.length;
                    I = I < L ? I : L;
                    for (var k = 0; k < I; ++k) {
                        var U = N[k];
                        x[O] = U.x,
                        x[O + 1] = U.y,
                        x[O + 2] = U.z,
                        u.minimizeInPlaceFromFloats(U.x, U.y, U.z),
                        c.maximizeInPlaceFromFloats(U.x, U.y, U.z),
                        O += 3
                    }
                    if (w._creationDataStorage && w._creationDataStorage.closePath) {
                        var U = N[0];
                        x[O] = U.x,
                        x[O + 1] = U.y,
                        x[O + 2] = U.z,
                        O += 3
                    }
                }
        }
          , f = s.getVerticesData(VertexBuffer.PositionKind);
        if (h(f),
        s.hasBoundingInfo ? s.getBoundingInfo().reConstruct(u, c, s._worldMatrix) : s.buildBoundingInfo(u, c, s._worldMatrix),
        s.updateVerticesData(VertexBuffer.PositionKind, f, !1, !1),
        e.colors) {
            for (var d = s.getVerticesData(VertexBuffer.ColorKind), _ = 0, g = 0; _ < e.colors.length; _++,
            g += 4) {
                var m = e.colors[_];
                d[g] = m.r,
                d[g + 1] = m.g,
                d[g + 2] = m.b,
                d[g + 3] = m.a
            }
            s.updateVerticesData(VertexBuffer.ColorKind, d, !1, !1)
        }
        if (e.uvs) {
            for (var v = s.getVerticesData(VertexBuffer.UVKind), y = 0; y < e.uvs.length; y++)
                v[y * 2] = e.uvs[y].x,
                v[y * 2 + 1] = e.uvs[y].y;
            s.updateVerticesData(VertexBuffer.UVKind, v, !1, !1)
        }
        if (!s.areNormalsFrozen || s.isFacetDataEnabled) {
            var b = s.getIndices()
              , T = s.getVerticesData(VertexBuffer.NormalKind)
              , C = s.isFacetDataEnabled ? s.getFacetDataParameters() : null;
            if (VertexData.ComputeNormals(f, b, T, C),
            s._creationDataStorage && s._creationDataStorage.closePath)
                for (var A = 0, S = 0, P = 0; P < r.length; P++)
                    A = s._creationDataStorage.idx[P] * 3,
                    P + 1 < r.length ? S = (s._creationDataStorage.idx[P + 1] - 1) * 3 : S = T.length - 3,
                    T[A] = (T[A] + T[S]) * .5,
                    T[A + 1] = (T[A + 1] + T[S + 1]) * .5,
                    T[A + 2] = (T[A + 2] + T[S + 2]) * .5,
                    T[S] = T[A],
                    T[S + 1] = T[A + 1],
                    T[S + 2] = T[A + 2];
            s.areNormalsFrozen || s.updateVerticesData(VertexBuffer.NormalKind, T, !1, !1)
        }
        return s
    } else {
        var R = new Mesh(i,t);
        R._originalBuilderSideOrientation = a,
        R._creationDataStorage = new _CreationDataStorage;
        var M = CreateRibbonVertexData(e);
        return o && (R._creationDataStorage.idx = M._idx),
        R._creationDataStorage.closePath = o,
        R._creationDataStorage.closeArray = n,
        M.applyToMesh(R, l),
        R
    }
}
VertexData.CreateRibbon = CreateRibbonVertexData;
Mesh.CreateRibbon = function(i, e, t, r, n, o, a, s, l) {
    return t === void 0 && (t = !1),
    a === void 0 && (a = !1),
    CreateRibbon(i, {
        pathArray: e,
        closeArray: t,
        closePath: r,
        offset: n,
        updatable: a,
        sideOrientation: s,
        instance: l
    }, o)
}
;
function CreateDiscVertexData(i) {
    var e = new Array
      , t = new Array
      , r = new Array
      , n = new Array
      , o = i.radius || .5
      , a = i.tessellation || 64
      , s = i.arc && (i.arc <= 0 || i.arc > 1) ? 1 : i.arc || 1
      , l = i.sideOrientation === 0 ? 0 : i.sideOrientation || VertexData.DEFAULTSIDE;
    e.push(0, 0, 0),
    n.push(.5, .5);
    for (var u = Math.PI * 2 * s, c = s === 1 ? u / a : u / (a - 1), h = 0, f = 0; f < a; f++) {
        var d = Math.cos(h)
          , _ = Math.sin(h)
          , g = (d + 1) / 2
          , m = (1 - _) / 2;
        e.push(o * d, o * _, 0),
        n.push(g, m),
        h += c
    }
    s === 1 && (e.push(e[3], e[4], e[5]),
    n.push(n[2], n[3]));
    for (var v = e.length / 3, y = 1; y < v - 1; y++)
        t.push(y + 1, 0, y);
    VertexData.ComputeNormals(e, t, r),
    VertexData._ComputeSides(l, e, t, r, n, i.frontUVs, i.backUVs);
    var b = new VertexData;
    return b.indices = t,
    b.positions = e,
    b.normals = r,
    b.uvs = n,
    b
}
function CreateDisc(i, e, t) {
    e === void 0 && (e = {}),
    t === void 0 && (t = null);
    var r = new Mesh(i,t);
    e.sideOrientation = Mesh._GetDefaultSideOrientation(e.sideOrientation),
    r._originalBuilderSideOrientation = e.sideOrientation;
    var n = CreateDiscVertexData(e);
    return n.applyToMesh(r, e.updatable),
    r
}
VertexData.CreateDisc = CreateDiscVertexData;
Mesh.CreateDisc = function(i, e, t, r, n, o) {
    r === void 0 && (r = null);
    var a = {
        radius: e,
        tessellation: t,
        sideOrientation: o,
        updatable: n
    };
    return CreateDisc(i, a, r)
}
;
function CreateBoxVertexData(i) {
    var e = 6
      , t = [0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7, 8, 9, 10, 8, 10, 11, 12, 13, 14, 12, 14, 15, 16, 17, 18, 16, 18, 19, 20, 21, 22, 20, 22, 23]
      , r = [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0]
      , n = []
      , o = []
      , a = i.width || i.size || 1
      , s = i.height || i.size || 1
      , l = i.depth || i.size || 1
      , u = i.wrap || !1
      , c = i.topBaseAt === void 0 ? 1 : i.topBaseAt
      , h = i.bottomBaseAt === void 0 ? 0 : i.bottomBaseAt;
    c = (c + 4) % 4,
    h = (h + 4) % 4;
    var f = [2, 0, 3, 1]
      , d = [2, 0, 1, 3]
      , _ = f[c]
      , g = d[h]
      , m = [1, -1, 1, -1, -1, 1, -1, 1, 1, 1, 1, 1, 1, 1, -1, -1, 1, -1, -1, -1, -1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, -1, 1, 1, 1, 1, -1, 1, 1, -1, -1, 1, -1, -1, -1, -1, 1, -1, -1, 1, 1, -1, 1, -1, 1, 1, -1, 1, 1, 1, 1, -1, 1, 1, -1, -1, -1, -1, -1, -1, -1, 1];
    if (u) {
        t = [2, 3, 0, 2, 0, 1, 4, 5, 6, 4, 6, 7, 9, 10, 11, 9, 11, 8, 12, 14, 15, 12, 13, 14],
        m = [-1, 1, 1, 1, 1, 1, 1, -1, 1, -1, -1, 1, 1, 1, -1, -1, 1, -1, -1, -1, -1, 1, -1, -1, 1, 1, 1, 1, 1, -1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1, 1, 1, -1, -1, 1, -1, -1, -1];
        for (var v = [[1, 1, 1], [-1, 1, 1], [-1, 1, -1], [1, 1, -1]], y = [[-1, -1, 1], [1, -1, 1], [1, -1, -1], [-1, -1, -1]], b = [17, 18, 19, 16], T = [22, 23, 20, 21]; _ > 0; )
            v.unshift(v.pop()),
            b.unshift(b.pop()),
            _--;
        for (; g > 0; )
            y.unshift(y.pop()),
            T.unshift(T.pop()),
            g--;
        v = v.flat(),
        y = y.flat(),
        m = m.concat(v).concat(y),
        t.push(b[0], b[2], b[3], b[0], b[1], b[2]),
        t.push(T[0], T[2], T[3], T[0], T[1], T[2])
    }
    var C = [a / 2, s / 2, l / 2];
    o = m.reduce(function(D, F, V) {
        return D.concat(F * C[V % 3])
    }, []);
    for (var A = i.sideOrientation === 0 ? 0 : i.sideOrientation || VertexData.DEFAULTSIDE, S = i.faceUV || new Array(6), P = i.faceColors, R = [], M = 0; M < 6; M++)
        S[M] === void 0 && (S[M] = new Vector4(0,0,1,1)),
        P && P[M] === void 0 && (P[M] = new Color4(1,1,1,1));
    for (var x = 0; x < e; x++)
        if (n.push(S[x].z, S[x].w),
        n.push(S[x].x, S[x].w),
        n.push(S[x].x, S[x].y),
        n.push(S[x].z, S[x].y),
        P)
            for (var I = 0; I < 4; I++)
                R.push(P[x].r, P[x].g, P[x].b, P[x].a);
    VertexData._ComputeSides(A, o, t, r, n, i.frontUVs, i.backUVs);
    var w = new VertexData;
    if (w.indices = t,
    w.positions = o,
    w.normals = r,
    w.uvs = n,
    P) {
        var O = A === VertexData.DOUBLESIDE ? R.concat(R) : R;
        w.colors = O
    }
    return w
}
function CreateBox(i, e, t) {
    e === void 0 && (e = {}),
    t === void 0 && (t = null);
    var r = new Mesh(i,t);
    e.sideOrientation = Mesh._GetDefaultSideOrientation(e.sideOrientation),
    r._originalBuilderSideOrientation = e.sideOrientation;
    var n = CreateBoxVertexData(e);
    return n.applyToMesh(r, e.updatable),
    r
}
VertexData.CreateBox = CreateBoxVertexData;
Mesh.CreateBox = function(i, e, t, r, n) {
    t === void 0 && (t = null);
    var o = {
        size: e,
        sideOrientation: n,
        updatable: r
    };
    return CreateBox(i, o, t)
}
;
function CreateTiledPlaneVertexData(i) {
    var e = i.pattern || Mesh.NO_FLIP
      , t = i.tileWidth || i.tileSize || 1
      , r = i.tileHeight || i.tileSize || 1
      , n = i.alignHorizontal || 0
      , o = i.alignVertical || 0
      , a = i.width || i.size || 1
      , s = Math.floor(a / t)
      , l = a - s * t
      , u = i.height || i.size || 1
      , c = Math.floor(u / r)
      , h = u - c * r
      , f = t * s / 2
      , d = r * c / 2
      , _ = 0
      , g = 0
      , m = 0
      , v = 0
      , y = 0
      , b = 0;
    if (l > 0 || h > 0) {
        m = -f,
        v = -d;
        var y = f
          , b = d;
        switch (n) {
        case Mesh.CENTER:
            l /= 2,
            m -= l,
            y += l;
            break;
        case Mesh.LEFT:
            y += l,
            _ = -l / 2;
            break;
        case Mesh.RIGHT:
            m -= l,
            _ = l / 2;
            break
        }
        switch (o) {
        case Mesh.CENTER:
            h /= 2,
            v -= h,
            b += h;
            break;
        case Mesh.BOTTOM:
            b += h,
            g = -h / 2;
            break;
        case Mesh.TOP:
            v -= h,
            g = h / 2;
            break
        }
    }
    var T = []
      , C = []
      , A = [];
    A[0] = [0, 0, 1, 0, 1, 1, 0, 1],
    A[1] = [0, 0, 1, 0, 1, 1, 0, 1],
    (e === Mesh.ROTATE_TILE || e === Mesh.ROTATE_ROW) && (A[1] = [1, 1, 0, 1, 0, 0, 1, 0]),
    (e === Mesh.FLIP_TILE || e === Mesh.FLIP_ROW) && (A[1] = [1, 0, 0, 0, 0, 1, 1, 1]),
    (e === Mesh.FLIP_N_ROTATE_TILE || e === Mesh.FLIP_N_ROTATE_ROW) && (A[1] = [0, 1, 1, 1, 1, 0, 0, 0]);
    for (var S = [], P = [], R = [], M = 0, x = 0; x < c; x++)
        for (var I = 0; I < s; I++)
            T.push(-f + I * t + _, -d + x * r + g, 0),
            T.push(-f + (I + 1) * t + _, -d + x * r + g, 0),
            T.push(-f + (I + 1) * t + _, -d + (x + 1) * r + g, 0),
            T.push(-f + I * t + _, -d + (x + 1) * r + g, 0),
            R.push(M, M + 1, M + 3, M + 1, M + 2, M + 3),
            e === Mesh.FLIP_TILE || e === Mesh.ROTATE_TILE || e === Mesh.FLIP_N_ROTATE_TILE ? S = S.concat(A[(I % 2 + x % 2) % 2]) : e === Mesh.FLIP_ROW || e === Mesh.ROTATE_ROW || e === Mesh.FLIP_N_ROTATE_ROW ? S = S.concat(A[x % 2]) : S = S.concat(A[0]),
            P.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
            C.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1),
            M += 4;
    if (l > 0 || h > 0) {
        var w = h > 0 && (o === Mesh.CENTER || o === Mesh.TOP), O = h > 0 && (o === Mesh.CENTER || o === Mesh.BOTTOM), D = l > 0 && (n === Mesh.CENTER || n === Mesh.RIGHT), F = l > 0 && (n === Mesh.CENTER || n === Mesh.LEFT), V = [], N, L, k, U;
        if (w && D && (T.push(m + _, v + g, 0),
        T.push(-f + _, v + g, 0),
        T.push(-f + _, v + h + g, 0),
        T.push(m + _, v + h + g, 0),
        R.push(M, M + 1, M + 3, M + 1, M + 2, M + 3),
        M += 4,
        N = 1 - l / t,
        L = 1 - h / r,
        k = 1,
        U = 1,
        V = [N, L, k, L, k, U, N, U],
        e === Mesh.ROTATE_ROW && (V = [1 - N, 1 - L, 1 - k, 1 - L, 1 - k, 1 - U, 1 - N, 1 - U]),
        e === Mesh.FLIP_ROW && (V = [1 - N, L, 1 - k, L, 1 - k, U, 1 - N, U]),
        e === Mesh.FLIP_N_ROTATE_ROW && (V = [N, 1 - L, k, 1 - L, k, 1 - U, N, 1 - U]),
        S = S.concat(V),
        P.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
        C.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1)),
        w && F && (T.push(f + _, v + g, 0),
        T.push(y + _, v + g, 0),
        T.push(y + _, v + h + g, 0),
        T.push(f + _, v + h + g, 0),
        R.push(M, M + 1, M + 3, M + 1, M + 2, M + 3),
        M += 4,
        N = 0,
        L = 1 - h / r,
        k = l / t,
        U = 1,
        V = [N, L, k, L, k, U, N, U],
        (e === Mesh.ROTATE_ROW || e === Mesh.ROTATE_TILE && s % 2 === 0) && (V = [1 - N, 1 - L, 1 - k, 1 - L, 1 - k, 1 - U, 1 - N, 1 - U]),
        (e === Mesh.FLIP_ROW || e === Mesh.FLIP_TILE && s % 2 === 0) && (V = [1 - N, L, 1 - k, L, 1 - k, U, 1 - N, U]),
        (e === Mesh.FLIP_N_ROTATE_ROW || e === Mesh.FLIP_N_ROTATE_TILE && s % 2 === 0) && (V = [N, 1 - L, k, 1 - L, k, 1 - U, N, 1 - U]),
        S = S.concat(V),
        P.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
        C.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1)),
        O && D && (T.push(m + _, d + g, 0),
        T.push(-f + _, d + g, 0),
        T.push(-f + _, b + g, 0),
        T.push(m + _, b + g, 0),
        R.push(M, M + 1, M + 3, M + 1, M + 2, M + 3),
        M += 4,
        N = 1 - l / t,
        L = 0,
        k = 1,
        U = h / r,
        V = [N, L, k, L, k, U, N, U],
        (e === Mesh.ROTATE_ROW && c % 2 === 1 || e === Mesh.ROTATE_TILE && c % 1 === 0) && (V = [1 - N, 1 - L, 1 - k, 1 - L, 1 - k, 1 - U, 1 - N, 1 - U]),
        (e === Mesh.FLIP_ROW && c % 2 === 1 || e === Mesh.FLIP_TILE && c % 2 === 0) && (V = [1 - N, L, 1 - k, L, 1 - k, U, 1 - N, U]),
        (e === Mesh.FLIP_N_ROTATE_ROW && c % 2 === 1 || e === Mesh.FLIP_N_ROTATE_TILE && c % 2 === 0) && (V = [N, 1 - L, k, 1 - L, k, 1 - U, N, 1 - U]),
        S = S.concat(V),
        P.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
        C.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1)),
        O && F && (T.push(f + _, d + g, 0),
        T.push(y + _, d + g, 0),
        T.push(y + _, b + g, 0),
        T.push(f + _, b + g, 0),
        R.push(M, M + 1, M + 3, M + 1, M + 2, M + 3),
        M += 4,
        N = 0,
        L = 0,
        k = l / t,
        U = h / r,
        V = [N, L, k, L, k, U, N, U],
        (e === Mesh.ROTATE_ROW && c % 2 === 1 || e === Mesh.ROTATE_TILE && (c + s) % 2 === 1) && (V = [1 - N, 1 - L, 1 - k, 1 - L, 1 - k, 1 - U, 1 - N, 1 - U]),
        (e === Mesh.FLIP_ROW && c % 2 === 1 || e === Mesh.FLIP_TILE && (c + s) % 2 === 1) && (V = [1 - N, L, 1 - k, L, 1 - k, U, 1 - N, U]),
        (e === Mesh.FLIP_N_ROTATE_ROW && c % 2 === 1 || e === Mesh.FLIP_N_ROTATE_TILE && (c + s) % 2 === 1) && (V = [N, 1 - L, k, 1 - L, k, 1 - U, N, 1 - U]),
        S = S.concat(V),
        P.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
        C.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1)),
        w) {
            var z = [];
            N = 0,
            L = 1 - h / r,
            k = 1,
            U = 1,
            z[0] = [N, L, k, L, k, U, N, U],
            z[1] = [N, L, k, L, k, U, N, U],
            (e === Mesh.ROTATE_TILE || e === Mesh.ROTATE_ROW) && (z[1] = [1 - N, 1 - L, 1 - k, 1 - L, 1 - k, 1 - U, 1 - N, 1 - U]),
            (e === Mesh.FLIP_TILE || e === Mesh.FLIP_ROW) && (z[1] = [1 - N, L, 1 - k, L, 1 - k, U, 1 - N, U]),
            (e === Mesh.FLIP_N_ROTATE_TILE || e === Mesh.FLIP_N_ROTATE_ROW) && (z[1] = [N, 1 - L, k, 1 - L, k, 1 - U, N, 1 - U]);
            for (var I = 0; I < s; I++)
                T.push(-f + I * t + _, v + g, 0),
                T.push(-f + (I + 1) * t + _, v + g, 0),
                T.push(-f + (I + 1) * t + _, v + h + g, 0),
                T.push(-f + I * t + _, v + h + g, 0),
                R.push(M, M + 1, M + 3, M + 1, M + 2, M + 3),
                M += 4,
                e === Mesh.FLIP_TILE || e === Mesh.ROTATE_TILE || e === Mesh.FLIP_N_ROTATE_TILE ? S = S.concat(z[(I + 1) % 2]) : e === Mesh.FLIP_ROW || e === Mesh.ROTATE_ROW || e === Mesh.FLIP_N_ROTATE_ROW ? S = S.concat(z[1]) : S = S.concat(z[0]),
                P.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
                C.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1)
        }
        if (O) {
            var H = [];
            N = 0,
            L = 0,
            k = 1,
            U = h / r,
            H[0] = [N, L, k, L, k, U, N, U],
            H[1] = [N, L, k, L, k, U, N, U],
            (e === Mesh.ROTATE_TILE || e === Mesh.ROTATE_ROW) && (H[1] = [1 - N, 1 - L, 1 - k, 1 - L, 1 - k, 1 - U, 1 - N, 1 - U]),
            (e === Mesh.FLIP_TILE || e === Mesh.FLIP_ROW) && (H[1] = [1 - N, L, 1 - k, L, 1 - k, U, 1 - N, U]),
            (e === Mesh.FLIP_N_ROTATE_TILE || e === Mesh.FLIP_N_ROTATE_ROW) && (H[1] = [N, 1 - L, k, 1 - L, k, 1 - U, N, 1 - U]);
            for (var I = 0; I < s; I++)
                T.push(-f + I * t + _, b - h + g, 0),
                T.push(-f + (I + 1) * t + _, b - h + g, 0),
                T.push(-f + (I + 1) * t + _, b + g, 0),
                T.push(-f + I * t + _, b + g, 0),
                R.push(M, M + 1, M + 3, M + 1, M + 2, M + 3),
                M += 4,
                e === Mesh.FLIP_TILE || e === Mesh.ROTATE_TILE || e === Mesh.FLIP_N_ROTATE_TILE ? S = S.concat(H[(I + c) % 2]) : e === Mesh.FLIP_ROW || e === Mesh.ROTATE_ROW || e === Mesh.FLIP_N_ROTATE_ROW ? S = S.concat(H[c % 2]) : S = S.concat(H[0]),
                P.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
                C.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1)
        }
        if (D) {
            var G = [];
            N = 1 - l / t,
            L = 0,
            k = 1,
            U = 1,
            G[0] = [N, L, k, L, k, U, N, U],
            G[1] = [N, L, k, L, k, U, N, U],
            (e === Mesh.ROTATE_TILE || e === Mesh.ROTATE_ROW) && (G[1] = [1 - N, 1 - L, 1 - k, 1 - L, 1 - k, 1 - U, 1 - N, 1 - U]),
            (e === Mesh.FLIP_TILE || e === Mesh.FLIP_ROW) && (G[1] = [1 - N, L, 1 - k, L, 1 - k, U, 1 - N, U]),
            (e === Mesh.FLIP_N_ROTATE_TILE || e === Mesh.FLIP_N_ROTATE_ROW) && (G[1] = [N, 1 - L, k, 1 - L, k, 1 - U, N, 1 - U]);
            for (var x = 0; x < c; x++)
                T.push(m + _, -d + x * r + g, 0),
                T.push(m + l + _, -d + x * r + g, 0),
                T.push(m + l + _, -d + (x + 1) * r + g, 0),
                T.push(m + _, -d + (x + 1) * r + g, 0),
                R.push(M, M + 1, M + 3, M + 1, M + 2, M + 3),
                M += 4,
                e === Mesh.FLIP_TILE || e === Mesh.ROTATE_TILE || e === Mesh.FLIP_N_ROTATE_TILE ? S = S.concat(G[(x + 1) % 2]) : e === Mesh.FLIP_ROW || e === Mesh.ROTATE_ROW || e === Mesh.FLIP_N_ROTATE_ROW ? S = S.concat(G[x % 2]) : S = S.concat(G[0]),
                P.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
                C.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1)
        }
        if (F) {
            var W = [];
            N = 0,
            L = 0,
            k = l / r,
            U = 1,
            W[0] = [N, L, k, L, k, U, N, U],
            W[1] = [N, L, k, L, k, U, N, U],
            (e === Mesh.ROTATE_TILE || e === Mesh.ROTATE_ROW) && (W[1] = [1 - N, 1 - L, 1 - k, 1 - L, 1 - k, 1 - U, 1 - N, 1 - U]),
            (e === Mesh.FLIP_TILE || e === Mesh.FLIP_ROW) && (W[1] = [1 - N, L, 1 - k, L, 1 - k, U, 1 - N, U]),
            (e === Mesh.FLIP_N_ROTATE_TILE || e === Mesh.FLIP_N_ROTATE_ROW) && (W[1] = [N, 1 - L, k, 1 - L, k, 1 - U, N, 1 - U]);
            for (var x = 0; x < c; x++)
                T.push(y - l + _, -d + x * r + g, 0),
                T.push(y + _, -d + x * r + g, 0),
                T.push(y + _, -d + (x + 1) * r + g, 0),
                T.push(y - l + _, -d + (x + 1) * r + g, 0),
                R.push(M, M + 1, M + 3, M + 1, M + 2, M + 3),
                M += 4,
                e === Mesh.FLIP_TILE || e === Mesh.ROTATE_TILE || e === Mesh.FLIP_N_ROTATE_TILE ? S = S.concat(W[(x + s) % 2]) : e === Mesh.FLIP_ROW || e === Mesh.ROTATE_ROW || e === Mesh.FLIP_N_ROTATE_ROW ? S = S.concat(W[x % 2]) : S = S.concat(W[0]),
                P.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
                C.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1)
        }
    }
    var j = i.sideOrientation === 0 ? 0 : i.sideOrientation || VertexData.DEFAULTSIDE;
    VertexData._ComputeSides(j, T, R, C, S, i.frontUVs, i.backUVs);
    var B = new VertexData;
    B.indices = R,
    B.positions = T,
    B.normals = C,
    B.uvs = S;
    var X = j === VertexData.DOUBLESIDE ? P.concat(P) : P;
    return B.colors = X,
    B
}
function CreateTiledPlane(i, e, t) {
    t === void 0 && (t = null);
    var r = new Mesh(i,t);
    e.sideOrientation = Mesh._GetDefaultSideOrientation(e.sideOrientation),
    r._originalBuilderSideOrientation = e.sideOrientation;
    var n = CreateTiledPlaneVertexData(e);
    return n.applyToMesh(r, e.updatable),
    r
}
VertexData.CreateTiledPlane = CreateTiledPlaneVertexData;
function CreateTiledBoxVertexData(i) {
    for (var e = 6, t = i.faceUV || new Array(6), r = i.faceColors, n = i.pattern || Mesh.NO_FLIP, o = i.width || i.size || 1, a = i.height || i.size || 1, s = i.depth || i.size || 1, l = i.tileWidth || i.tileSize || 1, u = i.tileHeight || i.tileSize || 1, c = i.alignHorizontal || 0, h = i.alignVertical || 0, f = i.sideOrientation === 0 ? 0 : i.sideOrientation || VertexData.DEFAULTSIDE, d = 0; d < e; d++)
        t[d] === void 0 && (t[d] = new Vector4(0,0,1,1)),
        r && r[d] === void 0 && (r[d] = new Color4(1,1,1,1));
    for (var _ = o / 2, g = a / 2, m = s / 2, v = [], d = 0; d < 2; d++)
        v[d] = CreateTiledPlaneVertexData({
            pattern: n,
            tileWidth: l,
            tileHeight: u,
            width: o,
            height: a,
            alignVertical: h,
            alignHorizontal: c,
            sideOrientation: f
        });
    for (var d = 2; d < 4; d++)
        v[d] = CreateTiledPlaneVertexData({
            pattern: n,
            tileWidth: l,
            tileHeight: u,
            width: s,
            height: a,
            alignVertical: h,
            alignHorizontal: c,
            sideOrientation: f
        });
    var y = h;
    h === Mesh.BOTTOM ? y = Mesh.TOP : h === Mesh.TOP && (y = Mesh.BOTTOM);
    for (var d = 4; d < 6; d++)
        v[d] = CreateTiledPlaneVertexData({
            pattern: n,
            tileWidth: l,
            tileHeight: u,
            width: o,
            height: s,
            alignVertical: y,
            alignHorizontal: c,
            sideOrientation: f
        });
    for (var b = [], T = [], C = [], A = [], S = [], P = [], R = [], M = [], x = 0, I = 0, w = 0, d = 0; d < e; d++) {
        var x = v[d].positions.length;
        P[d] = [],
        R[d] = [];
        for (var O = 0; O < x / 3; O++)
            P[d].push(new Vector3(v[d].positions[3 * O],v[d].positions[3 * O + 1],v[d].positions[3 * O + 2])),
            R[d].push(new Vector3(v[d].normals[3 * O],v[d].normals[3 * O + 1],v[d].normals[3 * O + 2]));
        I = v[d].uvs.length,
        M[d] = [];
        for (var D = 0; D < I; D += 2)
            M[d][D] = t[d].x + (t[d].z - t[d].x) * v[d].uvs[D],
            M[d][D + 1] = t[d].y + (t[d].w - t[d].y) * v[d].uvs[D + 1];
        if (C = C.concat(M[d]),
        A = A.concat(v[d].indices.map(function($) {
            return $ + w
        })),
        w += P[d].length,
        r)
            for (var F = 0; F < 4; F++)
                S.push(r[d].r, r[d].g, r[d].b, r[d].a)
    }
    var V = new Vector3(0,0,m)
      , N = Matrix.RotationY(Math.PI);
    b = P[0].map(function(B) {
        return Vector3.TransformNormal(B, N).add(V)
    }).map(function(B) {
        return [B.x, B.y, B.z]
    }).reduce(function(B, X) {
        return B.concat(X)
    }, []),
    T = R[0].map(function(B) {
        return Vector3.TransformNormal(B, N)
    }).map(function(B) {
        return [B.x, B.y, B.z]
    }).reduce(function(B, X) {
        return B.concat(X)
    }, []),
    b = b.concat(P[1].map(function(B) {
        return B.subtract(V)
    }).map(function(B) {
        return [B.x, B.y, B.z]
    }).reduce(function(B, X) {
        return B.concat(X)
    }, [])),
    T = T.concat(R[1].map(function(B) {
        return [B.x, B.y, B.z]
    }).reduce(function(B, X) {
        return B.concat(X)
    }, []));
    var L = new Vector3(_,0,0)
      , k = Matrix.RotationY(-Math.PI / 2);
    b = b.concat(P[2].map(function(B) {
        return Vector3.TransformNormal(B, k).add(L)
    }).map(function(B) {
        return [B.x, B.y, B.z]
    }).reduce(function(B, X) {
        return B.concat(X)
    }, [])),
    T = T.concat(R[2].map(function(B) {
        return Vector3.TransformNormal(B, k)
    }).map(function(B) {
        return [B.x, B.y, B.z]
    }).reduce(function(B, X) {
        return B.concat(X)
    }, []));
    var U = Matrix.RotationY(Math.PI / 2);
    b = b.concat(P[3].map(function(B) {
        return Vector3.TransformNormal(B, U).subtract(L)
    }).map(function(B) {
        return [B.x, B.y, B.z]
    }).reduce(function(B, X) {
        return B.concat(X)
    }, [])),
    T = T.concat(R[3].map(function(B) {
        return Vector3.TransformNormal(B, U)
    }).map(function(B) {
        return [B.x, B.y, B.z]
    }).reduce(function(B, X) {
        return B.concat(X)
    }, []));
    var z = new Vector3(0,g,0)
      , H = Matrix.RotationX(Math.PI / 2);
    b = b.concat(P[4].map(function(B) {
        return Vector3.TransformNormal(B, H).add(z)
    }).map(function(B) {
        return [B.x, B.y, B.z]
    }).reduce(function(B, X) {
        return B.concat(X)
    }, [])),
    T = T.concat(R[4].map(function(B) {
        return Vector3.TransformNormal(B, H)
    }).map(function(B) {
        return [B.x, B.y, B.z]
    }).reduce(function(B, X) {
        return B.concat(X)
    }, []));
    var G = Matrix.RotationX(-Math.PI / 2);
    b = b.concat(P[5].map(function(B) {
        return Vector3.TransformNormal(B, G).subtract(z)
    }).map(function(B) {
        return [B.x, B.y, B.z]
    }).reduce(function(B, X) {
        return B.concat(X)
    }, [])),
    T = T.concat(R[5].map(function(B) {
        return Vector3.TransformNormal(B, G)
    }).map(function(B) {
        return [B.x, B.y, B.z]
    }).reduce(function(B, X) {
        return B.concat(X)
    }, [])),
    VertexData._ComputeSides(f, b, A, T, C);
    var W = new VertexData;
    if (W.indices = A,
    W.positions = b,
    W.normals = T,
    W.uvs = C,
    r) {
        var j = f === VertexData.DOUBLESIDE ? S.concat(S) : S;
        W.colors = j
    }
    return W
}
function CreateTiledBox(i, e, t) {
    t === void 0 && (t = null);
    var r = new Mesh(i,t);
    e.sideOrientation = Mesh._GetDefaultSideOrientation(e.sideOrientation),
    r._originalBuilderSideOrientation = e.sideOrientation;
    var n = CreateTiledBoxVertexData(e);
    return n.applyToMesh(r, e.updatable),
    r
}
VertexData.CreateTiledBox = CreateTiledBoxVertexData;
function CreateSphereVertexData(i) {
    for (var e = i.segments || 32, t = i.diameterX || i.diameter || 1, r = i.diameterY || i.diameter || 1, n = i.diameterZ || i.diameter || 1, o = i.arc && (i.arc <= 0 || i.arc > 1) ? 1 : i.arc || 1, a = i.slice && i.slice <= 0 ? 1 : i.slice || 1, s = i.sideOrientation === 0 ? 0 : i.sideOrientation || VertexData.DEFAULTSIDE, l = !!i.dedupTopBottomIndices, u = new Vector3(t / 2,r / 2,n / 2), c = 2 + e, h = 2 * c, f = [], d = [], _ = [], g = [], m = 0; m <= c; m++) {
        for (var v = m / c, y = v * Math.PI * a, b = 0; b <= h; b++) {
            var T = b / h
              , C = T * Math.PI * 2 * o
              , A = Matrix.RotationZ(-y)
              , S = Matrix.RotationY(C)
              , P = Vector3.TransformCoordinates(Vector3.Up(), A)
              , R = Vector3.TransformCoordinates(P, S)
              , M = R.multiply(u)
              , x = R.divide(u).normalize();
            d.push(M.x, M.y, M.z),
            _.push(x.x, x.y, x.z),
            g.push(T, v)
        }
        if (m > 0)
            for (var I = d.length / 3, w = I - 2 * (h + 1); w + h + 2 < I; w++)
                l ? (m > 1 && (f.push(w),
                f.push(w + 1),
                f.push(w + h + 1)),
                (m < c || a < 1) && (f.push(w + h + 1),
                f.push(w + 1),
                f.push(w + h + 2))) : (f.push(w),
                f.push(w + 1),
                f.push(w + h + 1),
                f.push(w + h + 1),
                f.push(w + 1),
                f.push(w + h + 2))
    }
    VertexData._ComputeSides(s, d, f, _, g, i.frontUVs, i.backUVs);
    var O = new VertexData;
    return O.indices = f,
    O.positions = d,
    O.normals = _,
    O.uvs = g,
    O
}
function CreateSphere(i, e, t) {
    e === void 0 && (e = {}),
    t === void 0 && (t = null);
    var r = new Mesh(i,t);
    e.sideOrientation = Mesh._GetDefaultSideOrientation(e.sideOrientation),
    r._originalBuilderSideOrientation = e.sideOrientation;
    var n = CreateSphereVertexData(e);
    return n.applyToMesh(r, e.updatable),
    r
}
VertexData.CreateSphere = CreateSphereVertexData;
Mesh.CreateSphere = function(i, e, t, r, n, o) {
    var a = {
        segments: e,
        diameterX: t,
        diameterY: t,
        diameterZ: t,
        sideOrientation: o,
        updatable: n
    };
    return CreateSphere(i, a, r)
}
;
function CreateCylinderVertexData(i) {
    var e = i.height || 2
      , t = i.diameterTop === 0 ? 0 : i.diameterTop || i.diameter || 1
      , r = i.diameterBottom === 0 ? 0 : i.diameterBottom || i.diameter || 1;
    t = t || 1e-5,
    r = r || 1e-5;
    var n = i.tessellation || 24, o = i.subdivisions || 1, a = !!i.hasRings, s = !!i.enclose, l = i.cap === 0 ? 0 : i.cap || Mesh.CAP_ALL, u = i.arc && (i.arc <= 0 || i.arc > 1) ? 1 : i.arc || 1, c = i.sideOrientation === 0 ? 0 : i.sideOrientation || VertexData.DEFAULTSIDE, h = i.faceUV || new Array(3), f = i.faceColors, d = u !== 1 && s ? 2 : 0, _ = a ? o : 1, g = 2 + (1 + d) * _, m;
    for (m = 0; m < g; m++)
        f && f[m] === void 0 && (f[m] = new Color4(1,1,1,1));
    for (m = 0; m < g; m++)
        h && h[m] === void 0 && (h[m] = new Vector4(0,0,1,1));
    var v = new Array, y = new Array, b = new Array, T = new Array, C = new Array, A = Math.PI * 2 * u / n, S, P, R, M = (r - t) / 2 / e, x = Vector3.Zero(), I = Vector3.Zero(), w = Vector3.Zero(), O = Vector3.Zero(), D = Vector3.Zero(), F = Axis.Y, V, N, L, k = 1, G = 1, U = 0, z = 0;
    for (V = 0; V <= o; V++)
        for (P = V / o,
        R = (P * (t - r) + r) / 2,
        k = a && V !== 0 && V !== o ? 2 : 1,
        L = 0; L < k; L++) {
            for (a && (G += L),
            s && (G += 2 * L),
            N = 0; N <= n; N++)
                S = N * A,
                x.x = Math.cos(-S) * R,
                x.y = -e / 2 + P * e,
                x.z = Math.sin(-S) * R,
                t === 0 && V === o ? (I.x = b[b.length - (n + 1) * 3],
                I.y = b[b.length - (n + 1) * 3 + 1],
                I.z = b[b.length - (n + 1) * 3 + 2]) : (I.x = x.x,
                I.z = x.z,
                I.y = Math.sqrt(I.x * I.x + I.z * I.z) * M,
                I.normalize()),
                N === 0 && (w.copyFrom(x),
                O.copyFrom(I)),
                y.push(x.x, x.y, x.z),
                b.push(I.x, I.y, I.z),
                a ? z = U !== G ? h[G].y : h[G].w : z = h[G].y + (h[G].w - h[G].y) * P,
                T.push(h[G].x + (h[G].z - h[G].x) * N / n, z),
                f && C.push(f[G].r, f[G].g, f[G].b, f[G].a);
            u !== 1 && s && (y.push(x.x, x.y, x.z),
            y.push(0, x.y, 0),
            y.push(0, x.y, 0),
            y.push(w.x, w.y, w.z),
            Vector3.CrossToRef(F, I, D),
            D.normalize(),
            b.push(D.x, D.y, D.z, D.x, D.y, D.z),
            Vector3.CrossToRef(O, F, D),
            D.normalize(),
            b.push(D.x, D.y, D.z, D.x, D.y, D.z),
            a ? z = U !== G ? h[G + 1].y : h[G + 1].w : z = h[G + 1].y + (h[G + 1].w - h[G + 1].y) * P,
            T.push(h[G + 1].x, z),
            T.push(h[G + 1].z, z),
            a ? z = U !== G ? h[G + 2].y : h[G + 2].w : z = h[G + 2].y + (h[G + 2].w - h[G + 2].y) * P,
            T.push(h[G + 2].x, z),
            T.push(h[G + 2].z, z),
            f && (C.push(f[G + 1].r, f[G + 1].g, f[G + 1].b, f[G + 1].a),
            C.push(f[G + 1].r, f[G + 1].g, f[G + 1].b, f[G + 1].a),
            C.push(f[G + 2].r, f[G + 2].g, f[G + 2].b, f[G + 2].a),
            C.push(f[G + 2].r, f[G + 2].g, f[G + 2].b, f[G + 2].a))),
            U !== G && (U = G)
        }
    var H = u !== 1 && s ? n + 4 : n, G;
    for (V = 0,
    G = 0; G < o; G++) {
        var W = 0
          , j = 0
          , B = 0
          , X = 0;
        for (N = 0; N < n; N++)
            W = V * (H + 1) + N,
            j = (V + 1) * (H + 1) + N,
            B = V * (H + 1) + (N + 1),
            X = (V + 1) * (H + 1) + (N + 1),
            v.push(W, j, B),
            v.push(X, B, j);
        u !== 1 && s && (v.push(W + 2, j + 2, B + 2),
        v.push(X + 2, B + 2, j + 2),
        v.push(W + 4, j + 4, B + 4),
        v.push(X + 4, B + 4, j + 4)),
        V = a ? V + 2 : V + 1
    }
    var $ = function(K) {
        var Z = K ? t / 2 : r / 2;
        if (Z !== 0) {
            var q, J, Q, te = K ? h[g - 1] : h[0], re = null;
            f && (re = K ? f[g - 1] : f[0]);
            var ie = y.length / 3
              , ee = K ? e / 2 : -e / 2
              , ne = new Vector3(0,ee,0);
            y.push(ne.x, ne.y, ne.z),
            b.push(0, K ? 1 : -1, 0),
            T.push(te.x + (te.z - te.x) * .5, te.y + (te.w - te.y) * .5),
            re && C.push(re.r, re.g, re.b, re.a);
            var ce = new Vector2(.5,.5);
            for (Q = 0; Q <= n; Q++) {
                q = Math.PI * 2 * Q * u / n;
                var he = Math.cos(-q)
                  , fe = Math.sin(-q);
                J = new Vector3(he * Z,ee,fe * Z);
                var ue = new Vector2(he * ce.x + .5,fe * ce.y + .5);
                y.push(J.x, J.y, J.z),
                b.push(0, K ? 1 : -1, 0),
                T.push(te.x + (te.z - te.x) * ue.x, te.y + (te.w - te.y) * ue.y),
                re && C.push(re.r, re.g, re.b, re.a)
            }
            for (Q = 0; Q < n; Q++)
                K ? (v.push(ie),
                v.push(ie + (Q + 2)),
                v.push(ie + (Q + 1))) : (v.push(ie),
                v.push(ie + (Q + 1)),
                v.push(ie + (Q + 2)))
        }
    };
    (l === Mesh.CAP_START || l === Mesh.CAP_ALL) && $(!1),
    (l === Mesh.CAP_END || l === Mesh.CAP_ALL) && $(!0),
    VertexData._ComputeSides(c, y, v, b, T, i.frontUVs, i.backUVs);
    var Y = new VertexData;
    return Y.indices = v,
    Y.positions = y,
    Y.normals = b,
    Y.uvs = T,
    f && (Y.colors = C),
    Y
}
function CreateCylinder(i, e, t) {
    e === void 0 && (e = {});
    var r = new Mesh(i,t);
    e.sideOrientation = Mesh._GetDefaultSideOrientation(e.sideOrientation),
    r._originalBuilderSideOrientation = e.sideOrientation;
    var n = CreateCylinderVertexData(e);
    return n.applyToMesh(r, e.updatable),
    r
}
VertexData.CreateCylinder = CreateCylinderVertexData;
Mesh.CreateCylinder = function(i, e, t, r, n, o, a, s, l) {
    (a === void 0 || !(a instanceof Scene)) && (a !== void 0 && (l = s || Mesh.DEFAULTSIDE,
    s = a),
    a = o,
    o = 1);
    var u = {
        height: e,
        diameterTop: t,
        diameterBottom: r,
        tessellation: n,
        subdivisions: o,
        sideOrientation: l,
        updatable: s
    };
    return CreateCylinder(i, u, a)
}
;
function CreateTorusVertexData(i) {
    for (var e = [], t = [], r = [], n = [], o = i.diameter || 1, a = i.thickness || .5, s = i.tessellation || 16, l = i.sideOrientation === 0 ? 0 : i.sideOrientation || VertexData.DEFAULTSIDE, u = s + 1, c = 0; c <= s; c++)
        for (var h = c / s, f = c * Math.PI * 2 / s - Math.PI / 2, d = Matrix.Translation(o / 2, 0, 0).multiply(Matrix.RotationY(f)), _ = 0; _ <= s; _++) {
            var g = 1 - _ / s
              , m = _ * Math.PI * 2 / s + Math.PI
              , v = Math.cos(m)
              , y = Math.sin(m)
              , b = new Vector3(v,y,0)
              , T = b.scale(a / 2)
              , C = new Vector2(h,g);
            T = Vector3.TransformCoordinates(T, d),
            b = Vector3.TransformNormal(b, d),
            t.push(T.x, T.y, T.z),
            r.push(b.x, b.y, b.z),
            n.push(C.x, C.y);
            var A = (c + 1) % u
              , S = (_ + 1) % u;
            e.push(c * u + _),
            e.push(c * u + S),
            e.push(A * u + _),
            e.push(c * u + S),
            e.push(A * u + S),
            e.push(A * u + _)
        }
    VertexData._ComputeSides(l, t, e, r, n, i.frontUVs, i.backUVs);
    var P = new VertexData;
    return P.indices = e,
    P.positions = t,
    P.normals = r,
    P.uvs = n,
    P
}
function CreateTorus(i, e, t) {
    e === void 0 && (e = {});
    var r = new Mesh(i,t);
    e.sideOrientation = Mesh._GetDefaultSideOrientation(e.sideOrientation),
    r._originalBuilderSideOrientation = e.sideOrientation;
    var n = CreateTorusVertexData(e);
    return n.applyToMesh(r, e.updatable),
    r
}
VertexData.CreateTorus = CreateTorusVertexData;
Mesh.CreateTorus = function(i, e, t, r, n, o, a) {
    var s = {
        diameter: e,
        thickness: t,
        tessellation: r,
        sideOrientation: a,
        updatable: o
    };
    return CreateTorus(i, s, n)
}
;
function CreateTorusKnotVertexData(i) {
    var e = new Array, t = new Array, r = new Array, n = new Array, o = i.radius || 2, a = i.tube || .5, s = i.radialSegments || 32, l = i.tubularSegments || 32, u = i.p || 2, c = i.q || 3, h = i.sideOrientation === 0 ? 0 : i.sideOrientation || VertexData.DEFAULTSIDE, f = function(F) {
        var V = Math.cos(F)
          , N = Math.sin(F)
          , L = c / u * F
          , k = Math.cos(L)
          , U = o * (2 + k) * .5 * V
          , z = o * (2 + k) * N * .5
          , H = o * Math.sin(L) * .5;
        return new Vector3(U,z,H)
    }, d, _;
    for (d = 0; d <= s; d++) {
        var g = d % s
          , m = g / s * 2 * u * Math.PI
          , v = f(m)
          , y = f(m + .01)
          , b = y.subtract(v)
          , T = y.add(v)
          , C = Vector3.Cross(b, T);
        for (T = Vector3.Cross(C, b),
        C.normalize(),
        T.normalize(),
        _ = 0; _ < l; _++) {
            var A = _ % l
              , S = A / l * 2 * Math.PI
              , P = -a * Math.cos(S)
              , R = a * Math.sin(S);
            t.push(v.x + P * T.x + R * C.x),
            t.push(v.y + P * T.y + R * C.y),
            t.push(v.z + P * T.z + R * C.z),
            n.push(d / s),
            n.push(_ / l)
        }
    }
    for (d = 0; d < s; d++)
        for (_ = 0; _ < l; _++) {
            var M = (_ + 1) % l
              , x = d * l + _
              , I = (d + 1) * l + _
              , w = (d + 1) * l + M
              , O = d * l + M;
            e.push(O),
            e.push(I),
            e.push(x),
            e.push(O),
            e.push(w),
            e.push(I)
        }
    VertexData.ComputeNormals(t, e, r),
    VertexData._ComputeSides(h, t, e, r, n, i.frontUVs, i.backUVs);
    var D = new VertexData;
    return D.indices = e,
    D.positions = t,
    D.normals = r,
    D.uvs = n,
    D
}
function CreateTorusKnot(i, e, t) {
    e === void 0 && (e = {});
    var r = new Mesh(i,t);
    e.sideOrientation = Mesh._GetDefaultSideOrientation(e.sideOrientation),
    r._originalBuilderSideOrientation = e.sideOrientation;
    var n = CreateTorusKnotVertexData(e);
    return n.applyToMesh(r, e.updatable),
    r
}
VertexData.CreateTorusKnot = CreateTorusKnotVertexData;
Mesh.CreateTorusKnot = function(i, e, t, r, n, o, a, s, l, u) {
    var c = {
        radius: e,
        tube: t,
        radialSegments: r,
        tubularSegments: n,
        p: o,
        q: a,
        sideOrientation: u,
        updatable: l
    };
    return CreateTorusKnot(i, c, s)
}
;
Mesh._instancedMeshFactory = function(i, e) {
    var t = new InstancedMesh(i,e);
    if (e.instancedBuffers) {
        t.instancedBuffers = {};
        for (var r in e.instancedBuffers)
            t.instancedBuffers[r] = e.instancedBuffers[r]
    }
    return t
}
;
var InstancedMesh = function(i) {
    __extends(e, i);
    function e(t, r) {
        var n = i.call(this, t, r.getScene()) || this;
        n._indexInSourceMeshInstanceArray = -1,
        n._distanceToCamera = 0,
        r.addInstance(n),
        n._sourceMesh = r,
        n._unIndexed = r._unIndexed,
        n.position.copyFrom(r.position),
        n.rotation.copyFrom(r.rotation),
        n.scaling.copyFrom(r.scaling),
        r.rotationQuaternion && (n.rotationQuaternion = r.rotationQuaternion.clone()),
        n.animations = Tools.Slice(r.animations);
        for (var o = 0, a = r.getAnimationRanges(); o < a.length; o++) {
            var s = a[o];
            s != null && n.createAnimationRange(s.name, s.from, s.to)
        }
        return n.infiniteDistance = r.infiniteDistance,
        n.setPivotMatrix(r.getPivotMatrix()),
        n.refreshBoundingInfo(),
        n._syncSubMeshes(),
        n
    }
    return e.prototype.getClassName = function() {
        return "InstancedMesh"
    }
    ,
    Object.defineProperty(e.prototype, "lightSources", {
        get: function() {
            return this._sourceMesh._lightSources
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._resyncLightSources = function() {}
    ,
    e.prototype._resyncLightSource = function(t) {}
    ,
    e.prototype._removeLightSource = function(t, r) {}
    ,
    Object.defineProperty(e.prototype, "receiveShadows", {
        get: function() {
            return this._sourceMesh.receiveShadows
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "material", {
        get: function() {
            return this._sourceMesh.material
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "visibility", {
        get: function() {
            return this._sourceMesh.visibility
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "skeleton", {
        get: function() {
            return this._sourceMesh.skeleton
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "renderingGroupId", {
        get: function() {
            return this._sourceMesh.renderingGroupId
        },
        set: function(t) {
            !this._sourceMesh || t === this._sourceMesh.renderingGroupId || Logger$2.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene")
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getTotalVertices = function() {
        return this._sourceMesh ? this._sourceMesh.getTotalVertices() : 0
    }
    ,
    e.prototype.getTotalIndices = function() {
        return this._sourceMesh.getTotalIndices()
    }
    ,
    Object.defineProperty(e.prototype, "sourceMesh", {
        get: function() {
            return this._sourceMesh
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.createInstance = function(t) {
        return this._sourceMesh.createInstance(t)
    }
    ,
    e.prototype.isReady = function(t) {
        return t === void 0 && (t = !1),
        this._sourceMesh.isReady(t, !0)
    }
    ,
    e.prototype.getVerticesData = function(t, r) {
        return this._sourceMesh.getVerticesData(t, r)
    }
    ,
    e.prototype.setVerticesData = function(t, r, n, o) {
        return this.sourceMesh && this.sourceMesh.setVerticesData(t, r, n, o),
        this.sourceMesh
    }
    ,
    e.prototype.updateVerticesData = function(t, r, n, o) {
        return this.sourceMesh && this.sourceMesh.updateVerticesData(t, r, n, o),
        this.sourceMesh
    }
    ,
    e.prototype.setIndices = function(t, r) {
        return r === void 0 && (r = null),
        this.sourceMesh && this.sourceMesh.setIndices(t, r),
        this.sourceMesh
    }
    ,
    e.prototype.isVerticesDataPresent = function(t) {
        return this._sourceMesh.isVerticesDataPresent(t)
    }
    ,
    e.prototype.getIndices = function() {
        return this._sourceMesh.getIndices()
    }
    ,
    Object.defineProperty(e.prototype, "_positions", {
        get: function() {
            return this._sourceMesh._positions
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.refreshBoundingInfo = function(t, r) {
        if (t === void 0 && (t = !1),
        r === void 0 && (r = !1),
        this.hasBoundingInfo && this.getBoundingInfo().isLocked)
            return this;
        var n = this._sourceMesh.geometry ? this._sourceMesh.geometry.boundingBias : null;
        return this._refreshBoundingInfo(this._sourceMesh._getPositionData(t, r), n),
        this
    }
    ,
    e.prototype._preActivate = function() {
        return this._currentLOD && this._currentLOD._preActivate(),
        this
    }
    ,
    e.prototype._activate = function(t, r) {
        if (this._sourceMesh.subMeshes || Logger$2.Warn("Instances should only be created for meshes with geometry."),
        this._currentLOD) {
            var n = this._currentLOD._getWorldMatrixDeterminant() > 0 != this._getWorldMatrixDeterminant() > 0;
            if (n)
                return this._internalAbstractMeshDataInfo._actAsRegularMesh = !0,
                !0;
            if (this._internalAbstractMeshDataInfo._actAsRegularMesh = !1,
            this._currentLOD._registerInstanceForRenderId(this, t),
            r) {
                if (!this._currentLOD._internalAbstractMeshDataInfo._isActiveIntermediate)
                    return this._currentLOD._internalAbstractMeshDataInfo._onlyForInstancesIntermediate = !0,
                    !0
            } else if (!this._currentLOD._internalAbstractMeshDataInfo._isActive)
                return this._currentLOD._internalAbstractMeshDataInfo._onlyForInstances = !0,
                !0
        }
        return !1
    }
    ,
    e.prototype._postActivate = function() {
        this._sourceMesh.edgesShareWithInstances && this._sourceMesh._edgesRenderer && this._sourceMesh._edgesRenderer.isEnabled && this._sourceMesh._renderingGroup ? (this._sourceMesh._renderingGroup._edgesRenderers.pushNoDuplicate(this._sourceMesh._edgesRenderer),
        this._sourceMesh._edgesRenderer.customInstances.push(this.getWorldMatrix())) : this._edgesRenderer && this._edgesRenderer.isEnabled && this._sourceMesh._renderingGroup && this._sourceMesh._renderingGroup._edgesRenderers.push(this._edgesRenderer)
    }
    ,
    e.prototype.getWorldMatrix = function() {
        if (this._currentLOD && this._currentLOD.billboardMode !== TransformNode.BILLBOARDMODE_NONE && this._currentLOD._masterMesh !== this) {
            this._billboardWorldMatrix || (this._billboardWorldMatrix = new Matrix);
            var t = this._currentLOD._masterMesh;
            return this._currentLOD._masterMesh = this,
            TmpVectors.Vector3[7].copyFrom(this._currentLOD.position),
            this._currentLOD.position.set(0, 0, 0),
            this._billboardWorldMatrix.copyFrom(this._currentLOD.computeWorldMatrix(!0)),
            this._currentLOD.position.copyFrom(TmpVectors.Vector3[7]),
            this._currentLOD._masterMesh = t,
            this._billboardWorldMatrix
        }
        return i.prototype.getWorldMatrix.call(this)
    }
    ,
    Object.defineProperty(e.prototype, "isAnInstance", {
        get: function() {
            return !0
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getLOD = function(t) {
        if (!t)
            return this;
        var r = this.getBoundingInfo();
        return this._currentLOD = this.sourceMesh.getLOD(t, r.boundingSphere),
        this._currentLOD === this.sourceMesh ? this.sourceMesh : this._currentLOD
    }
    ,
    e.prototype._preActivateForIntermediateRendering = function(t) {
        return this.sourceMesh._preActivateForIntermediateRendering(t)
    }
    ,
    e.prototype._syncSubMeshes = function() {
        if (this.releaseSubMeshes(),
        this._sourceMesh.subMeshes)
            for (var t = 0; t < this._sourceMesh.subMeshes.length; t++)
                this._sourceMesh.subMeshes[t].clone(this, this._sourceMesh);
        return this
    }
    ,
    e.prototype._generatePointsArray = function() {
        return this._sourceMesh._generatePointsArray()
    }
    ,
    e.prototype._updateBoundingInfo = function() {
        var t = this;
        return this.hasBoundingInfo ? this.getBoundingInfo().update(t.worldMatrixFromCache) : this.buildBoundingInfo(this.absolutePosition, this.absolutePosition, t.worldMatrixFromCache),
        this._updateSubMeshesBoundingInfo(t.worldMatrixFromCache),
        this
    }
    ,
    e.prototype.clone = function(t, r, n) {
        r === void 0 && (r = null);
        var o = this._sourceMesh.createInstance(t);
        if (DeepCopier.DeepCopy(this, o, ["name", "subMeshes", "uniqueId", "parent", "lightSources", "receiveShadows", "material", "visibility", "skeleton", "sourceMesh", "isAnInstance", "facetNb", "isFacetDataEnabled", "isBlocked", "useBones", "hasInstances", "collider", "edgesRenderer", "forward", "up", "right", "absolutePosition", "absoluteScaling", "absoluteRotationQuaternion", "isWorldMatrixFrozen", "nonUniformScaling", "behaviors", "worldMatrixFromCache", "hasThinInstances"], []),
        this.refreshBoundingInfo(),
        r && (o.parent = r),
        !n)
            for (var a = 0; a < this.getScene().meshes.length; a++) {
                var s = this.getScene().meshes[a];
                s.parent === this && s.clone(s.name, o)
            }
        return o.computeWorldMatrix(!0),
        this.onClonedObservable.notifyObservers(o),
        o
    }
    ,
    e.prototype.dispose = function(t, r) {
        r === void 0 && (r = !1),
        this._sourceMesh.removeInstance(this),
        i.prototype.dispose.call(this, t, r)
    }
    ,
    e
}(AbstractMesh);
Mesh.prototype.edgesShareWithInstances = !1;
Mesh.prototype.registerInstancedBuffer = function(i, e) {
    var t, r;
    if ((r = (t = this._userInstancedBuffersStorage) === null || t === void 0 ? void 0 : t.vertexBuffers[i]) === null || r === void 0 || r.dispose(),
    !this.instancedBuffers) {
        this.instancedBuffers = {};
        for (var n = 0, o = this.instances; n < o.length; n++) {
            var a = o[n];
            a.instancedBuffers = {}
        }
        this._userInstancedBuffersStorage = {
            data: {},
            vertexBuffers: {},
            strides: {},
            sizes: {},
            vertexArrayObjects: this.getEngine().getCaps().vertexArrayObject ? {} : void 0
        }
    }
    this.instancedBuffers[i] = null,
    this._userInstancedBuffersStorage.strides[i] = e,
    this._userInstancedBuffersStorage.sizes[i] = e * 32,
    this._userInstancedBuffersStorage.data[i] = new Float32Array(this._userInstancedBuffersStorage.sizes[i]),
    this._userInstancedBuffersStorage.vertexBuffers[i] = new VertexBuffer(this.getEngine(),this._userInstancedBuffersStorage.data[i],i,!0,!1,e,!0);
    for (var s = 0, l = this.instances; s < l.length; s++) {
        var a = l[s];
        a.instancedBuffers[i] = null
    }
    this._invalidateInstanceVertexArrayObject()
}
;
Mesh.prototype._processInstancedBuffers = function(i, e) {
    var t = i.length;
    for (var r in this.instancedBuffers) {
        for (var n = this._userInstancedBuffersStorage.sizes[r], o = this._userInstancedBuffersStorage.strides[r], a = (t + 1) * o; n < a; )
            n *= 2;
        this._userInstancedBuffersStorage.data[r].length != n && (this._userInstancedBuffersStorage.data[r] = new Float32Array(n),
        this._userInstancedBuffersStorage.sizes[r] = n,
        this._userInstancedBuffersStorage.vertexBuffers[r] && (this._userInstancedBuffersStorage.vertexBuffers[r].dispose(),
        this._userInstancedBuffersStorage.vertexBuffers[r] = null));
        var s = this._userInstancedBuffersStorage.data[r]
          , l = 0;
        if (e) {
            var u = this.instancedBuffers[r];
            u.toArray ? u.toArray(s, l) : u.copyToArray ? u.copyToArray(s, l) : s[l] = u,
            l += o
        }
        for (var c = 0; c < t; c++) {
            var h = i[c]
              , u = h.instancedBuffers[r];
            u.toArray ? u.toArray(s, l) : u.copyToArray ? u.copyToArray(s, l) : s[l] = u,
            l += o
        }
        this._userInstancedBuffersStorage.vertexBuffers[r] ? this._userInstancedBuffersStorage.vertexBuffers[r].updateDirectly(s, 0) : (this._userInstancedBuffersStorage.vertexBuffers[r] = new VertexBuffer(this.getEngine(),this._userInstancedBuffersStorage.data[r],r,!0,!1,o,!0),
        this._invalidateInstanceVertexArrayObject())
    }
}
;
Mesh.prototype._invalidateInstanceVertexArrayObject = function() {
    if (!(!this._userInstancedBuffersStorage || this._userInstancedBuffersStorage.vertexArrayObjects === void 0)) {
        for (var i in this._userInstancedBuffersStorage.vertexArrayObjects)
            this.getEngine().releaseVertexArrayObject(this._userInstancedBuffersStorage.vertexArrayObjects[i]);
        this._userInstancedBuffersStorage.vertexArrayObjects = {}
    }
}
;
Mesh.prototype._disposeInstanceSpecificData = function() {
    for (this._instanceDataStorage.instancesBuffer && (this._instanceDataStorage.instancesBuffer.dispose(),
    this._instanceDataStorage.instancesBuffer = null); this.instances.length; )
        this.instances[0].dispose();
    for (var i in this.instancedBuffers)
        this._userInstancedBuffersStorage.vertexBuffers[i] && this._userInstancedBuffersStorage.vertexBuffers[i].dispose();
    this._invalidateInstanceVertexArrayObject(),
    this.instancedBuffers = {}
}
;
var name$1J = "colorPixelShader"
  , shader$1J = `#ifdef VERTEXCOLOR
varying vec4 vColor;
#else
uniform vec4 color;
#endif
#include<clipPlaneFragmentDeclaration>
void main(void) {
#include<clipPlaneFragment>
#ifdef VERTEXCOLOR
gl_FragColor=vColor;
#else
gl_FragColor=color;
#endif
}`;
ShaderStore.ShadersStore[name$1J] = shader$1J;
var name$1I = "colorVertexShader"
  , shader$1I = `
attribute vec3 position;
#ifdef VERTEXCOLOR
attribute vec4 color;
#endif
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<clipPlaneVertexDeclaration>

#include<instancesDeclaration>
uniform mat4 viewProjection;
#ifdef MULTIVIEW
uniform mat4 viewProjectionR;
#endif

#ifdef VERTEXCOLOR
varying vec4 vColor;
#endif
void main(void) {
#include<instancesVertex>
#include<bonesVertex>
#include<bakedVertexAnimation>
vec4 worldPos=finalWorld*vec4(position,1.0);
#ifdef MULTIVIEW
if (gl_ViewID_OVR == 0u) {
gl_Position=viewProjection*worldPos;
} else {
gl_Position=viewProjectionR*worldPos;
}
#else
gl_Position=viewProjection*worldPos;
#endif
#include<clipPlaneVertex>
#ifdef VERTEXCOLOR

vColor=color;
#endif
}`;
ShaderStore.ShadersStore[name$1I] = shader$1I;
Mesh._LinesMeshParser = function(i, e) {
    return LinesMesh.Parse(i, e)
}
;
var LinesMesh = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a, s, l, u) {
        r === void 0 && (r = null),
        n === void 0 && (n = null),
        o === void 0 && (o = null);
        var c = i.call(this, t, r, n, o, a) || this;
        c.useVertexColor = s,
        c.useVertexAlpha = l,
        c.color = new Color3(1,1,1),
        c.alpha = 1,
        o && (c.color = o.color.clone(),
        c.alpha = o.alpha,
        c.useVertexColor = o.useVertexColor,
        c.useVertexAlpha = o.useVertexAlpha),
        c.intersectionThreshold = .1;
        var h = []
          , f = {
            attributes: [VertexBuffer.PositionKind],
            uniforms: ["vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "vClipPlane5", "vClipPlane6", "world", "viewProjection"],
            needAlphaBlending: !0,
            defines: h,
            useClipPlane: null
        };
        return l === !1 && (f.needAlphaBlending = !1),
        s ? (f.defines.push("#define VERTEXCOLOR"),
        f.attributes.push(VertexBuffer.ColorKind)) : (f.uniforms.push("color"),
        c.color4 = new Color4),
        u ? c.material = u : c._lineMaterial = new ShaderMaterial("colorShader",c.getScene(),"color",f,!1),
        c
    }
    return e.prototype._isShaderMaterial = function(t) {
        return t.getClassName() === "ShaderMaterial"
    }
    ,
    e.prototype.isReady = function() {
        return this._lineMaterial.isReady(this, !!this._userInstancedBuffersStorage) ? i.prototype.isReady.call(this) : !1
    }
    ,
    e.prototype.getClassName = function() {
        return "LinesMesh"
    }
    ,
    Object.defineProperty(e.prototype, "material", {
        get: function() {
            return this._lineMaterial
        },
        set: function(t) {
            this._lineMaterial = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "checkCollisions", {
        get: function() {
            return !1
        },
        set: function(t) {},
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._bind = function(t, r, n) {
        if (!this._geometry)
            return this;
        var o = this._lineMaterial.getEffect()
          , a = this.isUnIndexed ? null : this._geometry.getIndexBuffer();
        if (this._userInstancedBuffersStorage ? this._geometry._bind(o, a, this._userInstancedBuffersStorage.vertexBuffers, this._userInstancedBuffersStorage.vertexArrayObjects) : this._geometry._bind(o, a),
        !this.useVertexColor && this._isShaderMaterial(this._lineMaterial)) {
            var s = this.color
              , l = s.r
              , u = s.g
              , c = s.b;
            this.color4.set(l, u, c, this.alpha),
            this._lineMaterial.setColor4("color", this.color4)
        }
        return this
    }
    ,
    e.prototype._draw = function(t, r, n) {
        if (!this._geometry || !this._geometry.getVertexBuffers() || !this._unIndexed && !this._geometry.getIndexBuffer())
            return this;
        var o = this.getScene().getEngine();
        return this._unIndexed ? o.drawArraysType(Material.LineListDrawMode, t.verticesStart, t.verticesCount, n) : o.drawElementsType(Material.LineListDrawMode, t.indexStart, t.indexCount, n),
        this
    }
    ,
    e.prototype.dispose = function(t) {
        this._lineMaterial.dispose(!1, !1, !0),
        i.prototype.dispose.call(this, t)
    }
    ,
    e.prototype.clone = function(t, r, n) {
        return r === void 0 && (r = null),
        new e(t,this.getScene(),r,this,n)
    }
    ,
    e.prototype.createInstance = function(t) {
        var r = new InstancedLinesMesh(t,this);
        if (this.instancedBuffers) {
            r.instancedBuffers = {};
            for (var n in this.instancedBuffers)
                r.instancedBuffers[n] = this.instancedBuffers[n]
        }
        return r
    }
    ,
    e.prototype.serialize = function(t) {
        i.prototype.serialize.call(this, t),
        t.color = this.color.asArray(),
        t.alpha = this.alpha
    }
    ,
    e.Parse = function(t, r) {
        var n = new e(t.name,r);
        return n.color = Color3.FromArray(t.color),
        n.alpha = t.alpha,
        n
    }
    ,
    e
}(Mesh)
  , InstancedLinesMesh = function(i) {
    __extends(e, i);
    function e(t, r) {
        var n = i.call(this, t, r) || this;
        return n.intersectionThreshold = r.intersectionThreshold,
        n
    }
    return e.prototype.getClassName = function() {
        return "InstancedLinesMesh"
    }
    ,
    e
}(InstancedMesh);
function CreateLineSystemVertexData(i) {
    for (var e = [], t = [], r = i.lines, n = i.colors, o = [], a = 0, s = 0; s < r.length; s++)
        for (var l = r[s], u = 0; u < l.length; u++) {
            if (t.push(l[u].x, l[u].y, l[u].z),
            n) {
                var c = n[s];
                o.push(c[u].r, c[u].g, c[u].b, c[u].a)
            }
            u > 0 && (e.push(a - 1),
            e.push(a)),
            a++
        }
    var h = new VertexData;
    return h.indices = e,
    h.positions = t,
    n && (h.colors = o),
    h
}
function CreateDashedLinesVertexData(i) {
    var e = i.dashSize || 3
      , t = i.gapSize || 1
      , r = i.dashNb || 200
      , n = i.points
      , o = new Array
      , a = new Array
      , s = Vector3.Zero()
      , l = 0
      , u = 0
      , c = 0
      , h = 0
      , f = 0
      , d = 0
      , _ = 0;
    for (_ = 0; _ < n.length - 1; _++)
        n[_ + 1].subtractToRef(n[_], s),
        l += s.length();
    for (c = l / r,
    h = e * c / (e + t),
    _ = 0; _ < n.length - 1; _++) {
        n[_ + 1].subtractToRef(n[_], s),
        u = Math.floor(s.length() / c),
        s.normalize();
        for (var g = 0; g < u; g++)
            f = c * g,
            o.push(n[_].x + f * s.x, n[_].y + f * s.y, n[_].z + f * s.z),
            o.push(n[_].x + (f + h) * s.x, n[_].y + (f + h) * s.y, n[_].z + (f + h) * s.z),
            a.push(d, d + 1),
            d += 2
    }
    var m = new VertexData;
    return m.positions = o,
    m.indices = a,
    m
}
function CreateLineSystem(i, e, t) {
    var r = e.instance
      , n = e.lines
      , o = e.colors;
    if (r) {
        var a = r.getVerticesData(VertexBuffer.PositionKind), s, l;
        o && (s = r.getVerticesData(VertexBuffer.ColorKind));
        for (var u = 0, c = 0, h = 0; h < n.length; h++)
            for (var f = n[h], d = 0; d < f.length; d++)
                a[u] = f[d].x,
                a[u + 1] = f[d].y,
                a[u + 2] = f[d].z,
                o && s && (l = o[h],
                s[c] = l[d].r,
                s[c + 1] = l[d].g,
                s[c + 2] = l[d].b,
                s[c + 3] = l[d].a,
                c += 4),
                u += 3;
        return r.updateVerticesData(VertexBuffer.PositionKind, a, !1, !1),
        o && s && r.updateVerticesData(VertexBuffer.ColorKind, s, !1, !1),
        r
    }
    var _ = !!o
      , g = new LinesMesh(i,t,null,void 0,void 0,_,e.useVertexAlpha,e.material)
      , m = CreateLineSystemVertexData(e);
    return m.applyToMesh(g, e.updatable),
    g
}
function CreateLines(i, e, t) {
    t === void 0 && (t = null);
    var r = e.colors ? [e.colors] : null
      , n = CreateLineSystem(i, {
        lines: [e.points],
        updatable: e.updatable,
        instance: e.instance,
        colors: r,
        useVertexAlpha: e.useVertexAlpha,
        material: e.material
    }, t);
    return n
}
function CreateDashedLines(i, e, t) {
    t === void 0 && (t = null);
    var r = e.points
      , n = e.instance
      , o = e.gapSize || 1
      , a = e.dashSize || 3;
    if (n) {
        var s = function(c) {
            var h = Vector3.Zero()
              , f = c.length / 6
              , d = 0
              , _ = 0
              , g = 0
              , m = 0
              , v = 0
              , y = 0
              , b = 0
              , T = 0;
            for (b = 0; b < r.length - 1; b++)
                r[b + 1].subtractToRef(r[b], h),
                d += h.length();
            g = d / f;
            var C = n._creationDataStorage.dashSize
              , A = n._creationDataStorage.gapSize;
            for (m = C * g / (C + A),
            b = 0; b < r.length - 1; b++)
                for (r[b + 1].subtractToRef(r[b], h),
                _ = Math.floor(h.length() / g),
                h.normalize(),
                T = 0; T < _ && y < c.length; )
                    v = g * T,
                    c[y] = r[b].x + v * h.x,
                    c[y + 1] = r[b].y + v * h.y,
                    c[y + 2] = r[b].z + v * h.z,
                    c[y + 3] = r[b].x + (v + m) * h.x,
                    c[y + 4] = r[b].y + (v + m) * h.y,
                    c[y + 5] = r[b].z + (v + m) * h.z,
                    y += 6,
                    T++;
            for (; y < c.length; )
                c[y] = r[b].x,
                c[y + 1] = r[b].y,
                c[y + 2] = r[b].z,
                y += 3
        };
        return n.updateMeshPositions(s, !1),
        n
    }
    var l = new LinesMesh(i,t,null,void 0,void 0,void 0,e.useVertexAlpha,e.material)
      , u = CreateDashedLinesVertexData(e);
    return u.applyToMesh(l, e.updatable),
    l._creationDataStorage = new _CreationDataStorage,
    l._creationDataStorage.dashSize = a,
    l._creationDataStorage.gapSize = o,
    l
}
VertexData.CreateLineSystem = CreateLineSystemVertexData;
VertexData.CreateDashedLines = CreateDashedLinesVertexData;
Mesh.CreateLines = function(i, e, t, r, n) {
    t === void 0 && (t = null),
    r === void 0 && (r = !1),
    n === void 0 && (n = null);
    var o = {
        points: e,
        updatable: r,
        instance: n
    };
    return CreateLines(i, o, t)
}
;
Mesh.CreateDashedLines = function(i, e, t, r, n, o, a, s) {
    o === void 0 && (o = null);
    var l = {
        points: e,
        dashSize: t,
        gapSize: r,
        dashNb: n,
        updatable: a,
        instance: s
    };
    return CreateDashedLines(i, l, o)
}
;
var IndexedVector2 = function(i) {
    __extends(e, i);
    function e(t, r) {
        var n = i.call(this, t.x, t.y) || this;
        return n.index = r,
        n
    }
    return e
}(Vector2)
  , PolygonPoints = function() {
    function i() {
        this.elements = new Array
    }
    return i.prototype.add = function(e) {
        var t = this
          , r = new Array;
        return e.forEach(function(n) {
            var o = new IndexedVector2(n,t.elements.length);
            r.push(o),
            t.elements.push(o)
        }),
        r
    }
    ,
    i.prototype.computeBounds = function() {
        var e = new Vector2(this.elements[0].x,this.elements[0].y)
          , t = new Vector2(this.elements[0].x,this.elements[0].y);
        return this.elements.forEach(function(r) {
            r.x < e.x ? e.x = r.x : r.x > t.x && (t.x = r.x),
            r.y < e.y ? e.y = r.y : r.y > t.y && (t.y = r.y)
        }),
        {
            min: e,
            max: t,
            width: t.x - e.x,
            height: t.y - e.y
        }
    }
    ,
    i
}()
  , PolygonMeshBuilder = function() {
    function i(e, t, r, n) {
        n === void 0 && (n = earcut),
        this._points = new PolygonPoints,
        this._outlinepoints = new PolygonPoints,
        this._holes = new Array,
        this._epoints = new Array,
        this._eholes = new Array,
        this.bjsEarcut = n,
        this._name = e,
        this._scene = r || Engine.LastCreatedScene;
        var o;
        t instanceof Path2 ? o = t.getPoints() : o = t,
        this._addToepoint(o),
        this._points.add(o),
        this._outlinepoints.add(o),
        typeof this.bjsEarcut == "undefined" && Logger$2.Warn("Earcut was not found, the polygon will not be built.")
    }
    return i.prototype._addToepoint = function(e) {
        for (var t = 0, r = e; t < r.length; t++) {
            var n = r[t];
            this._epoints.push(n.x, n.y)
        }
    }
    ,
    i.prototype.addHole = function(e) {
        this._points.add(e);
        var t = new PolygonPoints;
        return t.add(e),
        this._holes.push(t),
        this._eholes.push(this._epoints.length / 2),
        this._addToepoint(e),
        this
    }
    ,
    i.prototype.build = function(e, t, r) {
        e === void 0 && (e = !1),
        t === void 0 && (t = 0),
        r === void 0 && (r = 2);
        var n = new Mesh(this._name,this._scene)
          , o = this.buildVertexData(t, r);
        return n.setVerticesData(VertexBuffer.PositionKind, o.positions, e),
        n.setVerticesData(VertexBuffer.NormalKind, o.normals, e),
        n.setVerticesData(VertexBuffer.UVKind, o.uvs, e),
        n.setIndices(o.indices),
        n
    }
    ,
    i.prototype.buildVertexData = function(e, t) {
        var r = this;
        e === void 0 && (e = 0),
        t === void 0 && (t = 2);
        var n = new VertexData
          , o = new Array
          , a = new Array
          , s = new Array
          , l = this._points.computeBounds();
        this._points.elements.forEach(function(v) {
            o.push(0, 1, 0),
            a.push(v.x, 0, v.y),
            s.push((v.x - l.min.x) / l.width, (v.y - l.min.y) / l.height)
        });
        for (var u = new Array, c = this.bjsEarcut(this._epoints, this._eholes, 2), h = 0; h < c.length; h++)
            u.push(c[h]);
        if (e > 0) {
            var f = a.length / 3;
            this._points.elements.forEach(function(v) {
                o.push(0, -1, 0),
                a.push(v.x, -e, v.y),
                s.push(1 - (v.x - l.min.x) / l.width, 1 - (v.y - l.min.y) / l.height)
            });
            for (var d = u.length, h = 0; h < d; h += 3) {
                var _ = u[h + 0]
                  , g = u[h + 1]
                  , m = u[h + 2];
                u.push(m + f),
                u.push(g + f),
                u.push(_ + f)
            }
            this.addSide(a, o, s, u, l, this._outlinepoints, e, !1, t),
            this._holes.forEach(function(v) {
                r.addSide(a, o, s, u, l, v, e, !0, t)
            })
        }
        return n.indices = u,
        n.positions = a,
        n.normals = o,
        n.uvs = s,
        n
    }
    ,
    i.prototype.addSide = function(e, t, r, n, o, a, s, l, u) {
        for (var c = e.length / 3, h = 0, f = 0; f < a.elements.length; f++) {
            var d = a.elements[f]
              , _ = a.elements[(f + 1) % a.elements.length];
            e.push(d.x, 0, d.y),
            e.push(d.x, -s, d.y),
            e.push(_.x, 0, _.y),
            e.push(_.x, -s, _.y);
            var g = a.elements[(f + a.elements.length - 1) % a.elements.length]
              , m = a.elements[(f + 2) % a.elements.length]
              , v = new Vector3(-(_.y - d.y),0,_.x - d.x)
              , y = new Vector3(-(d.y - g.y),0,d.x - g.x)
              , b = new Vector3(-(m.y - _.y),0,m.x - _.x);
            l || (v = v.scale(-1),
            y = y.scale(-1),
            b = b.scale(-1));
            var T = v.normalizeToNew()
              , C = y.normalizeToNew()
              , A = b.normalizeToNew()
              , S = Vector3.Dot(C, T);
            S > u ? S < Epsilon - 1 ? C = new Vector3(d.x,0,d.y).subtract(new Vector3(_.x,0,_.y)).normalize() : C = y.add(v).normalize() : C = T;
            var P = Vector3.Dot(b, v);
            P > u ? P < Epsilon - 1 ? A = new Vector3(_.x,0,_.y).subtract(new Vector3(d.x,0,d.y)).normalize() : A = b.add(v).normalize() : A = T,
            r.push(h / o.width, 0),
            r.push(h / o.width, 1),
            h += v.length(),
            r.push(h / o.width, 0),
            r.push(h / o.width, 1),
            t.push(C.x, C.y, C.z),
            t.push(C.x, C.y, C.z),
            t.push(A.x, A.y, A.z),
            t.push(A.x, A.y, A.z),
            l ? (n.push(c),
            n.push(c + 2),
            n.push(c + 1),
            n.push(c + 1),
            n.push(c + 2),
            n.push(c + 3)) : (n.push(c),
            n.push(c + 1),
            n.push(c + 2),
            n.push(c + 1),
            n.push(c + 3),
            n.push(c + 2)),
            c += 4
        }
    }
    ,
    i
}();
function CreatePolygonVertexData(i, e, t, r, n, o, a) {
    for (var s = t || new Array(3), l = r, u = [], c = a || !1, h = 0; h < 3; h++)
        s[h] === void 0 && (s[h] = new Vector4(0,0,1,1)),
        l && l[h] === void 0 && (l[h] = new Color4(1,1,1,1));
    var f = i.getVerticesData(VertexBuffer.PositionKind)
      , d = i.getVerticesData(VertexBuffer.NormalKind)
      , _ = i.getVerticesData(VertexBuffer.UVKind)
      , g = i.getIndices()
      , m = f.length / 9
      , v = 0
      , y = 0
      , b = 0
      , T = 0
      , C = 0
      , A = [0];
    if (c)
        for (var S = m; S < f.length / 3; S += 4)
            y = f[3 * (S + 2)] - f[3 * S],
            b = f[3 * (S + 2) + 2] - f[3 * S + 2],
            T = Math.sqrt(y * y + b * b),
            C += T,
            A.push(C);
    for (var S = 0, P = 0, R = 0; R < d.length; R += 3)
        Math.abs(d[R + 1]) < .001 && (P = 1),
        Math.abs(d[R + 1] - 1) < .001 && (P = 0),
        Math.abs(d[R + 1] + 1) < .001 && (P = 2),
        S = R / 3,
        P === 1 ? (v = S - m,
        v % 4 < 1.5 ? c ? _[2 * S] = s[P].x + (s[P].z - s[P].x) * A[Math.floor(v / 4)] / C : _[2 * S] = s[P].x : c ? _[2 * S] = s[P].x + (s[P].z - s[P].x) * A[Math.floor(v / 4) + 1] / C : _[2 * S] = s[P].z,
        v % 2 === 0 ? _[2 * S + 1] = s[P].w : _[2 * S + 1] = s[P].y) : (_[2 * S] = (1 - _[2 * S]) * s[P].x + _[2 * S] * s[P].z,
        _[2 * S + 1] = (1 - _[2 * S + 1]) * s[P].y + _[2 * S + 1] * s[P].w),
        l && u.push(l[P].r, l[P].g, l[P].b, l[P].a);
    VertexData._ComputeSides(e, f, g, d, _, n, o);
    var M = new VertexData;
    if (M.indices = g,
    M.positions = f,
    M.normals = d,
    M.uvs = _,
    l) {
        var x = e === VertexData.DOUBLESIDE ? u.concat(u) : u;
        M.colors = x
    }
    return M
}
function CreatePolygon(i, e, t, r) {
    t === void 0 && (t = null),
    r === void 0 && (r = earcut),
    e.sideOrientation = Mesh._GetDefaultSideOrientation(e.sideOrientation);
    for (var n = e.shape, o = e.holes || [], a = e.depth || 0, s = e.smoothingThreshold || 2, l = [], u = [], c = 0; c < n.length; c++)
        l[c] = new Vector2(n[c].x,n[c].z);
    var h = 1e-8;
    l[0].equalsWithEpsilon(l[l.length - 1], h) && l.pop();
    for (var f = new PolygonMeshBuilder(i,l,t || EngineStore.LastCreatedScene,r), d = 0; d < o.length; d++) {
        u = [];
        for (var _ = 0; _ < o[d].length; _++)
            u.push(new Vector2(o[d][_].x,o[d][_].z));
        f.addHole(u)
    }
    var g = f.build(e.updatable, a, s);
    g._originalBuilderSideOrientation = e.sideOrientation;
    var m = CreatePolygonVertexData(g, e.sideOrientation, e.faceUV, e.faceColors, e.frontUVs, e.backUVs, e.wrap);
    return m.applyToMesh(g, e.updatable),
    g
}
function ExtrudePolygon(i, e, t, r) {
    return t === void 0 && (t = null),
    r === void 0 && (r = earcut),
    CreatePolygon(i, e, t, r)
}
VertexData.CreatePolygon = CreatePolygonVertexData;
Mesh.CreatePolygon = function(i, e, t, r, n, o, a) {
    a === void 0 && (a = earcut);
    var s = {
        shape: e,
        holes: r,
        updatable: n,
        sideOrientation: o
    };
    return CreatePolygon(i, s, t, a)
}
;
Mesh.ExtrudePolygon = function(i, e, t, r, n, o, a, s) {
    s === void 0 && (s = earcut);
    var l = {
        shape: e,
        holes: n,
        depth: t,
        updatable: o,
        sideOrientation: a
    };
    return ExtrudePolygon(i, l, r, s)
}
;
function ExtrudeShape(i, e, t) {
    t === void 0 && (t = null);
    var r = e.path
      , n = e.shape
      , o = e.scale || 1
      , a = e.rotation || 0
      , s = e.cap === 0 ? 0 : e.cap || Mesh.NO_CAP
      , l = e.updatable
      , u = Mesh._GetDefaultSideOrientation(e.sideOrientation)
      , c = e.instance || null
      , h = e.invertUV || !1;
    return _ExtrudeShapeGeneric(i, n, r, o, a, null, null, !1, !1, s, !1, t, !!l, u, c, h, e.frontUVs || null, e.backUVs || null)
}
function ExtrudeShapeCustom(i, e, t) {
    t === void 0 && (t = null);
    var r = e.path
      , n = e.shape
      , o = e.scaleFunction || function() {
        return 1
    }
      , a = e.rotationFunction || function() {
        return 0
    }
      , s = e.ribbonCloseArray || !1
      , l = e.ribbonClosePath || !1
      , u = e.cap === 0 ? 0 : e.cap || Mesh.NO_CAP
      , c = e.updatable
      , h = Mesh._GetDefaultSideOrientation(e.sideOrientation)
      , f = e.instance
      , d = e.invertUV || !1;
    return _ExtrudeShapeGeneric(i, n, r, null, null, o, a, s, l, u, !0, t, !!c, h, f || null, d, e.frontUVs || null, e.backUVs || null)
}
function _ExtrudeShapeGeneric(i, e, t, r, n, o, a, s, l, u, c, h, f, d, _, g, m, v) {
    var y = function(P, R, M, x, I, w, O, D, F, V) {
        for (var N = M.getTangents(), L = M.getNormals(), k = M.getBinormals(), U = M.getDistances(), z = 0, H = function() {
            return I !== null ? I : 1
        }, G = function() {
            return w !== null ? w : 0
        }, W = V && D ? D : G, j = V && O ? O : H, B = F === Mesh.NO_CAP || F === Mesh.CAP_END ? 0 : 2, X = TmpVectors.Matrix[0], $ = 0; $ < R.length; $++) {
            for (var Y = new Array, K = W($, U[$]), Z = j($, U[$]), q = 0; q < P.length; q++) {
                Matrix.RotationAxisToRef(N[$], z, X);
                var J = N[$].scale(P[q].z).add(L[$].scale(P[q].x)).add(k[$].scale(P[q].y))
                  , Q = Y[q] ? Y[q] : Vector3.Zero();
                Vector3.TransformCoordinatesToRef(J, X, Q),
                Q.scaleInPlace(Z).addInPlace(R[$]),
                Y[q] = Q
            }
            x[B] = Y,
            z += K,
            B++
        }
        var te = function(re) {
            var ie = Array(), ee = Vector3.Zero(), ne;
            for (ne = 0; ne < re.length; ne++)
                ee.addInPlace(re[ne]);
            for (ee.scaleInPlace(1 / re.length),
            ne = 0; ne < re.length; ne++)
                ie.push(ee);
            return ie
        };
        switch (F) {
        case Mesh.NO_CAP:
            break;
        case Mesh.CAP_START:
            x[0] = te(x[2]),
            x[1] = x[2];
            break;
        case Mesh.CAP_END:
            x[B] = x[B - 1],
            x[B + 1] = te(x[B - 1]);
            break;
        case Mesh.CAP_ALL:
            x[0] = te(x[2]),
            x[1] = x[2],
            x[B] = x[B - 1],
            x[B + 1] = te(x[B - 1]);
            break
        }
        return x
    }, b, T;
    if (_) {
        var C = _._creationDataStorage;
        return b = C.path3D.update(t),
        T = y(e, t, C.path3D, C.pathArray, r, n, o, a, C.cap, c),
        _ = CreateRibbon("", {
            pathArray: T,
            closeArray: !1,
            closePath: !1,
            offset: 0,
            updatable: !1,
            sideOrientation: 0,
            instance: _
        }, h || void 0),
        _
    }
    b = new Path3D(t);
    var A = new Array;
    u = u < 0 || u > 3 ? 0 : u,
    T = y(e, t, b, A, r, n, o, a, u, c);
    var S = CreateRibbon(i, {
        pathArray: T,
        closeArray: s,
        closePath: l,
        updatable: f,
        sideOrientation: d,
        invertUV: g,
        frontUVs: m || void 0,
        backUVs: v || void 0
    }, h);
    return S._creationDataStorage.pathArray = T,
    S._creationDataStorage.path3D = b,
    S._creationDataStorage.cap = u,
    S
}
Mesh.ExtrudeShape = function(i, e, t, r, n, o, a, s, l, u) {
    a === void 0 && (a = null);
    var c = {
        shape: e,
        path: t,
        scale: r,
        rotation: n,
        cap: o === 0 ? 0 : o || Mesh.NO_CAP,
        sideOrientation: l,
        instance: u,
        updatable: s
    };
    return ExtrudeShape(i, c, a)
}
;
Mesh.ExtrudeShapeCustom = function(i, e, t, r, n, o, a, s, l, u, c, h) {
    var f = {
        shape: e,
        path: t,
        scaleFunction: r,
        rotationFunction: n,
        ribbonCloseArray: o,
        ribbonClosePath: a,
        cap: s === 0 ? 0 : s || Mesh.NO_CAP,
        sideOrientation: c,
        instance: h,
        updatable: u
    };
    return ExtrudeShapeCustom(i, f, l)
}
;
function CreateLathe(i, e, t) {
    t === void 0 && (t = null);
    var r = e.arc ? e.arc <= 0 || e.arc > 1 ? 1 : e.arc : 1, n = e.closed === void 0 ? !0 : e.closed, o = e.shape, a = e.radius || 1, s = e.tessellation || 64, l = e.clip || 0, u = e.updatable, c = Mesh._GetDefaultSideOrientation(e.sideOrientation), h = e.cap || Mesh.NO_CAP, f = Math.PI * 2, d = new Array, _ = e.invertUV || !1, g = 0, m = 0, v = f / s * r, y, b = new Array;
    for (g = 0; g <= s - l; g++) {
        var b = [];
        for ((h == Mesh.CAP_START || h == Mesh.CAP_ALL) && (b.push(new Vector3(0,o[0].y,0)),
        b.push(new Vector3(Math.cos(g * v) * o[0].x * a,o[0].y,Math.sin(g * v) * o[0].x * a))),
        m = 0; m < o.length; m++)
            y = new Vector3(Math.cos(g * v) * o[m].x * a,o[m].y,Math.sin(g * v) * o[m].x * a),
            b.push(y);
        (h == Mesh.CAP_END || h == Mesh.CAP_ALL) && (b.push(new Vector3(Math.cos(g * v) * o[o.length - 1].x * a,o[o.length - 1].y,Math.sin(g * v) * o[o.length - 1].x * a)),
        b.push(new Vector3(0,o[o.length - 1].y,0))),
        d.push(b)
    }
    var T = CreateRibbon(i, {
        pathArray: d,
        closeArray: n,
        sideOrientation: c,
        updatable: u,
        invertUV: _,
        frontUVs: e.frontUVs,
        backUVs: e.backUVs
    }, t);
    return T
}
Mesh.CreateLathe = function(i, e, t, r, n, o, a) {
    var s = {
        shape: e,
        radius: t,
        tessellation: r,
        sideOrientation: a,
        updatable: o
    };
    return CreateLathe(i, s, n)
}
;
function CreatePlaneVertexData(i) {
    var e = []
      , t = []
      , r = []
      , n = []
      , o = i.width || i.size || 1
      , a = i.height || i.size || 1
      , s = i.sideOrientation === 0 ? 0 : i.sideOrientation || VertexData.DEFAULTSIDE
      , l = o / 2
      , u = a / 2;
    t.push(-l, -u, 0),
    r.push(0, 0, -1),
    n.push(0, 0),
    t.push(l, -u, 0),
    r.push(0, 0, -1),
    n.push(1, 0),
    t.push(l, u, 0),
    r.push(0, 0, -1),
    n.push(1, 1),
    t.push(-l, u, 0),
    r.push(0, 0, -1),
    n.push(0, 1),
    e.push(0),
    e.push(1),
    e.push(2),
    e.push(0),
    e.push(2),
    e.push(3),
    VertexData._ComputeSides(s, t, e, r, n, i.frontUVs, i.backUVs);
    var c = new VertexData;
    return c.indices = e,
    c.positions = t,
    c.normals = r,
    c.uvs = n,
    c
}
function CreatePlane(i, e, t) {
    e === void 0 && (e = {}),
    t === void 0 && (t = null);
    var r = new Mesh(i,t);
    e.sideOrientation = Mesh._GetDefaultSideOrientation(e.sideOrientation),
    r._originalBuilderSideOrientation = e.sideOrientation;
    var n = CreatePlaneVertexData(e);
    return n.applyToMesh(r, e.updatable),
    e.sourcePlane && (r.translate(e.sourcePlane.normal, -e.sourcePlane.d),
    r.setDirection(e.sourcePlane.normal.scale(-1))),
    r
}
VertexData.CreatePlane = CreatePlaneVertexData;
Mesh.CreatePlane = function(i, e, t, r, n) {
    var o = {
        size: e,
        width: e,
        height: e,
        sideOrientation: n,
        updatable: r
    };
    return CreatePlane(i, o, t)
}
;
Mesh._GroundMeshParser = function(i, e) {
    return GroundMesh.Parse(i, e)
}
;
var GroundMesh = function(i) {
    __extends(e, i);
    function e(t, r) {
        var n = i.call(this, t, r) || this;
        return n.generateOctree = !1,
        n
    }
    return e.prototype.getClassName = function() {
        return "GroundMesh"
    }
    ,
    Object.defineProperty(e.prototype, "subdivisions", {
        get: function() {
            return Math.min(this._subdivisionsX, this._subdivisionsY)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "subdivisionsX", {
        get: function() {
            return this._subdivisionsX
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "subdivisionsY", {
        get: function() {
            return this._subdivisionsY
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.optimize = function(t, r) {
        r === void 0 && (r = 32),
        this._subdivisionsX = t,
        this._subdivisionsY = t,
        this.subdivide(t);
        var n = this;
        n.createOrUpdateSubmeshesOctree && n.createOrUpdateSubmeshesOctree(r)
    }
    ,
    e.prototype.getHeightAtCoordinates = function(t, r) {
        var n = this.getWorldMatrix()
          , o = TmpVectors.Matrix[5];
        n.invertToRef(o);
        var a = TmpVectors.Vector3[8];
        if (Vector3.TransformCoordinatesFromFloatsToRef(t, 0, r, o, a),
        t = a.x,
        r = a.z,
        t < this._minX || t > this._maxX || r < this._minZ || r > this._maxZ)
            return this.position.y;
        (!this._heightQuads || this._heightQuads.length == 0) && (this._initHeightQuads(),
        this._computeHeightQuads());
        var s = this._getFacetAt(t, r)
          , l = -(s.x * t + s.z * r + s.w) / s.y;
        return Vector3.TransformCoordinatesFromFloatsToRef(0, l, 0, n, a),
        a.y
    }
    ,
    e.prototype.getNormalAtCoordinates = function(t, r) {
        var n = new Vector3(0,1,0);
        return this.getNormalAtCoordinatesToRef(t, r, n),
        n
    }
    ,
    e.prototype.getNormalAtCoordinatesToRef = function(t, r, n) {
        var o = this.getWorldMatrix()
          , a = TmpVectors.Matrix[5];
        o.invertToRef(a);
        var s = TmpVectors.Vector3[8];
        if (Vector3.TransformCoordinatesFromFloatsToRef(t, 0, r, a, s),
        t = s.x,
        r = s.z,
        t < this._minX || t > this._maxX || r < this._minZ || r > this._maxZ)
            return this;
        (!this._heightQuads || this._heightQuads.length == 0) && (this._initHeightQuads(),
        this._computeHeightQuads());
        var l = this._getFacetAt(t, r);
        return Vector3.TransformNormalFromFloatsToRef(l.x, l.y, l.z, o, n),
        this
    }
    ,
    e.prototype.updateCoordinateHeights = function() {
        return (!this._heightQuads || this._heightQuads.length == 0) && this._initHeightQuads(),
        this._computeHeightQuads(),
        this
    }
    ,
    e.prototype._getFacetAt = function(t, r) {
        var n = Math.floor((t + this._maxX) * this._subdivisionsX / this._width), o = Math.floor(-(r + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY), a = this._heightQuads[o * this._subdivisionsX + n], s;
        return r < a.slope.x * t + a.slope.y ? s = a.facet1 : s = a.facet2,
        s
    }
    ,
    e.prototype._initHeightQuads = function() {
        var t = this._subdivisionsX
          , r = this._subdivisionsY;
        this._heightQuads = new Array;
        for (var n = 0; n < r; n++)
            for (var o = 0; o < t; o++) {
                var a = {
                    slope: Vector2.Zero(),
                    facet1: new Vector4(0,0,0,0),
                    facet2: new Vector4(0,0,0,0)
                };
                this._heightQuads[n * t + o] = a
            }
        return this
    }
    ,
    e.prototype._computeHeightQuads = function() {
        var t = this.getVerticesData(VertexBuffer.PositionKind);
        if (!t)
            return this;
        for (var r = TmpVectors.Vector3[3], n = TmpVectors.Vector3[2], o = TmpVectors.Vector3[1], a = TmpVectors.Vector3[0], s = TmpVectors.Vector3[4], l = TmpVectors.Vector3[5], u = TmpVectors.Vector3[6], c = TmpVectors.Vector3[7], h = TmpVectors.Vector3[8], f = 0, d = 0, _ = 0, g = 0, m = 0, v = 0, y = 0, b = this._subdivisionsX, T = this._subdivisionsY, C = 0; C < T; C++)
            for (var A = 0; A < b; A++) {
                f = A * 3,
                d = C * (b + 1) * 3,
                _ = (C + 1) * (b + 1) * 3,
                r.x = t[d + f],
                r.y = t[d + f + 1],
                r.z = t[d + f + 2],
                n.x = t[d + f + 3],
                n.y = t[d + f + 4],
                n.z = t[d + f + 5],
                o.x = t[_ + f],
                o.y = t[_ + f + 1],
                o.z = t[_ + f + 2],
                a.x = t[_ + f + 3],
                a.y = t[_ + f + 4],
                a.z = t[_ + f + 5],
                g = (a.z - r.z) / (a.x - r.x),
                m = r.z - g * r.x,
                n.subtractToRef(r, s),
                o.subtractToRef(r, l),
                a.subtractToRef(r, u),
                Vector3.CrossToRef(u, l, c),
                Vector3.CrossToRef(s, u, h),
                c.normalize(),
                h.normalize(),
                v = -(c.x * r.x + c.y * r.y + c.z * r.z),
                y = -(h.x * n.x + h.y * n.y + h.z * n.z);
                var S = this._heightQuads[C * b + A];
                S.slope.copyFromFloats(g, m),
                S.facet1.copyFromFloats(c.x, c.y, c.z, v),
                S.facet2.copyFromFloats(h.x, h.y, h.z, y)
            }
        return this
    }
    ,
    e.prototype.serialize = function(t) {
        i.prototype.serialize.call(this, t),
        t.subdivisionsX = this._subdivisionsX,
        t.subdivisionsY = this._subdivisionsY,
        t.minX = this._minX,
        t.maxX = this._maxX,
        t.minZ = this._minZ,
        t.maxZ = this._maxZ,
        t.width = this._width,
        t.height = this._height
    }
    ,
    e.Parse = function(t, r) {
        var n = new e(t.name,r);
        return n._subdivisionsX = t.subdivisionsX || 1,
        n._subdivisionsY = t.subdivisionsY || 1,
        n._minX = t.minX,
        n._maxX = t.maxX,
        n._minZ = t.minZ,
        n._maxZ = t.maxZ,
        n._width = t.width,
        n._height = t.height,
        n
    }
    ,
    e
}(Mesh);
function CreateGroundVertexData(i) {
    var e = [], t = [], r = [], n = [], o, a, s = i.width || 1, l = i.height || 1, u = i.subdivisionsX || i.subdivisions || 1, c = i.subdivisionsY || i.subdivisions || 1;
    for (o = 0; o <= c; o++)
        for (a = 0; a <= u; a++) {
            var h = new Vector3(a * s / u - s / 2,0,(c - o) * l / c - l / 2)
              , f = new Vector3(0,1,0);
            t.push(h.x, h.y, h.z),
            r.push(f.x, f.y, f.z),
            n.push(a / u, 1 - o / c)
        }
    for (o = 0; o < c; o++)
        for (a = 0; a < u; a++)
            e.push(a + 1 + (o + 1) * (u + 1)),
            e.push(a + 1 + o * (u + 1)),
            e.push(a + o * (u + 1)),
            e.push(a + (o + 1) * (u + 1)),
            e.push(a + 1 + (o + 1) * (u + 1)),
            e.push(a + o * (u + 1));
    var d = new VertexData;
    return d.indices = e,
    d.positions = t,
    d.normals = r,
    d.uvs = n,
    d
}
function CreateTiledGroundVertexData(i) {
    var e = i.xmin !== void 0 && i.xmin !== null ? i.xmin : -1, t = i.zmin !== void 0 && i.zmin !== null ? i.zmin : -1, r = i.xmax !== void 0 && i.xmax !== null ? i.xmax : 1, n = i.zmax !== void 0 && i.zmax !== null ? i.zmax : 1, o = i.subdivisions || {
        w: 1,
        h: 1
    }, a = i.precision || {
        w: 1,
        h: 1
    }, s = new Array, l = new Array, u = new Array, c = new Array, h, f, d, _;
    o.h = o.h < 1 ? 1 : o.h,
    o.w = o.w < 1 ? 1 : o.w,
    a.w = a.w < 1 ? 1 : a.w,
    a.h = a.h < 1 ? 1 : a.h;
    var g = {
        w: (r - e) / o.w,
        h: (n - t) / o.h
    };
    function m(y, b, T, C) {
        var A = l.length / 3
          , S = a.w + 1;
        for (h = 0; h < a.h; h++)
            for (f = 0; f < a.w; f++) {
                var P = [A + f + h * S, A + (f + 1) + h * S, A + (f + 1) + (h + 1) * S, A + f + (h + 1) * S];
                s.push(P[1]),
                s.push(P[2]),
                s.push(P[3]),
                s.push(P[0]),
                s.push(P[1]),
                s.push(P[3])
            }
        var R = Vector3.Zero()
          , M = new Vector3(0,1,0);
        for (h = 0; h <= a.h; h++)
            for (R.z = h * (C - b) / a.h + b,
            f = 0; f <= a.w; f++)
                R.x = f * (T - y) / a.w + y,
                R.y = 0,
                l.push(R.x, R.y, R.z),
                u.push(M.x, M.y, M.z),
                c.push(f / a.w, h / a.h)
    }
    for (d = 0; d < o.h; d++)
        for (_ = 0; _ < o.w; _++)
            m(e + _ * g.w, t + d * g.h, e + (_ + 1) * g.w, t + (d + 1) * g.h);
    var v = new VertexData;
    return v.indices = s,
    v.positions = l,
    v.normals = u,
    v.uvs = c,
    v
}
function CreateGroundFromHeightMapVertexData(i) {
    var e = [], t = [], r = [], n = [], o, a, s = i.colorFilter || new Color3(.3,.59,.11), l = i.alphaFilter || 0, u = !1;
    if (i.minHeight > i.maxHeight) {
        u = !0;
        var c = i.maxHeight;
        i.maxHeight = i.minHeight,
        i.minHeight = c
    }
    for (o = 0; o <= i.subdivisions; o++)
        for (a = 0; a <= i.subdivisions; a++) {
            var h = new Vector3(a * i.width / i.subdivisions - i.width / 2,0,(i.subdivisions - o) * i.height / i.subdivisions - i.height / 2)
              , f = (h.x + i.width / 2) / i.width * (i.bufferWidth - 1) | 0
              , d = (1 - (h.z + i.height / 2) / i.height) * (i.bufferHeight - 1) | 0
              , _ = (f + d * i.bufferWidth) * 4
              , g = i.buffer[_] / 255
              , m = i.buffer[_ + 1] / 255
              , v = i.buffer[_ + 2] / 255
              , y = i.buffer[_ + 3] / 255;
            u && (g = 1 - g,
            m = 1 - m,
            v = 1 - v);
            var b = g * s.r + m * s.g + v * s.b;
            y >= l ? h.y = i.minHeight + (i.maxHeight - i.minHeight) * b : h.y = i.minHeight - Epsilon,
            t.push(h.x, h.y, h.z),
            r.push(0, 0, 0),
            n.push(a / i.subdivisions, 1 - o / i.subdivisions)
        }
    for (o = 0; o < i.subdivisions; o++)
        for (a = 0; a < i.subdivisions; a++) {
            var T = a + 1 + (o + 1) * (i.subdivisions + 1)
              , C = a + 1 + o * (i.subdivisions + 1)
              , A = a + o * (i.subdivisions + 1)
              , S = a + (o + 1) * (i.subdivisions + 1)
              , P = t[T * 3 + 1] >= i.minHeight
              , R = t[C * 3 + 1] >= i.minHeight
              , M = t[A * 3 + 1] >= i.minHeight;
            P && R && M && (e.push(T),
            e.push(C),
            e.push(A));
            var x = t[S * 3 + 1] >= i.minHeight;
            x && P && M && (e.push(S),
            e.push(T),
            e.push(A))
        }
    VertexData.ComputeNormals(t, e, r);
    var I = new VertexData;
    return I.indices = e,
    I.positions = t,
    I.normals = r,
    I.uvs = n,
    I
}
function CreateGround(i, e, t) {
    e === void 0 && (e = {});
    var r = new GroundMesh(i,t);
    r._setReady(!1),
    r._subdivisionsX = e.subdivisionsX || e.subdivisions || 1,
    r._subdivisionsY = e.subdivisionsY || e.subdivisions || 1,
    r._width = e.width || 1,
    r._height = e.height || 1,
    r._maxX = r._width / 2,
    r._maxZ = r._height / 2,
    r._minX = -r._maxX,
    r._minZ = -r._maxZ;
    var n = CreateGroundVertexData(e);
    return n.applyToMesh(r, e.updatable),
    r._setReady(!0),
    r
}
function CreateTiledGround(i, e, t) {
    t === void 0 && (t = null);
    var r = new Mesh(i,t)
      , n = CreateTiledGroundVertexData(e);
    return n.applyToMesh(r, e.updatable),
    r
}
function CreateGroundFromHeightMap(i, e, t, r) {
    t === void 0 && (t = {}),
    r === void 0 && (r = null);
    var n = t.width || 10
      , o = t.height || 10
      , a = t.subdivisions || 1
      , s = t.minHeight || 0
      , l = t.maxHeight || 1
      , u = t.colorFilter || new Color3(.3,.59,.11)
      , c = t.alphaFilter || 0
      , h = t.updatable
      , f = t.onReady;
    r = r || EngineStore.LastCreatedScene;
    var d = new GroundMesh(i,r);
    d._subdivisionsX = a,
    d._subdivisionsY = a,
    d._width = n,
    d._height = o,
    d._maxX = d._width / 2,
    d._maxZ = d._height / 2,
    d._minX = -d._maxX,
    d._minZ = -d._maxZ,
    d._setReady(!1);
    var _ = function(g) {
        var m = g.width
          , v = g.height;
        if (!r.isDisposed) {
            var y = r == null ? void 0 : r.getEngine().resizeImageBitmap(g, m, v)
              , b = CreateGroundFromHeightMapVertexData({
                width: n,
                height: o,
                subdivisions: a,
                minHeight: s,
                maxHeight: l,
                colorFilter: u,
                buffer: y,
                bufferWidth: m,
                bufferHeight: v,
                alphaFilter: c
            });
            b.applyToMesh(d, h),
            f && f(d),
            d._setReady(!0)
        }
    };
    return Tools.LoadImage(e, _, function() {}, r.offlineProvider),
    d
}
VertexData.CreateGround = CreateGroundVertexData;
VertexData.CreateTiledGround = CreateTiledGroundVertexData;
VertexData.CreateGroundFromHeightMap = CreateGroundFromHeightMapVertexData;
Mesh.CreateGround = function(i, e, t, r, n, o) {
    var a = {
        width: e,
        height: t,
        subdivisions: r,
        updatable: o
    };
    return CreateGround(i, a, n)
}
;
Mesh.CreateTiledGround = function(i, e, t, r, n, o, a, s, l) {
    var u = {
        xmin: e,
        zmin: t,
        xmax: r,
        zmax: n,
        subdivisions: o,
        precision: a,
        updatable: l
    };
    return CreateTiledGround(i, u, s)
}
;
Mesh.CreateGroundFromHeightMap = function(i, e, t, r, n, o, a, s, l, u, c) {
    var h = {
        width: t,
        height: r,
        subdivisions: n,
        minHeight: o,
        maxHeight: a,
        updatable: l,
        onReady: u,
        alphaFilter: c
    };
    return CreateGroundFromHeightMap(i, e, h, s)
}
;
function CreateTube(i, e, t) {
    t === void 0 && (t = null);
    var r = e.path
      , n = e.instance
      , o = 1;
    e.radius !== void 0 ? o = e.radius : n && (o = n._creationDataStorage.radius);
    var a = e.tessellation || 64
      , s = e.radiusFunction || null
      , l = e.cap || Mesh.NO_CAP
      , u = e.invertUV || !1
      , c = e.updatable
      , h = Mesh._GetDefaultSideOrientation(e.sideOrientation);
    e.arc = e.arc && (e.arc <= 0 || e.arc > 1) ? 1 : e.arc || 1;
    var f = function(b, T, C, A, S, P, R, M) {
        for (var x = T.getTangents(), I = T.getNormals(), w = T.getDistances(), O = Math.PI * 2, D = O / S * M, F = function() {
            return A
        }, V = P || F, N, L, k, U, z = TmpVectors.Matrix[0], H = R === Mesh.NO_CAP || R === Mesh.CAP_END ? 0 : 2, G = 0; G < b.length; G++) {
            L = V(G, w[G]),
            N = Array(),
            k = I[G];
            for (var W = 0; W < S; W++)
                Matrix.RotationAxisToRef(x[G], D * W, z),
                U = N[W] ? N[W] : Vector3.Zero(),
                Vector3.TransformCoordinatesToRef(k, z, U),
                U.scaleInPlace(L).addInPlace(b[G]),
                N[W] = U;
            C[H] = N,
            H++
        }
        var j = function(B, X) {
            for (var $ = Array(), Y = 0; Y < B; Y++)
                $.push(b[X]);
            return $
        };
        switch (R) {
        case Mesh.NO_CAP:
            break;
        case Mesh.CAP_START:
            C[0] = j(S, 0),
            C[1] = C[2].slice(0);
            break;
        case Mesh.CAP_END:
            C[H] = C[H - 1].slice(0),
            C[H + 1] = j(S, b.length - 1);
            break;
        case Mesh.CAP_ALL:
            C[0] = j(S, 0),
            C[1] = C[2].slice(0),
            C[H] = C[H - 1].slice(0),
            C[H + 1] = j(S, b.length - 1);
            break
        }
        return C
    }, d, _;
    if (n) {
        var g = n._creationDataStorage
          , m = e.arc || g.arc;
        return d = g.path3D.update(r),
        _ = f(r, d, g.pathArray, o, g.tessellation, s, g.cap, m),
        n = CreateRibbon("", {
            pathArray: _,
            instance: n
        }),
        g.path3D = d,
        g.pathArray = _,
        g.arc = m,
        g.radius = o,
        n
    }
    d = new Path3D(r);
    var v = new Array;
    l = l < 0 || l > 3 ? 0 : l,
    _ = f(r, d, v, o, a, s, l, e.arc);
    var y = CreateRibbon(i, {
        pathArray: _,
        closePath: !0,
        closeArray: !1,
        updatable: c,
        sideOrientation: h,
        invertUV: u,
        frontUVs: e.frontUVs,
        backUVs: e.backUVs
    }, t);
    return y._creationDataStorage.pathArray = _,
    y._creationDataStorage.path3D = d,
    y._creationDataStorage.tessellation = a,
    y._creationDataStorage.cap = l,
    y._creationDataStorage.arc = e.arc,
    y._creationDataStorage.radius = o,
    y
}
Mesh.CreateTube = function(i, e, t, r, n, o, a, s, l, u) {
    var c = {
        path: e,
        radius: t,
        tessellation: r,
        radiusFunction: n,
        arc: 1,
        cap: o,
        updatable: s,
        sideOrientation: l,
        instance: u
    };
    return CreateTube(i, c, a)
}
;
function CreatePolyhedronVertexData(i) {
    var e = [];
    e[0] = {
        vertex: [[0, 0, 1.732051], [1.632993, 0, -.5773503], [-.8164966, 1.414214, -.5773503], [-.8164966, -1.414214, -.5773503]],
        face: [[0, 1, 2], [0, 2, 3], [0, 3, 1], [1, 3, 2]]
    },
    e[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]]
    },
    e[2] = {
        vertex: [[0, 0, 1.070466], [.7136442, 0, .7978784], [-.3568221, .618034, .7978784], [-.3568221, -.618034, .7978784], [.7978784, .618034, .3568221], [.7978784, -.618034, .3568221], [-.9341724, .381966, .3568221], [.1362939, 1, .3568221], [.1362939, -1, .3568221], [-.9341724, -.381966, .3568221], [.9341724, .381966, -.3568221], [.9341724, -.381966, -.3568221], [-.7978784, .618034, -.3568221], [-.1362939, 1, -.3568221], [-.1362939, -1, -.3568221], [-.7978784, -.618034, -.3568221], [.3568221, .618034, -.7978784], [.3568221, -.618034, -.7978784], [-.7136442, 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]]
    },
    e[3] = {
        vertex: [[0, 0, 1.175571], [1.051462, 0, .5257311], [.3249197, 1, .5257311], [-.8506508, .618034, .5257311], [-.8506508, -.618034, .5257311], [.3249197, -1, .5257311], [.8506508, .618034, -.5257311], [.8506508, -.618034, -.5257311], [-.3249197, 1, -.5257311], [-1.051462, 0, -.5257311], [-.3249197, -1, -.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]]
    },
    e[4] = {
        vertex: [[0, 0, 1.070722], [.7148135, 0, .7971752], [-.104682, .7071068, .7971752], [-.6841528, .2071068, .7971752], [-.104682, -.7071068, .7971752], [.6101315, .7071068, .5236279], [1.04156, .2071068, .1367736], [.6101315, -.7071068, .5236279], [-.3574067, 1, .1367736], [-.7888348, -.5, .5236279], [-.9368776, .5, .1367736], [-.3574067, -1, .1367736], [.3574067, 1, -.1367736], [.9368776, -.5, -.1367736], [.7888348, .5, -.5236279], [.3574067, -1, -.1367736], [-.6101315, .7071068, -.5236279], [-1.04156, -.2071068, -.1367736], [-.6101315, -.7071068, -.5236279], [.104682, .7071068, -.7971752], [.6841528, -.2071068, -.7971752], [.104682, -.7071068, -.7971752], [-.7148135, 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]]
    },
    e[5] = {
        vertex: [[0, 0, 1.322876], [1.309307, 0, .1889822], [-.9819805, .8660254, .1889822], [.1636634, -1.299038, .1889822], [.3273268, .8660254, -.9449112], [-.8183171, -.4330127, -.9449112]],
        face: [[0, 3, 1], [2, 4, 5], [0, 1, 4, 2], [0, 2, 5, 3], [1, 3, 5, 4]]
    },
    e[6] = {
        vertex: [[0, 0, 1.159953], [1.013464, 0, .5642542], [-.3501431, .9510565, .5642542], [-.7715208, -.6571639, .5642542], [.6633206, .9510565, -.03144481], [.8682979, -.6571639, -.3996071], [-1.121664, .2938926, -.03144481], [-.2348831, -1.063314, -.3996071], [.5181548, .2938926, -.9953061], [-.5850262, -.112257, -.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]]
    },
    e[7] = {
        vertex: [[0, 0, 1.118034], [.8944272, 0, .6708204], [-.2236068, .8660254, .6708204], [-.7826238, -.4330127, .6708204], [.6708204, .8660254, .2236068], [1.006231, -.4330127, -.2236068], [-1.006231, .4330127, .2236068], [-.6708204, -.8660254, -.2236068], [.7826238, .4330127, -.6708204], [.2236068, -.8660254, -.6708204], [-.8944272, 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]]
    },
    e[8] = {
        vertex: [[-.729665, .670121, .319155], [-.655235, -.29213, -.754096], [-.093922, -.607123, .537818], [.702196, .595691, .485187], [.776626, -.36656, -.588064]],
        face: [[1, 4, 2], [0, 1, 2], [3, 0, 2], [4, 3, 2], [4, 1, 0, 3]]
    },
    e[9] = {
        vertex: [[-.868849, -.100041, .61257], [-.329458, .976099, .28078], [-.26629, -.013796, -.477654], [-.13392, -1.034115, .229829], [.738834, .707117, -.307018], [.859683, -.535264, -.338508]],
        face: [[3, 0, 2], [5, 3, 2], [4, 5, 2], [1, 4, 2], [0, 1, 2], [0, 3, 5, 4, 1]]
    },
    e[10] = {
        vertex: [[-.610389, .243975, .531213], [-.187812, -.48795, -.664016], [-.187812, .9759, -.664016], [.187812, -.9759, .664016], [.798201, .243975, .132803]],
        face: [[1, 3, 0], [3, 4, 0], [3, 1, 4], [0, 2, 1], [0, 4, 2], [2, 4, 1]]
    },
    e[11] = {
        vertex: [[-1.028778, .392027, -.048786], [-.640503, -.646161, .621837], [-.125162, -.395663, -.540059], [.004683, .888447, -.651988], [.125161, .395663, .540059], [.632925, -.791376, .433102], [1.031672, .157063, -.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]]
    },
    e[12] = {
        vertex: [[-.669867, .334933, -.529576], [-.669867, .334933, .529577], [-.4043, 1.212901, 0], [-.334933, -.669867, -.529576], [-.334933, -.669867, .529577], [.334933, .669867, -.529576], [.334933, .669867, .529577], [.4043, -1.212901, 0], [.669867, -.334933, -.529576], [.669867, -.334933, .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]]
    },
    e[13] = {
        vertex: [[-.931836, .219976, -.264632], [-.636706, .318353, .692816], [-.613483, -.735083, -.264632], [-.326545, .979634, 0], [-.318353, -.636706, .692816], [-.159176, .477529, -.856368], [.159176, -.477529, -.856368], [.318353, .636706, .692816], [.326545, -.979634, 0], [.613482, .735082, -.264632], [.636706, -.318353, .692816], [.931835, -.219977, -.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]]
    },
    e[14] = {
        vertex: [[-.93465, .300459, -.271185], [-.838689, -.260219, -.516017], [-.711319, .717591, .128359], [-.710334, -.156922, .080946], [-.599799, .556003, -.725148], [-.503838, -.004675, -.969981], [-.487004, .26021, .48049], [-.460089, -.750282, -.512622], [-.376468, .973135, -.325605], [-.331735, -.646985, .084342], [-.254001, .831847, .530001], [-.125239, -.494738, -.966586], [.029622, .027949, .730817], [.056536, -.982543, -.262295], [.08085, 1.087391, .076037], [.125583, -.532729, .485984], [.262625, .599586, .780328], [.391387, -.726999, -.716259], [.513854, -.868287, .139347], [.597475, .85513, .326364], [.641224, .109523, .783723], [.737185, -.451155, .538891], [.848705, -.612742, -.314616], [.976075, .365067, .32976], [1.072036, -.19561, .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 t = i.type && (i.type < 0 || i.type >= e.length) ? 0 : i.type || 0, r = i.size, n = i.sizeX || r || 1, o = i.sizeY || r || 1, a = i.sizeZ || r || 1, s = i.custom || e[t], l = s.face.length, u = i.faceUV || new Array(l), c = i.faceColors, h = i.flat === void 0 ? !0 : i.flat, f = i.sideOrientation === 0 ? 0 : i.sideOrientation || VertexData.DEFAULTSIDE, d = new Array, _ = new Array, g = new Array, m = new Array, v = new Array, y = 0, b = 0, T = new Array, C = 0, A = 0, S, P, R, M, x, I;
    if (h)
        for (A = 0; A < l; A++)
            c && c[A] === void 0 && (c[A] = new Color4(1,1,1,1)),
            u && u[A] === void 0 && (u[A] = new Vector4(0,0,1,1));
    if (h)
        for (A = 0; A < l; A++) {
            var w = s.face[A].length;
            for (R = 2 * Math.PI / w,
            M = .5 * Math.tan(R / 2),
            x = .5,
            C = 0; C < w; C++)
                d.push(s.vertex[s.face[A][C]][0] * n, s.vertex[s.face[A][C]][1] * o, s.vertex[s.face[A][C]][2] * a),
                T.push(y),
                y++,
                S = u[A].x + (u[A].z - u[A].x) * (.5 + M),
                P = u[A].y + (u[A].w - u[A].y) * (x - .5),
                m.push(S, P),
                I = M * Math.cos(R) - x * Math.sin(R),
                x = M * Math.sin(R) + x * Math.cos(R),
                M = I,
                c && v.push(c[A].r, c[A].g, c[A].b, c[A].a);
            for (C = 0; C < w - 2; C++)
                _.push(T[0 + b], T[C + 2 + b], T[C + 1 + b]);
            b += w
        }
    else {
        for (C = 0; C < s.vertex.length; C++)
            d.push(s.vertex[C][0] * n, s.vertex[C][1] * o, s.vertex[C][2] * a),
            m.push(0, 0);
        for (A = 0; A < l; A++)
            for (C = 0; C < s.face[A].length - 2; C++)
                _.push(s.face[A][0], s.face[A][C + 2], s.face[A][C + 1])
    }
    VertexData.ComputeNormals(d, _, g),
    VertexData._ComputeSides(f, d, _, g, m, i.frontUVs, i.backUVs);
    var O = new VertexData;
    return O.positions = d,
    O.indices = _,
    O.normals = g,
    O.uvs = m,
    c && h && (O.colors = v),
    O
}
function CreatePolyhedron(i, e, t) {
    e === void 0 && (e = {}),
    t === void 0 && (t = null);
    var r = new Mesh(i,t);
    e.sideOrientation = Mesh._GetDefaultSideOrientation(e.sideOrientation),
    r._originalBuilderSideOrientation = e.sideOrientation;
    var n = CreatePolyhedronVertexData(e);
    return n.applyToMesh(r, e.updatable),
    r
}
VertexData.CreatePolyhedron = CreatePolyhedronVertexData;
Mesh.CreatePolyhedron = function(i, e, t) {
    return CreatePolyhedron(i, e, t)
}
;
function CreateIcoSphereVertexData(i) {
    var e = i.sideOrientation || VertexData.DEFAULTSIDE, t = i.radius || 1, r = i.flat === void 0 ? !0 : i.flat, n = i.subdivisions || 4, o = i.radiusX || t, a = i.radiusY || t, s = i.radiusZ || t, l = (1 + Math.sqrt(5)) / 2, u = [-1, l, -0, 1, l, 0, -1, -l, 0, 1, -l, 0, 0, -1, -l, 0, 1, -l, 0, -1, l, 0, 1, l, l, 0, 1, l, 0, -1, -l, 0, 1, -l, 0, -1], c = [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], h = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 2, 3, 3, 3, 4, 7, 8, 9, 9, 10, 11], f = [5, 1, 3, 1, 6, 4, 0, 0, 5, 3, 4, 2, 2, 2, 4, 0, 2, 0, 1, 1, 6, 0, 6, 2, 0, 4, 3, 3, 4, 4, 3, 1, 4, 2, 4, 4, 0, 2, 1, 1, 2, 2, 3, 3, 1, 3, 2, 4], d = 138 / 1024, _ = 239 / 1024, g = 60 / 1024, m = 26 / 1024, v = -40 / 1024, y = 20 / 1024, b = [0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0], T = new Array, C = new Array, A = new Array, S = new Array, P = 0, R = new Array(3), M = new Array(3), x;
    for (x = 0; x < 3; x++)
        R[x] = Vector3.Zero(),
        M[x] = Vector2.Zero();
    for (var I = 0; I < 20; I++) {
        for (x = 0; x < 3; x++) {
            var w = c[3 * I + x];
            R[x].copyFromFloats(u[3 * h[w]], u[3 * h[w] + 1], u[3 * h[w] + 2]),
            R[x].normalize().scaleInPlace(t),
            M[x].copyFromFloats(f[2 * w] * d + g + b[I] * v, f[2 * w + 1] * _ + m + b[I] * y)
        }
        for (var O = function(N, L, k, U) {
            var z = Vector3.Lerp(R[0], R[2], L / n)
              , H = Vector3.Lerp(R[1], R[2], L / n)
              , G = n === L ? R[2] : Vector3.Lerp(z, H, N / (n - L));
            G.normalize();
            var W;
            if (r) {
                var j = Vector3.Lerp(R[0], R[2], U / n)
                  , B = Vector3.Lerp(R[1], R[2], U / n);
                W = Vector3.Lerp(j, B, k / (n - U))
            } else
                W = new Vector3(G.x,G.y,G.z);
            W.x /= o,
            W.y /= a,
            W.z /= s,
            W.normalize();
            var X = Vector2.Lerp(M[0], M[2], L / n)
              , $ = Vector2.Lerp(M[1], M[2], L / n)
              , Y = n === L ? M[2] : Vector2.Lerp(X, $, N / (n - L));
            C.push(G.x * o, G.y * a, G.z * s),
            A.push(W.x, W.y, W.z),
            S.push(Y.x, Y.y),
            T.push(P),
            P++
        }, D = 0; D < n; D++)
            for (var F = 0; F + D < n; F++)
                O(F, D, F + 1 / 3, D + 1 / 3),
                O(F + 1, D, F + 1 / 3, D + 1 / 3),
                O(F, D + 1, F + 1 / 3, D + 1 / 3),
                F + D + 1 < n && (O(F + 1, D, F + 2 / 3, D + 2 / 3),
                O(F + 1, D + 1, F + 2 / 3, D + 2 / 3),
                O(F, D + 1, F + 2 / 3, D + 2 / 3))
    }
    VertexData._ComputeSides(e, C, T, A, S, i.frontUVs, i.backUVs);
    var V = new VertexData;
    return V.indices = T,
    V.positions = C,
    V.normals = A,
    V.uvs = S,
    V
}
function CreateIcoSphere(i, e, t) {
    e === void 0 && (e = {}),
    t === void 0 && (t = null);
    var r = new Mesh(i,t);
    e.sideOrientation = Mesh._GetDefaultSideOrientation(e.sideOrientation),
    r._originalBuilderSideOrientation = e.sideOrientation;
    var n = CreateIcoSphereVertexData(e);
    return n.applyToMesh(r, e.updatable),
    r
}
VertexData.CreateIcoSphere = CreateIcoSphereVertexData;
Mesh.CreateIcoSphere = function(i, e, t) {
    return CreateIcoSphere(i, e, t)
}
;
var PositionNormalTextureVertex = function() {
    function i(e, t, r) {
        e === void 0 && (e = Vector3.Zero()),
        t === void 0 && (t = Vector3.Up()),
        r === void 0 && (r = Vector2.Zero()),
        this.position = e,
        this.normal = t,
        this.uv = r
    }
    return i.prototype.clone = function() {
        return new i(this.position.clone(),this.normal.clone(),this.uv.clone())
    }
    ,
    i
}();
function CreateDecal(i, e, t) {
    var r = e.getIndices()
      , n = e.getVerticesData(VertexBuffer.PositionKind)
      , o = e.getVerticesData(VertexBuffer.NormalKind)
      , a = e.getVerticesData(VertexBuffer.UVKind)
      , s = t.position || Vector3.Zero()
      , l = t.normal || Vector3.Up()
      , u = t.size || Vector3.One()
      , c = t.angle || 0;
    if (!l) {
        var h = new Vector3(0,0,1)
          , f = e.getScene().activeCamera
          , d = Vector3.TransformCoordinates(h, f.getWorldMatrix());
        l = f.globalPosition.subtract(d)
    }
    var _ = -Math.atan2(l.z, l.x) - Math.PI / 2
      , g = Math.sqrt(l.x * l.x + l.z * l.z)
      , m = Math.atan2(l.y, g)
      , v = Matrix.RotationYawPitchRoll(_, m, c).multiply(Matrix.Translation(s.x, s.y, s.z))
      , y = Matrix.Invert(v)
      , b = e.getWorldMatrix()
      , T = b.multiply(y)
      , C = new VertexData;
    C.indices = [],
    C.positions = [],
    C.normals = [],
    C.uvs = [];
    for (var A = 0, S = function(O) {
        var D = new PositionNormalTextureVertex;
        if (!r || !n || !o)
            return D;
        var F = r[O];
        return D.position = new Vector3(n[F * 3],n[F * 3 + 1],n[F * 3 + 2]),
        D.position = Vector3.TransformCoordinates(D.position, T),
        D.normal = new Vector3(o[F * 3],o[F * 3 + 1],o[F * 3 + 2]),
        D.normal = Vector3.TransformNormal(D.normal, T),
        t.captureUVS && a && (D.uv = new Vector2(a[F * 2],a[F * 2 + 1])),
        D
    }, P = function(O, D) {
        if (O.length === 0)
            return O;
        for (var F = .5 * Math.abs(Vector3.Dot(u, D)), V = function(K, Z) {
            var q = Vector3.GetClipFactor(K.position, Z.position, D, F);
            return new PositionNormalTextureVertex(Vector3.Lerp(K.position, Z.position, q),Vector3.Lerp(K.normal, Z.normal, q))
        }, N = new Array, L = 0; L < O.length; L += 3) {
            var k, U, z, H = 0, G = null, W = null, j = null, B = null, X = Vector3.Dot(O[L].position, D) - F, $ = Vector3.Dot(O[L + 1].position, D) - F, Y = Vector3.Dot(O[L + 2].position, D) - F;
            switch (k = X > 0,
            U = $ > 0,
            z = Y > 0,
            H = (k ? 1 : 0) + (U ? 1 : 0) + (z ? 1 : 0),
            H) {
            case 0:
                N.push(O[L]),
                N.push(O[L + 1]),
                N.push(O[L + 2]);
                break;
            case 1:
                if (k && (G = O[L + 1],
                W = O[L + 2],
                j = V(O[L], G),
                B = V(O[L], W)),
                U) {
                    G = O[L],
                    W = O[L + 2],
                    j = V(O[L + 1], G),
                    B = V(O[L + 1], W),
                    N.push(j),
                    N.push(W.clone()),
                    N.push(G.clone()),
                    N.push(W.clone()),
                    N.push(j.clone()),
                    N.push(B);
                    break
                }
                z && (G = O[L],
                W = O[L + 1],
                j = V(O[L + 2], G),
                B = V(O[L + 2], W)),
                G && W && j && B && (N.push(G.clone()),
                N.push(W.clone()),
                N.push(j),
                N.push(B),
                N.push(j.clone()),
                N.push(W.clone()));
                break;
            case 2:
                k || (G = O[L].clone(),
                W = V(G, O[L + 1]),
                j = V(G, O[L + 2]),
                N.push(G),
                N.push(W),
                N.push(j)),
                U || (G = O[L + 1].clone(),
                W = V(G, O[L + 2]),
                j = V(G, O[L]),
                N.push(G),
                N.push(W),
                N.push(j)),
                z || (G = O[L + 2].clone(),
                W = V(G, O[L]),
                j = V(G, O[L + 1]),
                N.push(G),
                N.push(W),
                N.push(j));
                break
            }
        }
        return N
    }, R = 0; R < r.length; R += 3) {
        var M = new Array;
        if (M.push(S(R)),
        M.push(S(R + 1)),
        M.push(S(R + 2)),
        M = P(M, new Vector3(1,0,0)),
        M = P(M, new Vector3(-1,0,0)),
        M = P(M, new Vector3(0,1,0)),
        M = P(M, new Vector3(0,-1,0)),
        M = P(M, new Vector3(0,0,1)),
        M = P(M, new Vector3(0,0,-1)),
        M.length !== 0)
            for (var x = 0; x < M.length; x++) {
                var I = M[x];
                C.indices.push(A),
                I.position.toArray(C.positions, A * 3),
                I.normal.toArray(C.normals, A * 3),
                t.captureUVS ? I.uv.toArray(C.uvs, A * 2) : (C.uvs.push(.5 + I.position.x / u.x),
                C.uvs.push(.5 + I.position.y / u.y)),
                A++
            }
    }
    var w = new Mesh(i,e.getScene());
    return C.applyToMesh(w),
    w.position = s.clone(),
    w.rotation = new Vector3(m,_,c),
    w
}
Mesh.CreateDecal = function(i, e, t, r, n, o) {
    var a = {
        position: t,
        normal: r,
        size: n,
        angle: o
    };
    return CreateDecal(i, e, a)
}
;
function CreateCapsuleVertexData(i) {
    i === void 0 && (i = {
        subdivisions: 2,
        tessellation: 16,
        height: 1,
        radius: .25,
        capSubdivisions: 6
    });
    var e = Math.max(i.subdivisions ? i.subdivisions : 2, 1), t = Math.max(i.tessellation ? i.tessellation : 16, 3), r = Math.max(i.height ? i.height : 1, 0), n = Math.max(i.radius ? i.radius : .25, 0), o = Math.max(i.capSubdivisions ? i.capSubdivisions : 6, 1), a = t, s = e, l = Math.max(i.radiusTop ? i.radiusTop : n, 0), u = Math.max(i.radiusBottom ? i.radiusBottom : n, 0), c = r - (l + u), h = 0, f = 2 * Math.PI, d = Math.max(i.topCapSubdivisions ? i.topCapSubdivisions : o, 1), _ = Math.max(i.bottomCapSubdivisions ? i.bottomCapSubdivisions : o, 1), g = Math.acos((u - l) / r), m = [], v = [], y = [], b = [], T = 0, C = [], A = c * .5, S = Math.PI * .5, P, R, M = Vector3.Zero(), x = Vector3.Zero(), I = Math.cos(g), w = Math.sin(g), O = new Vector2(l * w,A + l * I).subtract(new Vector2(u * w,-A + u * I)).length(), D = l * g + O + u * (S - g), F = 0;
    for (R = 0; R <= d; R++) {
        var V = []
          , N = S - g * (R / d);
        F += l * g / d;
        var L = Math.cos(N)
          , k = Math.sin(N)
          , U = L * l;
        for (P = 0; P <= a; P++) {
            var z = P / a
              , H = z * f + h
              , G = Math.sin(H)
              , W = Math.cos(H);
            x.x = U * G,
            x.y = A + k * l,
            x.z = U * W,
            v.push(x.x, x.y, x.z),
            M.set(L * G, k, L * W),
            y.push(M.x, M.y, M.z),
            b.push(z, 1 - F / D),
            V.push(T),
            T++
        }
        C.push(V)
    }
    var j = r - l - u + I * l - I * u
      , B = w * (u - l) / j;
    for (R = 1; R <= s; R++) {
        var V = [];
        F += O / s;
        var U = w * (R * (u - l) / s + l);
        for (P = 0; P <= a; P++) {
            var z = P / a
              , H = z * f + h
              , G = Math.sin(H)
              , W = Math.cos(H);
            x.x = U * G,
            x.y = A + I * l - R * j / s,
            x.z = U * W,
            v.push(x.x, x.y, x.z),
            M.set(G, B, W).normalize(),
            y.push(M.x, M.y, M.z),
            b.push(z, 1 - F / D),
            V.push(T),
            T++
        }
        C.push(V)
    }
    for (R = 1; R <= _; R++) {
        var V = []
          , N = S - g - (Math.PI - g) * (R / _);
        F += u * g / _;
        var L = Math.cos(N)
          , k = Math.sin(N)
          , U = L * u;
        for (P = 0; P <= a; P++) {
            var z = P / a
              , H = z * f + h
              , G = Math.sin(H)
              , W = Math.cos(H);
            x.x = U * G,
            x.y = -A + k * u,
            x.z = U * W,
            v.push(x.x, x.y, x.z),
            M.set(L * G, k, L * W),
            y.push(M.x, M.y, M.z),
            b.push(z, 1 - F / D),
            V.push(T),
            T++
        }
        C.push(V)
    }
    for (P = 0; P < a; P++)
        for (R = 0; R < d + s + _; R++) {
            var X = C[R][P]
              , $ = C[R + 1][P]
              , Y = C[R + 1][P + 1]
              , K = C[R][P + 1];
            m.push(X),
            m.push($),
            m.push(K),
            m.push($),
            m.push(Y),
            m.push(K)
        }
    if (m = m.reverse(),
    i.orientation && !i.orientation.equals(Vector3.Up())) {
        var Z = new Matrix;
        i.orientation.clone().scale(Math.PI * .5).cross(Vector3.Up()).toQuaternion().toRotationMatrix(Z);
        for (var q = Vector3.Zero(), J = 0; J < v.length; J += 3)
            q.set(v[J], v[J + 1], v[J + 2]),
            Vector3.TransformCoordinatesToRef(q.clone(), Z, q),
            v[J] = q.x,
            v[J + 1] = q.y,
            v[J + 2] = q.z
    }
    var Q = new VertexData;
    return Q.positions = v,
    Q.normals = y,
    Q.uvs = b,
    Q.indices = m,
    Q
}
function CreateCapsule(i, e, t) {
    e === void 0 && (e = {
        orientation: Vector3.Up(),
        subdivisions: 2,
        tessellation: 16,
        height: 1,
        radius: .25,
        capSubdivisions: 6,
        updatable: !1
    }),
    t === void 0 && (t = null);
    var r = new Mesh(i,t)
      , n = CreateCapsuleVertexData(e);
    return n.applyToMesh(r, e.updatable),
    r
}
Mesh.CreateCapsule = function(i, e, t) {
    return CreateCapsule(i, e, t)
}
;
VertexData.CreateCapsule = CreateCapsuleVertexData;
var _IsoVector = function() {
    function i(e, t) {
        e === void 0 && (e = 0),
        t === void 0 && (t = 0),
        this.x = e,
        this.y = t,
        e !== Math.floor(e) && Logger$2.Warn("x is not an integer, floor(x) used"),
        t !== Math.floor(t) && Logger$2.Warn("y is not an integer, floor(y) used")
    }
    return i.prototype.clone = function() {
        return new i(this.x,this.y)
    }
    ,
    i.prototype.rotate60About = function(e) {
        var t = this.x;
        return this.x = e.x + e.y - this.y,
        this.y = t + this.y - e.x,
        this
    }
    ,
    i.prototype.rotateNeg60About = function(e) {
        var t = this.x;
        return this.x = t + this.y - e.y,
        this.y = e.x + e.y - t,
        this
    }
    ,
    i.prototype.rotate120 = function(e, t) {
        e !== Math.floor(e) && Logger$2.Warn("m not an integer only floor(m) used"),
        t !== Math.floor(t) && Logger$2.Warn("n not an integer only floor(n) used");
        var r = this.x;
        return this.x = e - r - this.y,
        this.y = t + r,
        this
    }
    ,
    i.prototype.rotateNeg120 = function(e, t) {
        e !== Math.floor(e) && Logger$2.Warn("m is not an integer, floor(m) used"),
        t !== Math.floor(t) && Logger$2.Warn("n is not an integer,   floor(n) used");
        var r = this.x;
        return this.x = this.y - t,
        this.y = e + t - r - this.y,
        this
    }
    ,
    i.prototype.toCartesianOrigin = function(e, t) {
        var r = Vector3.Zero();
        return r.x = e.x + 2 * this.x * t + this.y * t,
        r.y = e.y + Math.sqrt(3) * this.y * t,
        r
    }
    ,
    i.Zero = function() {
        return new i(0,0)
    }
    ,
    i
}()
  , _PrimaryIsoTriangle = function() {
    function i() {
        this.cartesian = [],
        this.vertices = [],
        this.max = [],
        this.min = [],
        this.closestTo = [],
        this.innerFacets = [],
        this.isoVecsABOB = [],
        this.isoVecsOBOA = [],
        this.isoVecsBAOA = [],
        this.vertexTypes = [],
        this.IDATA = new PolyhedronData("icosahedron","Regular",[[0, PHI, -1], [-PHI, 1, 0], [-1, 0, -PHI], [1, 0, -PHI], [PHI, 1, 0], [0, PHI, 1], [-1, 0, PHI], [-PHI, -1, 0], [0, -PHI, -1], [PHI, -1, 0], [1, 0, PHI], [0, -PHI, 1]],[[0, 2, 1], [0, 3, 2], [0, 4, 3], [0, 5, 4], [0, 1, 5], [7, 6, 1], [8, 7, 2], [9, 8, 3], [10, 9, 4], [6, 10, 5], [2, 7, 1], [3, 8, 2], [4, 9, 3], [5, 10, 4], [1, 6, 5], [11, 6, 7], [11, 7, 8], [11, 8, 9], [11, 9, 10], [11, 10, 6]])
    }
    return i.prototype.setIndices = function() {
        var e = 12
          , t = {}
          , r = this.m
          , n = this.n
          , o = r
          , a = 1
          , s = 0;
        n !== 0 && (o = Scalar.HCF(r, n)),
        a = r / o,
        s = n / o;
        var l, u, c, h, f, d = _IsoVector.Zero(), _ = new _IsoVector(r,n), g = new _IsoVector(-n,r + n), m = _IsoVector.Zero(), v = _IsoVector.Zero(), y = _IsoVector.Zero(), b = [], T, C, A, S, P = [], R = this.vertByDist;
        this.IDATA.edgematch = [[1, "B"], [2, "B"], [3, "B"], [4, "B"], [0, "B"], [10, "O", 14, "A"], [11, "O", 10, "A"], [12, "O", 11, "A"], [13, "O", 12, "A"], [14, "O", 13, "A"], [0, "O"], [1, "O"], [2, "O"], [3, "O"], [4, "O"], [19, "B", 5, "A"], [15, "B", 6, "A"], [16, "B", 7, "A"], [17, "B", 8, "A"], [18, "B", 9, "A"]];
        for (var M = 0; M < 20; M++) {
            if (b = this.IDATA.face[M],
            c = b[2],
            h = b[1],
            f = b[0],
            A = d.x + "|" + d.y,
            T = M + "|" + A,
            T in t || (t[T] = c,
            P[c] = [b[R[A][0]], R[A][1]]),
            A = _.x + "|" + _.y,
            T = M + "|" + A,
            T in t || (t[T] = h,
            P[h] = [b[R[A][0]], R[A][1]]),
            A = g.x + "|" + g.y,
            T = M + "|" + A,
            T in t || (t[T] = f,
            P[f] = [b[R[A][0]], R[A][1]]),
            l = this.IDATA.edgematch[M][0],
            u = this.IDATA.edgematch[M][1],
            u === "B")
                for (var x = 1; x < o; x++)
                    v.x = r - x * (a + s),
                    v.y = n + x * a,
                    y.x = -x * s,
                    y.y = x * (a + s),
                    A = v.x + "|" + v.y,
                    S = y.x + "|" + y.y,
                    I(M, l, A, S);
            if (u === "O")
                for (var x = 1; x < o; x++)
                    y.x = -x * s,
                    y.y = x * (a + s),
                    m.x = x * a,
                    m.y = x * s,
                    A = y.x + "|" + y.y,
                    S = m.x + "|" + m.y,
                    I(M, l, A, S);
            if (l = this.IDATA.edgematch[M][2],
            u = this.IDATA.edgematch[M][3],
            u && u === "A")
                for (var x = 1; x < o; x++)
                    m.x = x * a,
                    m.y = x * s,
                    v.x = r - (o - x) * (a + s),
                    v.y = n + (o - x) * a,
                    A = m.x + "|" + m.y,
                    S = v.x + "|" + v.y,
                    I(M, l, A, S);
            for (var x = 0; x < this.vertices.length; x++)
                A = this.vertices[x].x + "|" + this.vertices[x].y,
                T = M + "|" + A,
                T in t || (t[T] = e++,
                R[A][0] > 2 ? P[t[T]] = [-R[A][0], R[A][1], t[T]] : P[t[T]] = [b[R[A][0]], R[A][1], t[T]])
        }
        function I(w, O, D, F) {
            T = w + "|" + D,
            C = O + "|" + F,
            T in t || C in t ? T in t && !(C in t) ? t[C] = t[T] : C in t && !(T in t) && (t[T] = t[C]) : (t[T] = e,
            t[C] = e,
            e++),
            R[D][0] > 2 ? P[t[T]] = [-R[D][0], R[D][1], t[T]] : P[t[T]] = [b[R[D][0]], R[D][1], t[T]]
        }
        this.closestTo = P,
        this.vecToIdx = t
    }
    ,
    i.prototype.calcCoeffs = function() {
        var e = this.m
          , t = this.n
          , r = Math.sqrt(3) / 3
          , n = e * e + t * t + e * t;
        this.coau = (e + t) / n,
        this.cobu = -t / n,
        this.coav = -r * (e - t) / n,
        this.cobv = r * (2 * e + t) / n
    }
    ,
    i.prototype.createInnerFacets = function() {
        for (var e = this.m, t = this.n, r = 0; r < t + e + 1; r++)
            for (var n = this.min[r]; n < this.max[r] + 1; n++)
                n < this.max[r] && n < this.max[r + 1] + 1 && this.innerFacets.push(["|" + n + "|" + r, "|" + n + "|" + (r + 1), "|" + (n + 1) + "|" + r]),
                r > 0 && n < this.max[r - 1] && n + 1 < this.max[r] + 1 && this.innerFacets.push(["|" + n + "|" + r, "|" + (n + 1) + "|" + r, "|" + (n + 1) + "|" + (r - 1)])
    }
    ,
    i.prototype.edgeVecsABOB = function() {
        for (var e = this.m, t = this.n, r = new _IsoVector(-t,e + t), n = 1; n < e + t; n++) {
            var o = new _IsoVector(this.min[n],n)
              , a = new _IsoVector(this.min[n - 1],n - 1)
              , s = new _IsoVector(this.min[n + 1],n + 1)
              , l = o.clone()
              , u = a.clone()
              , c = s.clone();
            l.rotate60About(r),
            u.rotate60About(r),
            c.rotate60About(r);
            var h = new _IsoVector(this.max[l.y],l.y)
              , f = new _IsoVector(this.max[l.y - 1],l.y - 1)
              , d = new _IsoVector(this.max[l.y - 1] - 1,l.y - 1);
            (l.x !== h.x || l.y !== h.y) && (l.x !== f.x ? (this.vertexTypes.push([1, 0, 0]),
            this.isoVecsABOB.push([o, f, d]),
            this.vertexTypes.push([1, 0, 0]),
            this.isoVecsABOB.push([o, d, h])) : l.y === c.y ? (this.vertexTypes.push([1, 1, 0]),
            this.isoVecsABOB.push([o, a, f]),
            this.vertexTypes.push([1, 0, 1]),
            this.isoVecsABOB.push([o, f, s])) : (this.vertexTypes.push([1, 1, 0]),
            this.isoVecsABOB.push([o, a, f]),
            this.vertexTypes.push([1, 0, 0]),
            this.isoVecsABOB.push([o, f, h])))
        }
    }
    ,
    i.prototype.mapABOBtoOBOA = function() {
        for (var e = new _IsoVector(0,0), t = 0; t < this.isoVecsABOB.length; t++) {
            for (var r = [], n = 0; n < 3; n++)
                e.x = this.isoVecsABOB[t][n].x,
                e.y = this.isoVecsABOB[t][n].y,
                this.vertexTypes[t][n] === 0 && e.rotateNeg120(this.m, this.n),
                r.push(e.clone());
            this.isoVecsOBOA.push(r)
        }
    }
    ,
    i.prototype.mapABOBtoBAOA = function() {
        for (var e = new _IsoVector(0,0), t = 0; t < this.isoVecsABOB.length; t++) {
            for (var r = [], n = 0; n < 3; n++)
                e.x = this.isoVecsABOB[t][n].x,
                e.y = this.isoVecsABOB[t][n].y,
                this.vertexTypes[t][n] === 1 && e.rotate120(this.m, this.n),
                r.push(e.clone());
            this.isoVecsBAOA.push(r)
        }
    }
    ,
    i.prototype.MapToFace = function(e, t) {
        for (var r = this.IDATA.face[e], n = r[2], o = r[1], a = r[0], s = Vector3.FromArray(this.IDATA.vertex[n]), l = Vector3.FromArray(this.IDATA.vertex[o]), u = Vector3.FromArray(this.IDATA.vertex[a]), c = l.subtract(s), h = u.subtract(s), f = c.scale(this.coau).add(h.scale(this.cobu)), d = c.scale(this.coav).add(h.scale(this.cobv)), _ = [], g, m = TmpVectors.Vector3[0], v = 0; v < this.cartesian.length; v++)
            m = f.scale(this.cartesian[v].x).add(d.scale(this.cartesian[v].y)).add(s),
            _[v] = [m.x, m.y, m.z],
            g = e + "|" + this.vertices[v].x + "|" + this.vertices[v].y,
            t.vertex[this.vecToIdx[g]] = [m.x, m.y, m.z]
    }
    ,
    i.prototype.build = function(e, t) {
        var r = new Array
          , n = _IsoVector.Zero()
          , o = new _IsoVector(e,t)
          , a = new _IsoVector(-t,e + t);
        r.push(n, o, a);
        for (var s = t; s < e + 1; s++)
            for (var l = 0; l < e + 1 - s; l++)
                r.push(new _IsoVector(l,s));
        if (t > 0) {
            for (var u = Scalar.HCF(e, t), c = e / u, h = t / u, f = 1; f < u; f++)
                r.push(new _IsoVector(f * c,f * h)),
                r.push(new _IsoVector(-f * h,f * (c + h))),
                r.push(new _IsoVector(e - f * (c + h),t + f * c));
            for (var d = e / t, _ = 1; _ < t; _++)
                for (var g = 0; g < _ * d; g++)
                    r.push(new _IsoVector(g,_)),
                    r.push(new _IsoVector(g,_).rotate120(e, t)),
                    r.push(new _IsoVector(g,_).rotateNeg120(e, t))
        }
        r.sort(function(D, F) {
            return D.x - F.x
        }),
        r.sort(function(D, F) {
            return D.y - F.y
        });
        for (var m = new Array(e + t + 1), v = new Array(e + t + 1), f = 0; f < m.length; f++)
            m[f] = 1 / 0,
            v[f] = -1 / 0;
        for (var y = 0, b = 0, T = r.length, f = 0; f < T; f++)
            b = r[f].x,
            y = r[f].y,
            m[y] = Math.min(b, m[y]),
            v[y] = Math.max(b, v[y]);
        for (var C = function(D, F) {
            var V = D.clone();
            return F === "A" && V.rotateNeg120(e, t),
            F === "B" && V.rotate120(e, t),
            V.x < 0 ? V.y : V.x + V.y
        }, A = [], S = [], P = [], R = [], M = {}, x = [], I = -1, w = -1, f = 0; f < T; f++)
            A[f] = r[f].toCartesianOrigin(new _IsoVector(0,0), .5),
            S[f] = C(r[f], "O"),
            P[f] = C(r[f], "A"),
            R[f] = C(r[f], "B"),
            S[f] === P[f] && P[f] === R[f] ? (I = 3,
            w = S[f]) : S[f] === P[f] ? (I = 4,
            w = S[f]) : P[f] === R[f] ? (I = 5,
            w = P[f]) : R[f] === S[f] && (I = 6,
            w = S[f]),
            S[f] < P[f] && S[f] < R[f] && (I = 2,
            w = S[f]),
            P[f] < S[f] && P[f] < R[f] && (I = 1,
            w = P[f]),
            R[f] < P[f] && R[f] < S[f] && (I = 0,
            w = R[f]),
            x.push([I, w, r[f].x, r[f].y]);
        x.sort(function(D, F) {
            return D[2] - F[2]
        }),
        x.sort(function(D, F) {
            return D[3] - F[3]
        }),
        x.sort(function(D, F) {
            return D[1] - F[1]
        }),
        x.sort(function(D, F) {
            return D[0] - F[0]
        });
        for (var O = 0; O < x.length; O++)
            M[x[O][2] + "|" + x[O][3]] = [x[O][0], x[O][1], O];
        return this.m = e,
        this.n = t,
        this.vertices = r,
        this.vertByDist = M,
        this.cartesian = A,
        this.min = m,
        this.max = v,
        this
    }
    ,
    i
}()
  , PolyhedronData = function() {
    function i(e, t, r, n) {
        this.name = e,
        this.category = t,
        this.vertex = r,
        this.face = n
    }
    return i
}()
  , GeodesicData = function(i) {
    __extends(e, i);
    function e() {
        return i !== null && i.apply(this, arguments) || this
    }
    return e.prototype.innerToData = function(t, r) {
        for (var n = 0; n < r.innerFacets.length; n++)
            this.face.push(r.innerFacets[n].map(function(o) {
                return r.vecToIdx[t + o]
            }))
    }
    ,
    e.prototype.mapABOBtoDATA = function(t, r) {
        for (var n = r.IDATA.edgematch[t][0], o = 0; o < r.isoVecsABOB.length; o++) {
            for (var a = [], s = 0; s < 3; s++)
                r.vertexTypes[o][s] === 0 ? a.push(t + "|" + r.isoVecsABOB[o][s].x + "|" + r.isoVecsABOB[o][s].y) : a.push(n + "|" + r.isoVecsABOB[o][s].x + "|" + r.isoVecsABOB[o][s].y);
            this.face.push([r.vecToIdx[a[0]], r.vecToIdx[a[1]], r.vecToIdx[a[2]]])
        }
    }
    ,
    e.prototype.mapOBOAtoDATA = function(t, r) {
        for (var n = r.IDATA.edgematch[t][0], o = 0; o < r.isoVecsOBOA.length; o++) {
            for (var a = [], s = 0; s < 3; s++)
                r.vertexTypes[o][s] === 1 ? a.push(t + "|" + r.isoVecsOBOA[o][s].x + "|" + r.isoVecsOBOA[o][s].y) : a.push(n + "|" + r.isoVecsOBOA[o][s].x + "|" + r.isoVecsOBOA[o][s].y);
            this.face.push([r.vecToIdx[a[0]], r.vecToIdx[a[1]], r.vecToIdx[a[2]]])
        }
    }
    ,
    e.prototype.mapBAOAtoDATA = function(t, r) {
        for (var n = r.IDATA.edgematch[t][2], o = 0; o < r.isoVecsBAOA.length; o++) {
            for (var a = [], s = 0; s < 3; s++)
                r.vertexTypes[o][s] === 1 ? a.push(t + "|" + r.isoVecsBAOA[o][s].x + "|" + r.isoVecsBAOA[o][s].y) : a.push(n + "|" + r.isoVecsBAOA[o][s].x + "|" + r.isoVecsBAOA[o][s].y);
            this.face.push([r.vecToIdx[a[0]], r.vecToIdx[a[1]], r.vecToIdx[a[2]]])
        }
    }
    ,
    e.prototype.orderData = function(t) {
        for (var r = [], n = 0; n < 13; n++)
            r[n] = [];
        for (var o = t.closestTo, n = 0; n < o.length; n++)
            o[n][0] > -1 ? o[n][1] > 0 && r[o[n][0]].push([n, o[n][1]]) : r[12].push([n, o[n][0]]);
        for (var a = [], n = 0; n < 12; n++)
            a[n] = n;
        for (var s = 12, n = 0; n < 12; n++) {
            r[n].sort(function(c, h) {
                return c[1] - h[1]
            });
            for (var l = 0; l < r[n].length; l++)
                a[r[n][l][0]] = s++
        }
        for (var l = 0; l < r[12].length; l++)
            a[r[12][l][0]] = s++;
        for (var n = 0; n < this.vertex.length; n++)
            this.vertex[n].push(a[n]);
        this.vertex.sort(function(u, c) {
            return u[3] - c[3]
        });
        for (var n = 0; n < this.vertex.length; n++)
            this.vertex[n].pop();
        for (var n = 0; n < this.face.length; n++)
            for (var l = 0; l < this.face[n].length; l++)
                this.face[n][l] = a[this.face[n][l]];
        this.sharedNodes = r[12].length,
        this.poleNodes = this.vertex.length - this.sharedNodes
    }
    ,
    e.prototype.setOrder = function(t, r) {
        var n = []
          , o = []
          , a = r.pop();
        o.push(a);
        var s = this.face[a].indexOf(t);
        s = (s + 2) % 3;
        var l = this.face[a][s];
        n.push(l);
        for (var u = 0; r.length > 0; )
            a = r[u],
            this.face[a].indexOf(l) > -1 ? (s = (this.face[a].indexOf(l) + 1) % 3,
            l = this.face[a][s],
            n.push(l),
            o.push(a),
            r.splice(u, 1),
            u = 0) : u++;
        return this.adjacentFaces.push(n),
        o
    }
    ,
    e.prototype.toGoldbergData = function() {
        var t = this
          , r = new PolyhedronData("GeoDual","Goldberg",[],[]);
        r.name = "GD dual";
        for (var n = this.vertex.length, o = new Array(n), a = 0; a < n; a++)
            o[a] = [];
        for (var s = 0; s < this.face.length; s++)
            for (var l = 0; l < 3; l++)
                o[this.face[s][l]].push(s);
        var u = 0
          , c = 0
          , h = 0
          , f = []
          , d = [];
        this.adjacentFaces = [];
        for (var _ = 0; _ < o.length; _++)
            r.face[_] = this.setOrder(_, o[_].concat([])),
            o[_].forEach(function(g) {
                u = 0,
                c = 0,
                h = 0,
                f = t.face[g];
                for (var m = 0; m < 3; m++)
                    d = t.vertex[f[m]],
                    u += d[0],
                    c += d[1],
                    h += d[2];
                r.vertex[g] = [u / 3, c / 3, h / 3]
            });
        return r
    }
    ,
    e.BuildGeodesicData = function(t) {
        var r = new e("Geodesic-m-n","Geodesic",[[0, PHI, -1], [-PHI, 1, 0], [-1, 0, -PHI], [1, 0, -PHI], [PHI, 1, 0], [0, PHI, 1], [-1, 0, PHI], [-PHI, -1, 0], [0, -PHI, -1], [PHI, -1, 0], [1, 0, PHI], [0, -PHI, 1]],[]);
        t.setIndices(),
        t.calcCoeffs(),
        t.createInnerFacets(),
        t.edgeVecsABOB(),
        t.mapABOBtoOBOA(),
        t.mapABOBtoBAOA();
        for (var n = 0; n < t.IDATA.face.length; n++)
            t.MapToFace(n, r),
            r.innerToData(n, t),
            t.IDATA.edgematch[n][1] === "B" && r.mapABOBtoDATA(n, t),
            t.IDATA.edgematch[n][1] === "O" && r.mapOBOAtoDATA(n, t),
            t.IDATA.edgematch[n][3] === "A" && r.mapBAOAtoDATA(n, t);
        r.orderData(t);
        var o = 1;
        return r.vertex = r.vertex.map(function(a) {
            var s = a[0]
              , l = a[1]
              , u = a[2]
              , c = Math.sqrt(s * s + l * l + u * u);
            return a[0] *= o / c,
            a[1] *= o / c,
            a[2] *= o / c,
            a
        }),
        r
    }
    ,
    e
}(PolyhedronData);
function CreateGeodesic(i, e, t) {
    t === void 0 && (t = null);
    var r = e.m || 1;
    r !== Math.floor(r) && Logger$2.Warn("m not an integer only floor(m) used");
    var n = e.n || 0;
    if (n !== Math.floor(n) && Logger$2.Warn("n not an integer only floor(n) used"),
    n > r) {
        var o = n;
        n = r,
        r = o,
        Logger$2.Warn("n > m therefore m and n swapped")
    }
    var a = new _PrimaryIsoTriangle;
    a.build(r, n);
    var s = GeodesicData.BuildGeodesicData(a)
      , l = {
        custom: s,
        size: e.size,
        sizeX: e.sizeX,
        sizeY: e.sizeY,
        sizeZ: e.sizeZ,
        faceUV: e.faceUV,
        faceColors: e.faceColors,
        flat: e.flat,
        updatable: e.updatable,
        sideOrientation: e.sideOrientation,
        frontUVs: e.frontUVs,
        backUVs: e.backUVs
    }
      , u = CreatePolyhedron(i, l, t);
    return u
}
function CreateGoldbergVertexData(i, e) {
    for (var t = i.size, r = i.sizeX || t || 1, n = i.sizeY || t || 1, o = i.sizeZ || t || 1, a = i.sideOrientation === 0 ? 0 : i.sideOrientation || VertexData.DEFAULTSIDE, s = new Array, l = new Array, u = new Array, c = new Array, h = 1 / 0, f = -1 / 0, d = 1 / 0, _ = -1 / 0, g = 0; g < e.vertex.length; g++)
        h = Math.min(h, e.vertex[g][0] * r),
        f = Math.max(f, e.vertex[g][0] * r),
        d = Math.min(d, e.vertex[g][1] * n),
        _ = Math.max(_, e.vertex[g][1] * n);
    for (var m = 0, v = 0; v < e.face.length; v++) {
        for (var y = e.face[v], b = Vector3.FromArray(e.vertex[y[0]]), T = Vector3.FromArray(e.vertex[y[2]]), C = Vector3.FromArray(e.vertex[y[1]]), A = T.subtract(b), S = C.subtract(b), P = Vector3.Cross(S, A).normalize(), g = 0; g < y.length; g++) {
            u.push(P.x, P.y, P.z);
            var R = e.vertex[y[g]];
            s.push(R[0] * r, R[1] * n, R[2] * o),
            c.push((R[0] * r - h) / (f - h), (R[1] * n - d) / (_ - d))
        }
        for (var g = 0; g < y.length - 2; g++)
            l.push(m, m + g + 2, m + g + 1);
        m += y.length
    }
    VertexData._ComputeSides(a, s, l, u, c);
    var M = new VertexData;
    return M.positions = s,
    M.indices = l,
    M.normals = u,
    M.uvs = c,
    M
}
function CreateGoldberg(i, e, t) {
    var r = e.m || 1;
    r !== Math.floor(r) && Logger$2.Warn("m not an integer only floor(m) used");
    var n = e.n || 0;
    if (n !== Math.floor(n) && Logger$2.Warn("n not an integer only floor(n) used"),
    n > r) {
        var o = n;
        n = r,
        r = o,
        Logger$2.Warn("n > m therefore m and n swapped")
    }
    var a = new _PrimaryIsoTriangle;
    a.build(r, n);
    var s = GeodesicData.BuildGeodesicData(a)
      , l = s.toGoldbergData()
      , u = new GoldbergMesh(i);
    e.sideOrientation = Mesh._GetDefaultSideOrientation(e.sideOrientation),
    u._originalBuilderSideOrientation = e.sideOrientation;
    var c = CreateGoldbergVertexData(e, l);
    c.applyToMesh(u, e.updatable),
    u.nbSharedFaces = s.sharedNodes,
    u.nbUnsharedFaces = s.poleNodes,
    u.adjacentFaces = s.adjacentFaces,
    u.nbFaces = u.nbSharedFaces + u.nbUnsharedFaces,
    u.nbFacesAtPole = (u.nbUnsharedFaces - 12) / 12;
    for (var h = 0; h < s.vertex.length; h++)
        u.faceCenters.push(Vector3.FromArray(s.vertex[h])),
        u.faceColors.push(new Color4(1,1,1,1));
    for (var h = 0; h < l.face.length; h++) {
        var f = l.face[h]
          , d = Vector3.FromArray(l.vertex[f[0]])
          , _ = Vector3.FromArray(l.vertex[f[2]])
          , g = Vector3.FromArray(l.vertex[f[1]])
          , m = _.subtract(d)
          , v = g.subtract(d)
          , y = Vector3.Cross(v, m).normalize()
          , b = Vector3.Cross(v, y).normalize();
        u.faceXaxis.push(v.normalize()),
        u.faceYaxis.push(y),
        u.faceZaxis.push(b)
    }
    return u.setMetadata(),
    u
}
function GoldbergCreate(i) {
    return function(e) {
        __extends(t, e);
        function t() {
            var r = e !== null && e.apply(this, arguments) || this;
            return r.faceColors = [],
            r.faceCenters = [],
            r.faceZaxis = [],
            r.faceXaxis = [],
            r.faceYaxis = [],
            r
        }
        return t.prototype.setMetadata = function() {
            this.metadata = {
                nbSharedFaces: this.nbSharedFaces,
                nbUnsharedFaces: this.nbUnsharedFaces,
                nbFacesAtPole: this.nbFacesAtPole,
                nbFaces: this.nbFaces,
                faceCenters: this.faceCenters,
                faceXaxis: this.faceXaxis,
                faceYaxis: this.faceYaxis,
                faceZaxis: this.faceZaxis,
                adjacentFaces: this.adjacentFaces
            }
        }
        ,
        t.prototype.relFace = function(r, n) {
            return n === void 0 ? (r > this.nbUnsharedFaces - 1 && (Logger$2.Warn("Maximum number of unshared faces used"),
            r = this.nbUnsharedFaces - 1),
            this.nbUnsharedFaces + r) : (r > 11 && (Logger$2.Warn("Last pole used"),
            r = 11),
            n > this.nbFacesAtPole - 1 && (Logger$2.Warn("Maximum number of faces at a pole used"),
            n = this.nbFacesAtPole - 1),
            12 + r * this.nbFacesAtPole + n)
        }
        ,
        t.prototype.refreshFaceData = function() {
            this.nbSharedFaces = this.metadata.nbSharedFaces,
            this.nbUnsharedFaces = this.metadata.nbUnsharedFaces,
            this.nbFacesAtPole = this.metadata.nbFacesAtPole,
            this.adjacentFaces = this.metadata.adjacentFaces,
            this.nbFaces = this.metadata.nbFaces,
            this.faceCenters = this.metadata.faceCenters,
            this.faceXaxis = this.metadata.faceXaxis,
            this.faceYaxis = this.metadata.faceYaxis,
            this.faceZaxis = this.metadata.faceZaxis
        }
        ,
        t.prototype.changeFaceColors = function(r) {
            for (var n = 0; n < r.length; n++)
                for (var o = r[n][0], a = r[n][1], s = r[n][2], l = o; l < a + 1; l++)
                    this.faceColors[l] = s;
            for (var u = [], l = 0; l < 12; l++)
                for (var n = 0; n < 5; n++)
                    u.push(this.faceColors[l].r, this.faceColors[l].g, this.faceColors[l].b, this.faceColors[l].a);
            for (var l = 12; l < this.faceColors.length; l++)
                for (var n = 0; n < 6; n++)
                    u.push(this.faceColors[l].r, this.faceColors[l].g, this.faceColors[l].b, this.faceColors[l].a);
            return u
        }
        ,
        t.prototype.setFaceColors = function(r) {
            var n = this.changeFaceColors(r);
            this.setVerticesData(VertexBuffer.ColorKind, n)
        }
        ,
        t.prototype.updateFaceColors = function(r) {
            var n = this.changeFaceColors(r);
            this.updateVerticesData(VertexBuffer.ColorKind, n)
        }
        ,
        t.prototype.changeFaceUVs = function(r) {
            for (var n = this.getVerticesData(VertexBuffer.UVKind), o = 0; o < r.length; o++) {
                for (var a = r[o][0], s = r[o][1], l = r[o][2], u = r[o][3], c = r[o][4], h = [], f = [], d = void 0, _ = void 0, g = 0; g < 5; g++)
                    d = l.x + u * Math.cos(c + g * Math.PI / 2.5),
                    _ = l.y + u * Math.sin(c + g * Math.PI / 2.5),
                    d < 0 && (d = 0),
                    d > 1 && (d = 1),
                    h.push(d, _);
                for (var g = 0; g < 6; g++)
                    d = l.x + u * Math.cos(c + g * Math.PI / 3),
                    _ = l.y + u * Math.sin(c + g * Math.PI / 3),
                    d < 0 && (d = 0),
                    d > 1 && (d = 1),
                    f.push(d, _);
                for (var m = a; m < Math.min(12, s + 1); m++)
                    for (var g = 0; g < 5; g++)
                        n[10 * m + 2 * g] = h[2 * g],
                        n[10 * m + 2 * g + 1] = h[2 * g + 1];
                for (var m = Math.max(12, a); m < s + 1; m++)
                    for (var g = 0; g < 6; g++)
                        n[12 * m - 24 + 2 * g] = f[2 * g],
                        n[12 * m - 23 + 2 * g] = f[2 * g + 1]
            }
            return n
        }
        ,
        t.prototype.setFaceUVs = function(r) {
            var n = this.changeFaceUVs(r);
            this.setVerticesData(VertexBuffer.UVKind, n)
        }
        ,
        t.prototype.updateFaceUVs = function(r) {
            var n = this.changeFaceUVs(r);
            this.updateVerticesData(VertexBuffer.UVKind, n)
        }
        ,
        t.prototype.placeOnFaceAt = function(r, n, o) {
            var a = Vector3.RotationFromAxis(this.faceXaxis[n], this.faceYaxis[n], this.faceZaxis[n]);
            r.rotation = a,
            r.position = this.faceCenters[n].add(this.faceXaxis[n].scale(o.x)).add(this.faceYaxis[n].scale(o.y)).add(this.faceZaxis[n].scale(o.z))
        }
        ,
        t
    }(i)
}
var GoldbergMesh = GoldbergCreate(Mesh)
  , MeshBuilder = {
    CreateBox,
    CreateTiledBox,
    CreateSphere,
    CreateDisc,
    CreateIcoSphere,
    CreateRibbon,
    CreateCylinder,
    CreateTorus,
    CreateTorusKnot,
    CreateLineSystem,
    CreateLines,
    CreateDashedLines,
    ExtrudeShape,
    ExtrudeShapeCustom,
    CreateLathe,
    CreateTiledPlane,
    CreatePlane,
    CreateGround,
    CreateTiledGround,
    CreateGroundFromHeightMap,
    CreatePolygon,
    ExtrudePolygon,
    CreateTube,
    CreatePolyhedron,
    CreateGeodesic,
    CreateGoldberg,
    CreateDecal,
    CreateCapsule
}
  , Ray = function() {
    function i(e, t, r) {
        r === void 0 && (r = Number.MAX_VALUE),
        this.origin = e,
        this.direction = t,
        this.length = r
    }
    return i.prototype.clone = function() {
        return new i(this.origin.clone(),this.direction.clone(),this.length)
    }
    ,
    i.prototype.intersectsBoxMinMax = function(e, t, r) {
        r === void 0 && (r = 0);
        var n = i._TmpVector3[0].copyFromFloats(e.x - r, e.y - r, e.z - r), o = i._TmpVector3[1].copyFromFloats(t.x + r, t.y + r, t.z + r), a = 0, s = Number.MAX_VALUE, l, u, c, h;
        if (Math.abs(this.direction.x) < 1e-7) {
            if (this.origin.x < n.x || this.origin.x > o.x)
                return !1
        } else if (l = 1 / this.direction.x,
        u = (n.x - this.origin.x) * l,
        c = (o.x - this.origin.x) * l,
        c === -1 / 0 && (c = 1 / 0),
        u > c && (h = u,
        u = c,
        c = h),
        a = Math.max(u, a),
        s = Math.min(c, s),
        a > s)
            return !1;
        if (Math.abs(this.direction.y) < 1e-7) {
            if (this.origin.y < n.y || this.origin.y > o.y)
                return !1
        } else if (l = 1 / this.direction.y,
        u = (n.y - this.origin.y) * l,
        c = (o.y - this.origin.y) * l,
        c === -1 / 0 && (c = 1 / 0),
        u > c && (h = u,
        u = c,
        c = h),
        a = Math.max(u, a),
        s = Math.min(c, s),
        a > s)
            return !1;
        if (Math.abs(this.direction.z) < 1e-7) {
            if (this.origin.z < n.z || this.origin.z > o.z)
                return !1
        } else if (l = 1 / this.direction.z,
        u = (n.z - this.origin.z) * l,
        c = (o.z - this.origin.z) * l,
        c === -1 / 0 && (c = 1 / 0),
        u > c && (h = u,
        u = c,
        c = h),
        a = Math.max(u, a),
        s = Math.min(c, s),
        a > s)
            return !1;
        return !0
    }
    ,
    i.prototype.intersectsBox = function(e, t) {
        return t === void 0 && (t = 0),
        this.intersectsBoxMinMax(e.minimum, e.maximum, t)
    }
    ,
    i.prototype.intersectsSphere = function(e, t) {
        t === void 0 && (t = 0);
        var r = e.center.x - this.origin.x
          , n = e.center.y - this.origin.y
          , o = e.center.z - this.origin.z
          , a = r * r + n * n + o * o
          , s = e.radius + t
          , l = s * s;
        if (a <= l)
            return !0;
        var u = r * this.direction.x + n * this.direction.y + o * this.direction.z;
        if (u < 0)
            return !1;
        var c = a - u * u;
        return c <= l
    }
    ,
    i.prototype.intersectsTriangle = function(e, t, r) {
        var n = i._TmpVector3[0]
          , o = i._TmpVector3[1]
          , a = i._TmpVector3[2]
          , s = i._TmpVector3[3]
          , l = i._TmpVector3[4];
        t.subtractToRef(e, n),
        r.subtractToRef(e, o),
        Vector3.CrossToRef(this.direction, o, a);
        var u = Vector3.Dot(n, a);
        if (u === 0)
            return null;
        var c = 1 / u;
        this.origin.subtractToRef(e, s);
        var h = Vector3.Dot(s, a) * c;
        if (h < 0 || h > 1)
            return null;
        Vector3.CrossToRef(s, n, l);
        var f = Vector3.Dot(this.direction, l) * c;
        if (f < 0 || h + f > 1)
            return null;
        var d = Vector3.Dot(o, l) * c;
        return d > this.length ? null : new IntersectionInfo(1 - h - f,h,d)
    }
    ,
    i.prototype.intersectsPlane = function(e) {
        var t, r = Vector3.Dot(e.normal, this.direction);
        if (Math.abs(r) < 999999997475243e-21)
            return null;
        var n = Vector3.Dot(e.normal, this.origin);
        return t = (-e.d - n) / r,
        t < 0 ? t < -999999997475243e-21 ? null : 0 : t
    }
    ,
    i.prototype.intersectsAxis = function(e, t) {
        switch (t === void 0 && (t = 0),
        e) {
        case "y":
            var r = (this.origin.y - t) / this.direction.y;
            return r > 0 ? null : new Vector3(this.origin.x + this.direction.x * -r,t,this.origin.z + this.direction.z * -r);
        case "x":
            var r = (this.origin.x - t) / this.direction.x;
            return r > 0 ? null : new Vector3(t,this.origin.y + this.direction.y * -r,this.origin.z + this.direction.z * -r);
        case "z":
            var r = (this.origin.z - t) / this.direction.z;
            return r > 0 ? null : new Vector3(this.origin.x + this.direction.x * -r,this.origin.y + this.direction.y * -r,t);
        default:
            return null
        }
    }
    ,
    i.prototype.intersectsMesh = function(e, t) {
        var r = TmpVectors.Matrix[0];
        return e.getWorldMatrix().invertToRef(r),
        this._tmpRay ? i.TransformToRef(this, r, this._tmpRay) : this._tmpRay = i.Transform(this, r),
        e.intersects(this._tmpRay, t)
    }
    ,
    i.prototype.intersectsMeshes = function(e, t, r) {
        r ? r.length = 0 : r = [];
        for (var n = 0; n < e.length; n++) {
            var o = this.intersectsMesh(e[n], t);
            o.hit && r.push(o)
        }
        return r.sort(this._comparePickingInfo),
        r
    }
    ,
    i.prototype._comparePickingInfo = function(e, t) {
        return e.distance < t.distance ? -1 : e.distance > t.distance ? 1 : 0
    }
    ,
    i.prototype.intersectionSegment = function(e, t, r) {
        var n = this.origin
          , o = TmpVectors.Vector3[0]
          , a = TmpVectors.Vector3[1]
          , s = TmpVectors.Vector3[2]
          , l = TmpVectors.Vector3[3];
        t.subtractToRef(e, o),
        this.direction.scaleToRef(i.rayl, s),
        n.addToRef(s, a),
        e.subtractToRef(n, l);
        var u = Vector3.Dot(o, o), c = Vector3.Dot(o, s), h = Vector3.Dot(s, s), f = Vector3.Dot(o, l), d = Vector3.Dot(s, l), _ = u * h - c * c, g, m, v = _, y, b, T = _;
        _ < i.smallnum ? (m = 0,
        v = 1,
        b = d,
        T = h) : (m = c * d - h * f,
        b = u * d - c * f,
        m < 0 ? (m = 0,
        b = d,
        T = h) : m > v && (m = v,
        b = d + c,
        T = h)),
        b < 0 ? (b = 0,
        -f < 0 ? m = 0 : -f > u ? m = v : (m = -f,
        v = u)) : b > T && (b = T,
        -f + c < 0 ? m = 0 : -f + c > u ? m = v : (m = -f + c,
        v = u)),
        g = Math.abs(m) < i.smallnum ? 0 : m / v,
        y = Math.abs(b) < i.smallnum ? 0 : b / T;
        var C = TmpVectors.Vector3[4];
        s.scaleToRef(y, C);
        var A = TmpVectors.Vector3[5];
        o.scaleToRef(g, A),
        A.addInPlace(l);
        var S = TmpVectors.Vector3[6];
        A.subtractToRef(C, S);
        var P = y > 0 && y <= this.length && S.lengthSquared() < r * r;
        return P ? A.length() : -1
    }
    ,
    i.prototype.update = function(e, t, r, n, o, a, s) {
        return this.unprojectRayToRef(e, t, r, n, o, a, s),
        this
    }
    ,
    i.Zero = function() {
        return new i(Vector3.Zero(),Vector3.Zero())
    }
    ,
    i.CreateNew = function(e, t, r, n, o, a, s) {
        var l = i.Zero();
        return l.update(e, t, r, n, o, a, s)
    }
    ,
    i.CreateNewFromTo = function(e, t, r) {
        r === void 0 && (r = Matrix.IdentityReadOnly);
        var n = t.subtract(e)
          , o = Math.sqrt(n.x * n.x + n.y * n.y + n.z * n.z);
        return n.normalize(),
        i.Transform(new i(e,n,o), r)
    }
    ,
    i.Transform = function(e, t) {
        var r = new i(new Vector3(0,0,0),new Vector3(0,0,0));
        return i.TransformToRef(e, t, r),
        r
    }
    ,
    i.TransformToRef = function(e, t, r) {
        Vector3.TransformCoordinatesToRef(e.origin, t, r.origin),
        Vector3.TransformNormalToRef(e.direction, t, r.direction),
        r.length = e.length;
        var n = r.direction
          , o = n.length();
        if (!(o === 0 || o === 1)) {
            var a = 1 / o;
            n.x *= a,
            n.y *= a,
            n.z *= a,
            r.length *= o
        }
    }
    ,
    i.prototype.unprojectRayToRef = function(e, t, r, n, o, a, s) {
        var l = TmpVectors.Matrix[0];
        o.multiplyToRef(a, l),
        l.multiplyToRef(s, l),
        l.invert();
        var u = TmpVectors.Vector3[0];
        u.x = e / r * 2 - 1,
        u.y = -(t / n * 2 - 1),
        u.z = -1;
        var c = TmpVectors.Vector3[1].copyFromFloats(u.x, u.y, 1)
          , h = TmpVectors.Vector3[2]
          , f = TmpVectors.Vector3[3];
        Vector3._UnprojectFromInvertedMatrixToRef(u, l, h),
        Vector3._UnprojectFromInvertedMatrixToRef(c, l, f),
        this.origin.copyFrom(h),
        f.subtractToRef(h, this.direction),
        this.direction.normalize()
    }
    ,
    i._TmpVector3 = ArrayTools.BuildArray(6, Vector3.Zero),
    i.smallnum = 1e-8,
    i.rayl = 1e9,
    i
}();
Scene.prototype.createPickingRay = function(i, e, t, r, n) {
    n === void 0 && (n = !1);
    var o = Ray.Zero();
    return this.createPickingRayToRef(i, e, t, o, r, n),
    o
}
;
Scene.prototype.createPickingRayToRef = function(i, e, t, r, n, o) {
    o === void 0 && (o = !1);
    var a = this.getEngine();
    if (!n) {
        if (!this.activeCamera)
            return this;
        n = this.activeCamera
    }
    var s = n.viewport
      , l = s.toGlobal(a.getRenderWidth(), a.getRenderHeight());
    return i = i / a.getHardwareScalingLevel() - l.x,
    e = e / a.getHardwareScalingLevel() - (a.getRenderHeight() - l.y - l.height),
    r.update(i, e, l.width, l.height, t || Matrix.IdentityReadOnly, o ? Matrix.IdentityReadOnly : n.getViewMatrix(), n.getProjectionMatrix()),
    this
}
;
Scene.prototype.createPickingRayInCameraSpace = function(i, e, t) {
    var r = Ray.Zero();
    return this.createPickingRayInCameraSpaceToRef(i, e, r, t),
    r
}
;
Scene.prototype.createPickingRayInCameraSpaceToRef = function(i, e, t, r) {
    if (!PickingInfo)
        return this;
    var n = this.getEngine();
    if (!r) {
        if (!this.activeCamera)
            throw new Error("Active camera not set");
        r = this.activeCamera
    }
    var o = r.viewport
      , a = o.toGlobal(n.getRenderWidth(), n.getRenderHeight())
      , s = Matrix.Identity();
    return i = i / n.getHardwareScalingLevel() - a.x,
    e = e / n.getHardwareScalingLevel() - (n.getRenderHeight() - a.y - a.height),
    t.update(i, e, a.width, a.height, s, s, r.getProjectionMatrix()),
    this
}
;
Scene.prototype._internalPickForMesh = function(i, e, t, r, n, o, a, s) {
    var l = e(r)
      , u = t.intersects(l, n, a, o, r, s);
    return !u || !u.hit || !n && i != null && u.distance >= i.distance ? null : u
}
;
Scene.prototype._internalPick = function(i, e, t, r, n) {
    if (!PickingInfo)
        return null;
    for (var o = null, a = 0; a < this.meshes.length; a++) {
        var s = this.meshes[a];
        if (e) {
            if (!e(s))
                continue
        } else if (!s.isEnabled() || !s.isVisible || !s.isPickable)
            continue;
        var l = s.skeleton && s.skeleton.overrideMesh ? s.skeleton.overrideMesh.getWorldMatrix() : s.getWorldMatrix();
        if (s.hasThinInstances && s.thinInstanceEnablePicking) {
            var u = this._internalPickForMesh(o, i, s, l, !0, !0, n);
            if (u) {
                if (r)
                    return o;
                for (var c = TmpVectors.Matrix[1], h = s.thinInstanceGetWorldMatrices(), f = 0; f < h.length; f++) {
                    var d = h[f];
                    d.multiplyToRef(l, c);
                    var _ = this._internalPickForMesh(o, i, s, c, t, r, n, !0);
                    if (_ && (o = _,
                    o.thinInstanceIndex = f,
                    t))
                        return o
                }
            }
        } else {
            var u = this._internalPickForMesh(o, i, s, l, t, r, n);
            if (u && (o = u,
            t))
                return o
        }
    }
    return o || new PickingInfo
}
;
Scene.prototype._internalMultiPick = function(i, e, t) {
    if (!PickingInfo)
        return null;
    for (var r = new Array, n = 0; n < this.meshes.length; n++) {
        var o = this.meshes[n];
        if (e) {
            if (!e(o))
                continue
        } else if (!o.isEnabled() || !o.isVisible || !o.isPickable)
            continue;
        var a = o.skeleton && o.skeleton.overrideMesh ? o.skeleton.overrideMesh.getWorldMatrix() : o.getWorldMatrix();
        if (o.hasThinInstances && o.thinInstanceEnablePicking) {
            var s = this._internalPickForMesh(null, i, o, a, !0, !0, t);
            if (s)
                for (var l = TmpVectors.Matrix[1], u = o.thinInstanceGetWorldMatrices(), c = 0; c < u.length; c++) {
                    var h = u[c];
                    h.multiplyToRef(a, l);
                    var f = this._internalPickForMesh(null, i, o, l, !1, !1, t, !0);
                    f && (f.thinInstanceIndex = c,
                    r.push(f))
                }
        } else {
            var s = this._internalPickForMesh(null, i, o, a, !1, !1, t);
            s && r.push(s)
        }
    }
    return r
}
;
Scene.prototype.pickWithBoundingInfo = function(i, e, t, r, n) {
    var o = this;
    if (!PickingInfo)
        return null;
    var a = this._internalPick(function(s) {
        return o._tempPickingRay || (o._tempPickingRay = Ray.Zero()),
        o.createPickingRayToRef(i, e, s, o._tempPickingRay, n || null),
        o._tempPickingRay
    }, t, r, !0);
    return a && (a.ray = this.createPickingRay(i, e, Matrix.Identity(), n || null)),
    a
}
;
Scene.prototype.pick = function(i, e, t, r, n, o) {
    var a = this;
    if (!PickingInfo)
        return null;
    var s = this._internalPick(function(l) {
        return a._tempPickingRay || (a._tempPickingRay = Ray.Zero()),
        a.createPickingRayToRef(i, e, l, a._tempPickingRay, n || null),
        a._tempPickingRay
    }, t, r, !1, o);
    return s && (s.ray = this.createPickingRay(i, e, Matrix.Identity(), n || null)),
    s
}
;
Scene.prototype.pickWithRay = function(i, e, t, r) {
    var n = this
      , o = this._internalPick(function(a) {
        return n._pickWithRayInverseMatrix || (n._pickWithRayInverseMatrix = Matrix.Identity()),
        a.invertToRef(n._pickWithRayInverseMatrix),
        n._cachedRayForTransform || (n._cachedRayForTransform = Ray.Zero()),
        Ray.TransformToRef(i, n._pickWithRayInverseMatrix, n._cachedRayForTransform),
        n._cachedRayForTransform
    }, e, t, !1, r);
    return o && (o.ray = i),
    o
}
;
Scene.prototype.multiPick = function(i, e, t, r, n) {
    var o = this;
    return this._internalMultiPick(function(a) {
        return o.createPickingRay(i, e, a, r || null)
    }, t, n)
}
;
Scene.prototype.multiPickWithRay = function(i, e, t) {
    var r = this;
    return this._internalMultiPick(function(n) {
        return r._pickWithRayInverseMatrix || (r._pickWithRayInverseMatrix = Matrix.Identity()),
        n.invertToRef(r._pickWithRayInverseMatrix),
        r._cachedRayForTransform || (r._cachedRayForTransform = Ray.Zero()),
        Ray.TransformToRef(i, r._pickWithRayInverseMatrix, r._cachedRayForTransform),
        r._cachedRayForTransform
    }, e, t)
}
;
Camera$1.prototype.getForwardRay = function(i, e, t) {
    return i === void 0 && (i = 100),
    this.getForwardRayToRef(new Ray(Vector3.Zero(),Vector3.Zero(),i), i, e, t)
}
;
Camera$1.prototype.getForwardRayToRef = function(i, e, t, r) {
    return e === void 0 && (e = 100),
    t || (t = this.getWorldMatrix()),
    i.length = e,
    r ? i.origin.copyFrom(r) : i.origin.copyFrom(this.position),
    TmpVectors.Vector3[2].set(0, 0, this._scene.useRightHandedSystem ? -1 : 1),
    Vector3.TransformNormalToRef(TmpVectors.Vector3[2], t, TmpVectors.Vector3[3]),
    Vector3.NormalizeToRef(TmpVectors.Vector3[3], i.direction),
    i
}
;
var ColorGradient = function() {
    function i(e, t, r) {
        this.gradient = e,
        this.color1 = t,
        this.color2 = r
    }
    return i.prototype.getColorToRef = function(e) {
        if (!this.color2) {
            e.copyFrom(this.color1);
            return
        }
        Color4.LerpToRef(this.color1, this.color2, Math.random(), e)
    }
    ,
    i
}(), Color3Gradient = function() {
    function i(e, t) {
        this.gradient = e,
        this.color = t
    }
    return i
}(), FactorGradient = function() {
    function i(e, t, r) {
        this.gradient = e,
        this.factor1 = t,
        this.factor2 = r
    }
    return i.prototype.getFactor = function() {
        return this.factor2 === void 0 || this.factor2 === this.factor1 ? this.factor1 : this.factor1 + (this.factor2 - this.factor1) * Math.random()
    }
    ,
    i
}(), GradientHelper = function() {
    function i() {}
    return i.GetCurrentGradient = function(e, t, r) {
        if (t[0].gradient > e) {
            r(t[0], t[0], 1);
            return
        }
        for (var n = 0; n < t.length - 1; n++) {
            var o = t[n]
              , a = t[n + 1];
            if (e >= o.gradient && e <= a.gradient) {
                var s = (e - o.gradient) / (a.gradient - o.gradient);
                r(o, a, s);
                return
            }
        }
        var l = t.length - 1;
        r(t[l], t[l], 1)
    }
    ,
    i
}(), BoxParticleEmitter = function() {
    function i() {
        this.direction1 = new Vector3(0,1,0),
        this.direction2 = new Vector3(0,1,0),
        this.minEmitBox = new Vector3(-.5,-.5,-.5),
        this.maxEmitBox = new Vector3(.5,.5,.5)
    }
    return i.prototype.startDirectionFunction = function(e, t, r, n) {
        var o = Scalar.RandomRange(this.direction1.x, this.direction2.x)
          , a = Scalar.RandomRange(this.direction1.y, this.direction2.y)
          , s = Scalar.RandomRange(this.direction1.z, this.direction2.z);
        if (n) {
            t.x = o,
            t.y = a,
            t.z = s;
            return
        }
        Vector3.TransformNormalFromFloatsToRef(o, a, s, e, t)
    }
    ,
    i.prototype.startPositionFunction = function(e, t, r, n) {
        var o = Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x)
          , a = Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y)
          , s = Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
        if (n) {
            t.x = o,
            t.y = a,
            t.z = s;
            return
        }
        Vector3.TransformCoordinatesFromFloatsToRef(o, a, s, e, t)
    }
    ,
    i.prototype.clone = function() {
        var e = new i;
        return DeepCopier.DeepCopy(this, e),
        e
    }
    ,
    i.prototype.applyToShader = function(e) {
        e.setVector3("direction1", this.direction1),
        e.setVector3("direction2", this.direction2),
        e.setVector3("minEmitBox", this.minEmitBox),
        e.setVector3("maxEmitBox", this.maxEmitBox)
    }
    ,
    i.prototype.buildUniformLayout = function(e) {
        e.addUniform("direction1", 3),
        e.addUniform("direction2", 3),
        e.addUniform("minEmitBox", 3),
        e.addUniform("maxEmitBox", 3)
    }
    ,
    i.prototype.getEffectDefines = function() {
        return "#define BOXEMITTER"
    }
    ,
    i.prototype.getClassName = function() {
        return "BoxParticleEmitter"
    }
    ,
    i.prototype.serialize = function() {
        var e = {};
        return e.type = this.getClassName(),
        e.direction1 = this.direction1.asArray(),
        e.direction2 = this.direction2.asArray(),
        e.minEmitBox = this.minEmitBox.asArray(),
        e.maxEmitBox = this.maxEmitBox.asArray(),
        e
    }
    ,
    i.prototype.parse = function(e) {
        Vector3.FromArrayToRef(e.direction1, 0, this.direction1),
        Vector3.FromArrayToRef(e.direction2, 0, this.direction2),
        Vector3.FromArrayToRef(e.minEmitBox, 0, this.minEmitBox),
        Vector3.FromArrayToRef(e.maxEmitBox, 0, this.maxEmitBox)
    }
    ,
    i
}(), ConeParticleEmitter = function() {
    function i(e, t, r) {
        e === void 0 && (e = 1),
        t === void 0 && (t = Math.PI),
        r === void 0 && (r = 0),
        this.directionRandomizer = r,
        this.radiusRange = 1,
        this.heightRange = 1,
        this.emitFromSpawnPointOnly = !1,
        this.angle = t,
        this.radius = e
    }
    return Object.defineProperty(i.prototype, "radius", {
        get: function() {
            return this._radius
        },
        set: function(e) {
            this._radius = e,
            this._buildHeight()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "angle", {
        get: function() {
            return this._angle
        },
        set: function(e) {
            this._angle = e,
            this._buildHeight()
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype._buildHeight = function() {
        this._angle !== 0 ? this._height = this._radius / Math.tan(this._angle / 2) : this._height = 1
    }
    ,
    i.prototype.startDirectionFunction = function(e, t, r, n) {
        n ? TmpVectors.Vector3[0].copyFrom(r._localPosition).normalize() : r.position.subtractToRef(e.getTranslation(), TmpVectors.Vector3[0]).normalize();
        var o = Scalar.RandomRange(0, this.directionRandomizer)
          , a = Scalar.RandomRange(0, this.directionRandomizer)
          , s = Scalar.RandomRange(0, this.directionRandomizer);
        t.x = TmpVectors.Vector3[0].x + o,
        t.y = TmpVectors.Vector3[0].y + a,
        t.z = TmpVectors.Vector3[0].z + s,
        t.normalize()
    }
    ,
    i.prototype.startPositionFunction = function(e, t, r, n) {
        var o = Scalar.RandomRange(0, Math.PI * 2), a;
        this.emitFromSpawnPointOnly ? a = 1e-4 : (a = Scalar.RandomRange(0, this.heightRange),
        a = 1 - a * a);
        var s = this._radius - Scalar.RandomRange(0, this._radius * this.radiusRange);
        s = s * a;
        var l = s * Math.sin(o)
          , u = s * Math.cos(o)
          , c = a * this._height;
        if (n) {
            t.x = l,
            t.y = c,
            t.z = u;
            return
        }
        Vector3.TransformCoordinatesFromFloatsToRef(l, c, u, e, t)
    }
    ,
    i.prototype.clone = function() {
        var e = new i(this._radius,this._angle,this.directionRandomizer);
        return DeepCopier.DeepCopy(this, e),
        e
    }
    ,
    i.prototype.applyToShader = function(e) {
        e.setFloat2("radius", this._radius, this.radiusRange),
        e.setFloat("coneAngle", this._angle),
        e.setFloat2("height", this._height, this.heightRange),
        e.setFloat("directionRandomizer", this.directionRandomizer)
    }
    ,
    i.prototype.buildUniformLayout = function(e) {
        e.addUniform("radius", 2),
        e.addUniform("coneAngle", 1),
        e.addUniform("height", 2),
        e.addUniform("directionRandomizer", 1)
    }
    ,
    i.prototype.getEffectDefines = function() {
        var e = "#define CONEEMITTER";
        return this.emitFromSpawnPointOnly && (e += `
#define CONEEMITTERSPAWNPOINT`),
        e
    }
    ,
    i.prototype.getClassName = function() {
        return "ConeParticleEmitter"
    }
    ,
    i.prototype.serialize = function() {
        var e = {};
        return e.type = this.getClassName(),
        e.radius = this._radius,
        e.angle = this._angle,
        e.directionRandomizer = this.directionRandomizer,
        e.radiusRange = this.radiusRange,
        e.heightRange = this.heightRange,
        e.emitFromSpawnPointOnly = this.emitFromSpawnPointOnly,
        e
    }
    ,
    i.prototype.parse = function(e) {
        this.radius = e.radius,
        this.angle = e.angle,
        this.directionRandomizer = e.directionRandomizer,
        this.radiusRange = e.radiusRange !== void 0 ? e.radiusRange : 1,
        this.heightRange = e.radiusRange !== void 0 ? e.heightRange : 1,
        this.emitFromSpawnPointOnly = e.emitFromSpawnPointOnly !== void 0 ? e.emitFromSpawnPointOnly : !1
    }
    ,
    i
}(), CylinderParticleEmitter = function() {
    function i(e, t, r, n) {
        e === void 0 && (e = 1),
        t === void 0 && (t = 1),
        r === void 0 && (r = 1),
        n === void 0 && (n = 0),
        this.radius = e,
        this.height = t,
        this.radiusRange = r,
        this.directionRandomizer = n,
        this._tempVector = Vector3.Zero()
    }
    return i.prototype.startDirectionFunction = function(e, t, r, n, o) {
        r.position.subtractToRef(e.getTranslation(), this._tempVector),
        this._tempVector.normalize(),
        Vector3.TransformNormalToRef(this._tempVector, o, this._tempVector);
        var a = Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2)
          , s = Math.atan2(this._tempVector.x, this._tempVector.z);
        if (s += Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer,
        this._tempVector.y = a,
        this._tempVector.x = Math.sin(s),
        this._tempVector.z = Math.cos(s),
        this._tempVector.normalize(),
        n) {
            t.copyFrom(this._tempVector);
            return
        }
        Vector3.TransformNormalFromFloatsToRef(this._tempVector.x, this._tempVector.y, this._tempVector.z, e, t)
    }
    ,
    i.prototype.startPositionFunction = function(e, t, r, n) {
        var o = Scalar.RandomRange(-this.height / 2, this.height / 2)
          , a = Scalar.RandomRange(0, 2 * Math.PI)
          , s = Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1)
          , l = Math.sqrt(s) * this.radius
          , u = l * Math.cos(a)
          , c = l * Math.sin(a);
        if (n) {
            t.copyFromFloats(u, o, c);
            return
        }
        Vector3.TransformCoordinatesFromFloatsToRef(u, o, c, e, t)
    }
    ,
    i.prototype.clone = function() {
        var e = new i(this.radius,this.directionRandomizer);
        return DeepCopier.DeepCopy(this, e),
        e
    }
    ,
    i.prototype.applyToShader = function(e) {
        e.setFloat("radius", this.radius),
        e.setFloat("height", this.height),
        e.setFloat("radiusRange", this.radiusRange),
        e.setFloat("directionRandomizer", this.directionRandomizer)
    }
    ,
    i.prototype.buildUniformLayout = function(e) {
        e.addUniform("radius", 1),
        e.addUniform("height", 1),
        e.addUniform("radiusRange", 1),
        e.addUniform("directionRandomizer", 1)
    }
    ,
    i.prototype.getEffectDefines = function() {
        return "#define CYLINDEREMITTER"
    }
    ,
    i.prototype.getClassName = function() {
        return "CylinderParticleEmitter"
    }
    ,
    i.prototype.serialize = function() {
        var e = {};
        return e.type = this.getClassName(),
        e.radius = this.radius,
        e.height = this.height,
        e.radiusRange = this.radiusRange,
        e.directionRandomizer = this.directionRandomizer,
        e
    }
    ,
    i.prototype.parse = function(e) {
        this.radius = e.radius,
        this.height = e.height,
        this.radiusRange = e.radiusRange,
        this.directionRandomizer = e.directionRandomizer
    }
    ,
    i
}(), CylinderDirectedParticleEmitter = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a) {
        t === void 0 && (t = 1),
        r === void 0 && (r = 1),
        n === void 0 && (n = 1),
        o === void 0 && (o = new Vector3(0,1,0)),
        a === void 0 && (a = new Vector3(0,1,0));
        var s = i.call(this, t, r, n) || this;
        return s.direction1 = o,
        s.direction2 = a,
        s
    }
    return e.prototype.startDirectionFunction = function(t, r, n) {
        var o = Scalar.RandomRange(this.direction1.x, this.direction2.x)
          , a = Scalar.RandomRange(this.direction1.y, this.direction2.y)
          , s = Scalar.RandomRange(this.direction1.z, this.direction2.z);
        Vector3.TransformNormalFromFloatsToRef(o, a, s, t, r)
    }
    ,
    e.prototype.clone = function() {
        var t = new e(this.radius,this.height,this.radiusRange,this.direction1,this.direction2);
        return DeepCopier.DeepCopy(this, t),
        t
    }
    ,
    e.prototype.applyToShader = function(t) {
        t.setFloat("radius", this.radius),
        t.setFloat("height", this.height),
        t.setFloat("radiusRange", this.radiusRange),
        t.setVector3("direction1", this.direction1),
        t.setVector3("direction2", this.direction2)
    }
    ,
    e.prototype.buildUniformLayout = function(t) {
        t.addUniform("radius", 1),
        t.addUniform("height", 1),
        t.addUniform("radiusRange", 1),
        t.addUniform("direction1", 3),
        t.addUniform("direction2", 3)
    }
    ,
    e.prototype.getEffectDefines = function() {
        return `#define CYLINDEREMITTER
#define DIRECTEDCYLINDEREMITTER`
    }
    ,
    e.prototype.getClassName = function() {
        return "CylinderDirectedParticleEmitter"
    }
    ,
    e.prototype.serialize = function() {
        var t = i.prototype.serialize.call(this);
        return t.direction1 = this.direction1.asArray(),
        t.direction2 = this.direction2.asArray(),
        t
    }
    ,
    e.prototype.parse = function(t) {
        i.prototype.parse.call(this, t),
        this.direction1.copyFrom(t.direction1),
        this.direction2.copyFrom(t.direction2)
    }
    ,
    e
}(CylinderParticleEmitter), HemisphericParticleEmitter = function() {
    function i(e, t, r) {
        e === void 0 && (e = 1),
        t === void 0 && (t = 1),
        r === void 0 && (r = 0),
        this.radius = e,
        this.radiusRange = t,
        this.directionRandomizer = r
    }
    return i.prototype.startDirectionFunction = function(e, t, r, n) {
        var o = r.position.subtract(e.getTranslation()).normalize()
          , a = Scalar.RandomRange(0, this.directionRandomizer)
          , s = Scalar.RandomRange(0, this.directionRandomizer)
          , l = Scalar.RandomRange(0, this.directionRandomizer);
        if (o.x += a,
        o.y += s,
        o.z += l,
        o.normalize(),
        n) {
            t.copyFrom(o);
            return
        }
        Vector3.TransformNormalFromFloatsToRef(o.x, o.y, o.z, e, t)
    }
    ,
    i.prototype.startPositionFunction = function(e, t, r, n) {
        var o = this.radius - Scalar.RandomRange(0, this.radius * this.radiusRange)
          , a = Scalar.RandomRange(0, 1)
          , s = Scalar.RandomRange(0, 2 * Math.PI)
          , l = Math.acos(2 * a - 1)
          , u = o * Math.cos(s) * Math.sin(l)
          , c = o * Math.cos(l)
          , h = o * Math.sin(s) * Math.sin(l);
        if (n) {
            t.copyFromFloats(u, Math.abs(c), h);
            return
        }
        Vector3.TransformCoordinatesFromFloatsToRef(u, Math.abs(c), h, e, t)
    }
    ,
    i.prototype.clone = function() {
        var e = new i(this.radius,this.directionRandomizer);
        return DeepCopier.DeepCopy(this, e),
        e
    }
    ,
    i.prototype.applyToShader = function(e) {
        e.setFloat("radius", this.radius),
        e.setFloat("radiusRange", this.radiusRange),
        e.setFloat("directionRandomizer", this.directionRandomizer)
    }
    ,
    i.prototype.buildUniformLayout = function(e) {
        e.addUniform("radius", 1),
        e.addUniform("radiusRange", 1),
        e.addUniform("directionRandomizer", 1)
    }
    ,
    i.prototype.getEffectDefines = function() {
        return "#define HEMISPHERICEMITTER"
    }
    ,
    i.prototype.getClassName = function() {
        return "HemisphericParticleEmitter"
    }
    ,
    i.prototype.serialize = function() {
        var e = {};
        return e.type = this.getClassName(),
        e.radius = this.radius,
        e.radiusRange = this.radiusRange,
        e.directionRandomizer = this.directionRandomizer,
        e
    }
    ,
    i.prototype.parse = function(e) {
        this.radius = e.radius,
        this.radiusRange = e.radiusRange,
        this.directionRandomizer = e.directionRandomizer
    }
    ,
    i
}(), PointParticleEmitter = function() {
    function i() {
        this.direction1 = new Vector3(0,1,0),
        this.direction2 = new Vector3(0,1,0)
    }
    return i.prototype.startDirectionFunction = function(e, t, r, n) {
        var o = Scalar.RandomRange(this.direction1.x, this.direction2.x)
          , a = Scalar.RandomRange(this.direction1.y, this.direction2.y)
          , s = Scalar.RandomRange(this.direction1.z, this.direction2.z);
        if (n) {
            t.copyFromFloats(o, a, s);
            return
        }
        Vector3.TransformNormalFromFloatsToRef(o, a, s, e, t)
    }
    ,
    i.prototype.startPositionFunction = function(e, t, r, n) {
        if (n) {
            t.copyFromFloats(0, 0, 0);
            return
        }
        Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, e, t)
    }
    ,
    i.prototype.clone = function() {
        var e = new i;
        return DeepCopier.DeepCopy(this, e),
        e
    }
    ,
    i.prototype.applyToShader = function(e) {
        e.setVector3("direction1", this.direction1),
        e.setVector3("direction2", this.direction2)
    }
    ,
    i.prototype.buildUniformLayout = function(e) {
        e.addUniform("direction1", 3),
        e.addUniform("direction2", 3)
    }
    ,
    i.prototype.getEffectDefines = function() {
        return "#define POINTEMITTER"
    }
    ,
    i.prototype.getClassName = function() {
        return "PointParticleEmitter"
    }
    ,
    i.prototype.serialize = function() {
        var e = {};
        return e.type = this.getClassName(),
        e.direction1 = this.direction1.asArray(),
        e.direction2 = this.direction2.asArray(),
        e
    }
    ,
    i.prototype.parse = function(e) {
        Vector3.FromArrayToRef(e.direction1, 0, this.direction1),
        Vector3.FromArrayToRef(e.direction2, 0, this.direction2)
    }
    ,
    i
}(), SphereParticleEmitter = function() {
    function i(e, t, r) {
        e === void 0 && (e = 1),
        t === void 0 && (t = 1),
        r === void 0 && (r = 0),
        this.radius = e,
        this.radiusRange = t,
        this.directionRandomizer = r
    }
    return i.prototype.startDirectionFunction = function(e, t, r, n) {
        var o = r.position.subtract(e.getTranslation()).normalize()
          , a = Scalar.RandomRange(0, this.directionRandomizer)
          , s = Scalar.RandomRange(0, this.directionRandomizer)
          , l = Scalar.RandomRange(0, this.directionRandomizer);
        if (o.x += a,
        o.y += s,
        o.z += l,
        o.normalize(),
        n) {
            t.copyFrom(o);
            return
        }
        Vector3.TransformNormalFromFloatsToRef(o.x, o.y, o.z, e, t)
    }
    ,
    i.prototype.startPositionFunction = function(e, t, r, n) {
        var o = this.radius - Scalar.RandomRange(0, this.radius * this.radiusRange)
          , a = Scalar.RandomRange(0, 1)
          , s = Scalar.RandomRange(0, 2 * Math.PI)
          , l = Math.acos(2 * a - 1)
          , u = o * Math.cos(s) * Math.sin(l)
          , c = o * Math.cos(l)
          , h = o * Math.sin(s) * Math.sin(l);
        if (n) {
            t.copyFromFloats(u, c, h);
            return
        }
        Vector3.TransformCoordinatesFromFloatsToRef(u, c, h, e, t)
    }
    ,
    i.prototype.clone = function() {
        var e = new i(this.radius,this.directionRandomizer);
        return DeepCopier.DeepCopy(this, e),
        e
    }
    ,
    i.prototype.applyToShader = function(e) {
        e.setFloat("radius", this.radius),
        e.setFloat("radiusRange", this.radiusRange),
        e.setFloat("directionRandomizer", this.directionRandomizer)
    }
    ,
    i.prototype.buildUniformLayout = function(e) {
        e.addUniform("radius", 1),
        e.addUniform("radiusRange", 1),
        e.addUniform("directionRandomizer", 1)
    }
    ,
    i.prototype.getEffectDefines = function() {
        return "#define SPHEREEMITTER"
    }
    ,
    i.prototype.getClassName = function() {
        return "SphereParticleEmitter"
    }
    ,
    i.prototype.serialize = function() {
        var e = {};
        return e.type = this.getClassName(),
        e.radius = this.radius,
        e.radiusRange = this.radiusRange,
        e.directionRandomizer = this.directionRandomizer,
        e
    }
    ,
    i.prototype.parse = function(e) {
        this.radius = e.radius,
        this.radiusRange = e.radiusRange,
        this.directionRandomizer = e.directionRandomizer
    }
    ,
    i
}(), SphereDirectedParticleEmitter = function(i) {
    __extends(e, i);
    function e(t, r, n) {
        t === void 0 && (t = 1),
        r === void 0 && (r = new Vector3(0,1,0)),
        n === void 0 && (n = new Vector3(0,1,0));
        var o = i.call(this, t) || this;
        return o.direction1 = r,
        o.direction2 = n,
        o
    }
    return e.prototype.startDirectionFunction = function(t, r, n) {
        var o = Scalar.RandomRange(this.direction1.x, this.direction2.x)
          , a = Scalar.RandomRange(this.direction1.y, this.direction2.y)
          , s = Scalar.RandomRange(this.direction1.z, this.direction2.z);
        Vector3.TransformNormalFromFloatsToRef(o, a, s, t, r)
    }
    ,
    e.prototype.clone = function() {
        var t = new e(this.radius,this.direction1,this.direction2);
        return DeepCopier.DeepCopy(this, t),
        t
    }
    ,
    e.prototype.applyToShader = function(t) {
        t.setFloat("radius", this.radius),
        t.setFloat("radiusRange", this.radiusRange),
        t.setVector3("direction1", this.direction1),
        t.setVector3("direction2", this.direction2)
    }
    ,
    e.prototype.buildUniformLayout = function(t) {
        t.addUniform("radius", 1),
        t.addUniform("radiusRange", 1),
        t.addUniform("direction1", 3),
        t.addUniform("direction2", 3)
    }
    ,
    e.prototype.getEffectDefines = function() {
        return `#define SPHEREEMITTER
#define DIRECTEDSPHEREEMITTER`
    }
    ,
    e.prototype.getClassName = function() {
        return "SphereDirectedParticleEmitter"
    }
    ,
    e.prototype.serialize = function() {
        var t = i.prototype.serialize.call(this);
        return t.direction1 = this.direction1.asArray(),
        t.direction2 = this.direction2.asArray(),
        t
    }
    ,
    e.prototype.parse = function(t) {
        i.prototype.parse.call(this, t),
        this.direction1.copyFrom(t.direction1),
        this.direction2.copyFrom(t.direction2)
    }
    ,
    e
}(SphereParticleEmitter), CustomParticleEmitter = function() {
    function i() {
        this.particlePositionGenerator = function() {}
        ,
        this.particleDestinationGenerator = function() {}
    }
    return i.prototype.startDirectionFunction = function(e, t, r, n) {
        var o = TmpVectors.Vector3[0];
        if (this.particleDestinationGenerator) {
            this.particleDestinationGenerator(-1, r, o);
            var a = TmpVectors.Vector3[1];
            o.subtractToRef(r.position, a),
            a.scaleToRef(1 / r.lifeTime, o)
        } else
            o.set(0, 0, 0);
        if (n) {
            t.copyFrom(o);
            return
        }
        Vector3.TransformNormalToRef(o, e, t)
    }
    ,
    i.prototype.startPositionFunction = function(e, t, r, n) {
        var o = TmpVectors.Vector3[0];
        if (this.particlePositionGenerator ? this.particlePositionGenerator(-1, r, o) : o.set(0, 0, 0),
        n) {
            t.copyFrom(o);
            return
        }
        Vector3.TransformCoordinatesToRef(o, e, t)
    }
    ,
    i.prototype.clone = function() {
        var e = new i;
        return DeepCopier.DeepCopy(this, e),
        e
    }
    ,
    i.prototype.applyToShader = function(e) {}
    ,
    i.prototype.buildUniformLayout = function(e) {}
    ,
    i.prototype.getEffectDefines = function() {
        return "#define CUSTOMEMITTER"
    }
    ,
    i.prototype.getClassName = function() {
        return "CustomParticleEmitter"
    }
    ,
    i.prototype.serialize = function() {
        var e = {};
        return e.type = this.getClassName(),
        e
    }
    ,
    i.prototype.parse = function(e) {}
    ,
    i
}(), MeshParticleEmitter = function() {
    function i(e) {
        e === void 0 && (e = null),
        this._indices = null,
        this._positions = null,
        this._normals = null,
        this._storedNormal = Vector3.Zero(),
        this._mesh = null,
        this.direction1 = new Vector3(0,1,0),
        this.direction2 = new Vector3(0,1,0),
        this.useMeshNormalsForDirection = !0,
        this.mesh = e
    }
    return Object.defineProperty(i.prototype, "mesh", {
        get: function() {
            return this._mesh
        },
        set: function(e) {
            this._mesh !== e && (this._mesh = e,
            e ? (this._indices = e.getIndices(),
            this._positions = e.getVerticesData(VertexBuffer.PositionKind),
            this._normals = e.getVerticesData(VertexBuffer.NormalKind)) : (this._indices = null,
            this._positions = null,
            this._normals = null))
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.startDirectionFunction = function(e, t, r, n) {
        if (this.useMeshNormalsForDirection && this._normals) {
            Vector3.TransformNormalToRef(this._storedNormal, e, t);
            return
        }
        var o = Scalar.RandomRange(this.direction1.x, this.direction2.x)
          , a = Scalar.RandomRange(this.direction1.y, this.direction2.y)
          , s = Scalar.RandomRange(this.direction1.z, this.direction2.z);
        if (n) {
            t.copyFromFloats(o, a, s);
            return
        }
        Vector3.TransformNormalFromFloatsToRef(o, a, s, e, t)
    }
    ,
    i.prototype.startPositionFunction = function(e, t, r, n) {
        if (!(!this._indices || !this._positions)) {
            var o = 3 * Math.random() * (this._indices.length / 3) | 0
              , a = Math.random()
              , s = Math.random() * (1 - a)
              , l = 1 - a - s
              , u = this._indices[o]
              , c = this._indices[o + 1]
              , h = this._indices[o + 2]
              , f = TmpVectors.Vector3[0]
              , d = TmpVectors.Vector3[1]
              , _ = TmpVectors.Vector3[2]
              , g = TmpVectors.Vector3[3];
            Vector3.FromArrayToRef(this._positions, u * 3, f),
            Vector3.FromArrayToRef(this._positions, c * 3, d),
            Vector3.FromArrayToRef(this._positions, h * 3, _),
            g.x = a * f.x + s * d.x + l * _.x,
            g.y = a * f.y + s * d.y + l * _.y,
            g.z = a * f.z + s * d.z + l * _.z,
            n ? t.copyFromFloats(g.x, g.y, g.z) : Vector3.TransformCoordinatesFromFloatsToRef(g.x, g.y, g.z, e, t),
            this.useMeshNormalsForDirection && this._normals && (Vector3.FromArrayToRef(this._normals, u * 3, f),
            Vector3.FromArrayToRef(this._normals, c * 3, d),
            Vector3.FromArrayToRef(this._normals, h * 3, _),
            this._storedNormal.x = a * f.x + s * d.x + l * _.x,
            this._storedNormal.y = a * f.y + s * d.y + l * _.y,
            this._storedNormal.z = a * f.z + s * d.z + l * _.z)
        }
    }
    ,
    i.prototype.clone = function() {
        var e = new i(this.mesh);
        return DeepCopier.DeepCopy(this, e),
        e
    }
    ,
    i.prototype.applyToShader = function(e) {
        e.setVector3("direction1", this.direction1),
        e.setVector3("direction2", this.direction2)
    }
    ,
    i.prototype.buildUniformLayout = function(e) {
        e.addUniform("direction1", 3),
        e.addUniform("direction2", 3)
    }
    ,
    i.prototype.getEffectDefines = function() {
        return ""
    }
    ,
    i.prototype.getClassName = function() {
        return "MeshParticleEmitter"
    }
    ,
    i.prototype.serialize = function() {
        var e, t = {};
        return t.type = this.getClassName(),
        t.direction1 = this.direction1.asArray(),
        t.direction2 = this.direction2.asArray(),
        t.meshId = (e = this.mesh) === null || e === void 0 ? void 0 : e.id,
        t.useMeshNormalsForDirection = this.useMeshNormalsForDirection,
        t
    }
    ,
    i.prototype.parse = function(e, t) {
        Vector3.FromArrayToRef(e.direction1, 0, this.direction1),
        Vector3.FromArrayToRef(e.direction2, 0, this.direction2),
        e.meshId && t && (this.mesh = t.getLastMeshById(e.meshId)),
        this.useMeshNormalsForDirection = e.useMeshNormalsForDirection
    }
    ,
    i
}(), BaseParticleSystem = function() {
    function i(e) {
        this.animations = [],
        this.renderingGroupId = 0,
        this.emitter = Vector3.Zero(),
        this.emitRate = 10,
        this.manualEmitCount = -1,
        this.updateSpeed = .01,
        this.targetStopDuration = 0,
        this.disposeOnStop = !1,
        this.minEmitPower = 1,
        this.maxEmitPower = 1,
        this.minLifeTime = 1,
        this.maxLifeTime = 1,
        this.minSize = 1,
        this.maxSize = 1,
        this.minScaleX = 1,
        this.maxScaleX = 1,
        this.minScaleY = 1,
        this.maxScaleY = 1,
        this.minInitialRotation = 0,
        this.maxInitialRotation = 0,
        this.minAngularSpeed = 0,
        this.maxAngularSpeed = 0,
        this.layerMask = 268435455,
        this.customShader = null,
        this.preventAutoStart = !1,
        this._rootUrl = "",
        this.noiseStrength = new Vector3(10,10,10),
        this.onAnimationEnd = null,
        this.blendMode = i.BLENDMODE_ONEONE,
        this.forceDepthWrite = !1,
        this.preWarmCycles = 0,
        this.preWarmStepOffset = 1,
        this.spriteCellChangeSpeed = 1,
        this.startSpriteCellID = 0,
        this.endSpriteCellID = 0,
        this.spriteCellWidth = 0,
        this.spriteCellHeight = 0,
        this.spriteCellLoop = !0,
        this.spriteRandomStartCell = !1,
        this.translationPivot = new Vector2(0,0),
        this.beginAnimationOnStart = !1,
        this.beginAnimationFrom = 0,
        this.beginAnimationTo = 60,
        this.beginAnimationLoop = !1,
        this.worldOffset = new Vector3(0,0,0),
        this.gravity = 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,
        this.startDelay = 0,
        this.limitVelocityDamping = .4,
        this.color1 = new Color4(1,1,1,1),
        this.color2 = new Color4(1,1,1,1),
        this.colorDead = new Color4(0,0,0,1),
        this.textureMask = new Color4(1,1,1,1),
        this._isSubEmitter = !1,
        this.billboardMode = 7,
        this._isBillboardBased = !0,
        this._imageProcessingConfigurationDefines = new ImageProcessingConfigurationDefines,
        this.id = e,
        this.name = e
    }
    return Object.defineProperty(i.prototype, "noiseTexture", {
        get: function() {
            return this._noiseTexture
        },
        set: function(e) {
            this._noiseTexture !== e && (this._noiseTexture = e,
            this._reset())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "isAnimationSheetEnabled", {
        get: function() {
            return this._isAnimationSheetEnabled
        },
        set: function(e) {
            this._isAnimationSheetEnabled != e && (this._isAnimationSheetEnabled = e,
            this._reset())
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.getScene = function() {
        return this._scene
    }
    ,
    i.prototype._hasTargetStopDurationDependantGradient = function() {
        return this._startSizeGradients && this._startSizeGradients.length > 0 || this._emitRateGradients && this._emitRateGradients.length > 0 || this._lifeTimeGradients && this._lifeTimeGradients.length > 0
    }
    ,
    i.prototype.getDragGradients = function() {
        return this._dragGradients
    }
    ,
    i.prototype.getLimitVelocityGradients = function() {
        return this._limitVelocityGradients
    }
    ,
    i.prototype.getColorGradients = function() {
        return this._colorGradients
    }
    ,
    i.prototype.getSizeGradients = function() {
        return this._sizeGradients
    }
    ,
    i.prototype.getColorRemapGradients = function() {
        return this._colorRemapGradients
    }
    ,
    i.prototype.getAlphaRemapGradients = function() {
        return this._alphaRemapGradients
    }
    ,
    i.prototype.getLifeTimeGradients = function() {
        return this._lifeTimeGradients
    }
    ,
    i.prototype.getAngularSpeedGradients = function() {
        return this._angularSpeedGradients
    }
    ,
    i.prototype.getVelocityGradients = function() {
        return this._velocityGradients
    }
    ,
    i.prototype.getStartSizeGradients = function() {
        return this._startSizeGradients
    }
    ,
    i.prototype.getEmitRateGradients = function() {
        return this._emitRateGradients
    }
    ,
    Object.defineProperty(i.prototype, "direction1", {
        get: function() {
            return this.particleEmitterType.direction1 ? this.particleEmitterType.direction1 : Vector3.Zero()
        },
        set: function(e) {
            this.particleEmitterType.direction1 && (this.particleEmitterType.direction1 = e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "direction2", {
        get: function() {
            return this.particleEmitterType.direction2 ? this.particleEmitterType.direction2 : Vector3.Zero()
        },
        set: function(e) {
            this.particleEmitterType.direction2 && (this.particleEmitterType.direction2 = e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "minEmitBox", {
        get: function() {
            return this.particleEmitterType.minEmitBox ? this.particleEmitterType.minEmitBox : Vector3.Zero()
        },
        set: function(e) {
            this.particleEmitterType.minEmitBox && (this.particleEmitterType.minEmitBox = e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "maxEmitBox", {
        get: function() {
            return this.particleEmitterType.maxEmitBox ? this.particleEmitterType.maxEmitBox : Vector3.Zero()
        },
        set: function(e) {
            this.particleEmitterType.maxEmitBox && (this.particleEmitterType.maxEmitBox = e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "isBillboardBased", {
        get: function() {
            return this._isBillboardBased
        },
        set: function(e) {
            this._isBillboardBased !== e && (this._isBillboardBased = e,
            this._reset())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "imageProcessingConfiguration", {
        get: function() {
            return this._imageProcessingConfiguration
        },
        set: function(e) {
            this._attachImageProcessingConfiguration(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype._attachImageProcessingConfiguration = function(e) {
        e !== this._imageProcessingConfiguration && (!e && this._scene ? this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration : this._imageProcessingConfiguration = e)
    }
    ,
    i.prototype._reset = function() {}
    ,
    i.prototype._removeGradientAndTexture = function(e, t, r) {
        if (!t)
            return this;
        for (var n = 0, o = 0, a = t; o < a.length; o++) {
            var s = a[o];
            if (s.gradient === e) {
                t.splice(n, 1);
                break
            }
            n++
        }
        return r && r.dispose(),
        this
    }
    ,
    i.prototype.createPointEmitter = function(e, t) {
        var r = new PointParticleEmitter;
        return r.direction1 = e,
        r.direction2 = t,
        this.particleEmitterType = r,
        r
    }
    ,
    i.prototype.createHemisphericEmitter = function(e, t) {
        e === void 0 && (e = 1),
        t === void 0 && (t = 1);
        var r = new HemisphericParticleEmitter(e,t);
        return this.particleEmitterType = r,
        r
    }
    ,
    i.prototype.createSphereEmitter = function(e, t) {
        e === void 0 && (e = 1),
        t === void 0 && (t = 1);
        var r = new SphereParticleEmitter(e,t);
        return this.particleEmitterType = r,
        r
    }
    ,
    i.prototype.createDirectedSphereEmitter = function(e, t, r) {
        e === void 0 && (e = 1),
        t === void 0 && (t = new Vector3(0,1,0)),
        r === void 0 && (r = new Vector3(0,1,0));
        var n = new SphereDirectedParticleEmitter(e,t,r);
        return this.particleEmitterType = n,
        n
    }
    ,
    i.prototype.createCylinderEmitter = function(e, t, r, n) {
        e === void 0 && (e = 1),
        t === void 0 && (t = 1),
        r === void 0 && (r = 1),
        n === void 0 && (n = 0);
        var o = new CylinderParticleEmitter(e,t,r,n);
        return this.particleEmitterType = o,
        o
    }
    ,
    i.prototype.createDirectedCylinderEmitter = function(e, t, r, n, o) {
        e === void 0 && (e = 1),
        t === void 0 && (t = 1),
        r === void 0 && (r = 1),
        n === void 0 && (n = new Vector3(0,1,0)),
        o === void 0 && (o = new Vector3(0,1,0));
        var a = new CylinderDirectedParticleEmitter(e,t,r,n,o);
        return this.particleEmitterType = a,
        a
    }
    ,
    i.prototype.createConeEmitter = function(e, t) {
        e === void 0 && (e = 1),
        t === void 0 && (t = Math.PI / 4);
        var r = new ConeParticleEmitter(e,t);
        return this.particleEmitterType = r,
        r
    }
    ,
    i.prototype.createBoxEmitter = function(e, t, r, n) {
        var o = new BoxParticleEmitter;
        return this.particleEmitterType = o,
        this.direction1 = e,
        this.direction2 = t,
        this.minEmitBox = r,
        this.maxEmitBox = n,
        o
    }
    ,
    i.BLENDMODE_ONEONE = 0,
    i.BLENDMODE_STANDARD = 1,
    i.BLENDMODE_ADD = 2,
    i.BLENDMODE_MULTIPLY = 3,
    i.BLENDMODE_MULTIPLYADD = 4,
    i
}(), Particle = function() {
    function i(e) {
        this.particleSystem = e,
        this.position = Vector3.Zero(),
        this.direction = Vector3.Zero(),
        this.color = new Color4(0,0,0,0),
        this.colorStep = new Color4(0,0,0,0),
        this.lifeTime = 1,
        this.age = 0,
        this.size = 0,
        this.scale = new Vector2(1,1),
        this.angle = 0,
        this.angularSpeed = 0,
        this.cellIndex = 0,
        this._attachedSubEmitters = null,
        this._currentColor1 = new Color4(0,0,0,0),
        this._currentColor2 = new Color4(0,0,0,0),
        this._currentSize1 = 0,
        this._currentSize2 = 0,
        this._currentAngularSpeed1 = 0,
        this._currentAngularSpeed2 = 0,
        this._currentVelocity1 = 0,
        this._currentVelocity2 = 0,
        this._currentLimitVelocity1 = 0,
        this._currentLimitVelocity2 = 0,
        this._currentDrag1 = 0,
        this._currentDrag2 = 0,
        this.id = i._Count++,
        this.particleSystem.isAnimationSheetEnabled && this.updateCellInfoFromSystem()
    }
    return i.prototype.updateCellInfoFromSystem = function() {
        this.cellIndex = this.particleSystem.startSpriteCellID
    }
    ,
    i.prototype.updateCellIndex = function() {
        var e = this.age
          , t = this.particleSystem.spriteCellChangeSpeed;
        this.particleSystem.spriteRandomStartCell && (this._randomCellOffset === void 0 && (this._randomCellOffset = Math.random() * this.lifeTime),
        t === 0 ? (t = 1,
        e = this._randomCellOffset) : e += this._randomCellOffset);
        var r = this._initialEndSpriteCellID - this._initialStartSpriteCellID, n;
        this._initialSpriteCellLoop ? n = Scalar.Clamp(e * t % this.lifeTime / this.lifeTime) : n = Scalar.Clamp(e * t / this.lifeTime),
        this.cellIndex = this._initialStartSpriteCellID + n * r | 0
    }
    ,
    i.prototype._inheritParticleInfoToSubEmitter = function(e) {
        if (e.particleSystem.emitter.position) {
            var t = e.particleSystem.emitter;
            if (t.position.copyFrom(this.position),
            e.inheritDirection) {
                var r = TmpVectors.Vector3[0];
                this.direction.normalizeToRef(r),
                t.setDirection(r, 0, Math.PI / 2)
            }
        } else {
            var n = e.particleSystem.emitter;
            n.copyFrom(this.position)
        }
        this.direction.scaleToRef(e.inheritedVelocityAmount / 2, TmpVectors.Vector3[0]),
        e.particleSystem._inheritedVelocityOffset.copyFrom(TmpVectors.Vector3[0])
    }
    ,
    i.prototype._inheritParticleInfoToSubEmitters = function() {
        var e = this;
        this._attachedSubEmitters && this._attachedSubEmitters.length > 0 && this._attachedSubEmitters.forEach(function(t) {
            e._inheritParticleInfoToSubEmitter(t)
        })
    }
    ,
    i.prototype._reset = function() {
        this.age = 0,
        this.id = i._Count++,
        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 = void 0
    }
    ,
    i.prototype.copyTo = function(e) {
        e.position.copyFrom(this.position),
        this._initialDirection ? e._initialDirection ? e._initialDirection.copyFrom(this._initialDirection) : e._initialDirection = this._initialDirection.clone() : e._initialDirection = null,
        e.direction.copyFrom(this.direction),
        this._localPosition && (e._localPosition ? e._localPosition.copyFrom(this._localPosition) : e._localPosition = this._localPosition.clone()),
        e.color.copyFrom(this.color),
        e.colorStep.copyFrom(this.colorStep),
        e.lifeTime = this.lifeTime,
        e.age = this.age,
        e._randomCellOffset = this._randomCellOffset,
        e.size = this.size,
        e.scale.copyFrom(this.scale),
        e.angle = this.angle,
        e.angularSpeed = this.angularSpeed,
        e.particleSystem = this.particleSystem,
        e.cellIndex = this.cellIndex,
        e.id = this.id,
        e._attachedSubEmitters = this._attachedSubEmitters,
        this._currentColorGradient && (e._currentColorGradient = this._currentColorGradient,
        e._currentColor1.copyFrom(this._currentColor1),
        e._currentColor2.copyFrom(this._currentColor2)),
        this._currentSizeGradient && (e._currentSizeGradient = this._currentSizeGradient,
        e._currentSize1 = this._currentSize1,
        e._currentSize2 = this._currentSize2),
        this._currentAngularSpeedGradient && (e._currentAngularSpeedGradient = this._currentAngularSpeedGradient,
        e._currentAngularSpeed1 = this._currentAngularSpeed1,
        e._currentAngularSpeed2 = this._currentAngularSpeed2),
        this._currentVelocityGradient && (e._currentVelocityGradient = this._currentVelocityGradient,
        e._currentVelocity1 = this._currentVelocity1,
        e._currentVelocity2 = this._currentVelocity2),
        this._currentLimitVelocityGradient && (e._currentLimitVelocityGradient = this._currentLimitVelocityGradient,
        e._currentLimitVelocity1 = this._currentLimitVelocity1,
        e._currentLimitVelocity2 = this._currentLimitVelocity2),
        this._currentDragGradient && (e._currentDragGradient = this._currentDragGradient,
        e._currentDrag1 = this._currentDrag1,
        e._currentDrag2 = this._currentDrag2),
        this.particleSystem.isAnimationSheetEnabled && (e._initialStartSpriteCellID = this._initialStartSpriteCellID,
        e._initialEndSpriteCellID = this._initialEndSpriteCellID,
        e._initialSpriteCellLoop = this._initialSpriteCellLoop),
        this.particleSystem.useRampGradients && (e.remapData && this.remapData ? e.remapData.copyFrom(this.remapData) : e.remapData = new Vector4(0,0,0,0)),
        this._randomNoiseCoordinates1 && (e._randomNoiseCoordinates1 ? (e._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1),
        e._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2)) : (e._randomNoiseCoordinates1 = this._randomNoiseCoordinates1.clone(),
        e._randomNoiseCoordinates2 = this._randomNoiseCoordinates2.clone()))
    }
    ,
    i._Count = 0,
    i
}(), SubEmitterType;
(function(i) {
    i[i.ATTACHED = 0] = "ATTACHED",
    i[i.END = 1] = "END"
}
)(SubEmitterType || (SubEmitterType = {}));
var SubEmitter = function() {
    function i(e) {
        if (this.particleSystem = e,
        this.type = SubEmitterType.END,
        this.inheritDirection = !1,
        this.inheritedVelocityAmount = 0,
        !e.emitter || !e.emitter.dispose) {
            var t = GetClass("BABYLON.AbstractMesh");
            e.emitter = new t("SubemitterSystemEmitter",e.getScene()),
            e._disposeEmitterOnDispose = !0
        }
    }
    return i.prototype.clone = function() {
        var e = this.particleSystem.emitter;
        if (!e)
            e = new Vector3;
        else if (e instanceof Vector3)
            e = e.clone();
        else if (e.getClassName().indexOf("Mesh") !== -1) {
            var t = GetClass("BABYLON.Mesh");
            e = new t("",e.getScene()),
            e.isVisible = !1
        }
        var r = new i(this.particleSystem.clone(this.particleSystem.name, e));
        return r.particleSystem.name += "Clone",
        r.type = this.type,
        r.inheritDirection = this.inheritDirection,
        r.inheritedVelocityAmount = this.inheritedVelocityAmount,
        r.particleSystem._disposeEmitterOnDispose = !0,
        r.particleSystem.disposeOnStop = !0,
        r
    }
    ,
    i.prototype.serialize = function(e) {
        e === void 0 && (e = !1);
        var t = {};
        return t.type = this.type,
        t.inheritDirection = this.inheritDirection,
        t.inheritedVelocityAmount = this.inheritedVelocityAmount,
        t.particleSystem = this.particleSystem.serialize(e),
        t
    }
    ,
    i._ParseParticleSystem = function(e, t, r, n) {
        throw _WarnImport("ParseParticle")
    }
    ,
    i.Parse = function(e, t, r) {
        var n = e.particleSystem
          , o = new i(i._ParseParticleSystem(n, t, r, !0));
        return o.type = e.type,
        o.inheritDirection = e.inheritDirection,
        o.inheritedVelocityAmount = e.inheritedVelocityAmount,
        o.particleSystem._isSubEmitter = !0,
        o
    }
    ,
    i.prototype.dispose = function() {
        this.particleSystem.dispose()
    }
    ,
    i
}()
  , name$1H = "particlesPixelShader"
  , shader$1H = `
varying vec2 vUV;
varying vec4 vColor;
uniform vec4 textureMask;
uniform sampler2D diffuseSampler;
#include<clipPlaneFragmentDeclaration>
#include<imageProcessingDeclaration>
#include<helperFunctions>
#include<imageProcessingFunctions>
#ifdef RAMPGRADIENT
varying vec4 remapRanges;
uniform sampler2D rampSampler;
#endif
void main(void) {
#include<clipPlaneFragment>
vec4 textureColor=texture2D(diffuseSampler,vUV);
vec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;
#ifdef RAMPGRADIENT
float alpha=baseColor.a;
float remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);
vec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));
baseColor.rgb*=rampColor.rgb;

float finalAlpha=baseColor.a;
baseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0);
#endif
#ifdef BLENDMULTIPLYMODE
float sourceAlpha=vColor.a*textureColor.a;
baseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha);
#endif


#ifdef IMAGEPROCESSINGPOSTPROCESS
baseColor.rgb=toLinearSpace(baseColor.rgb);
#else
#ifdef IMAGEPROCESSING
baseColor.rgb=toLinearSpace(baseColor.rgb);
baseColor=applyImageProcessing(baseColor);
#endif
#endif
gl_FragColor=baseColor;
}`;
ShaderStore.ShadersStore[name$1H] = shader$1H;
var name$1G = "particlesVertexShader"
  , shader$1G = `
attribute vec3 position;
attribute vec4 color;
attribute float angle;
attribute vec2 size;
#ifdef ANIMATESHEET
attribute float cellIndex;
#endif
#ifndef BILLBOARD
attribute vec3 direction;
#endif
#ifdef BILLBOARDSTRETCHED
attribute vec3 direction;
#endif
#ifdef RAMPGRADIENT
attribute vec4 remapData;
#endif
attribute vec2 offset;

uniform mat4 view;
uniform mat4 projection;
uniform vec2 translationPivot;
#ifdef ANIMATESHEET
uniform vec3 particlesInfos;
#endif

varying vec2 vUV;
varying vec4 vColor;
varying vec3 vPositionW;
#ifdef RAMPGRADIENT
varying vec4 remapRanges;
#endif
#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED)
uniform mat4 invView;
#endif
#include<clipPlaneVertexDeclaration>
#ifdef BILLBOARD
uniform vec3 eyePosition;
#endif
vec3 rotate(vec3 yaxis,vec3 rotatedCorner) {
vec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));
vec3 zaxis=normalize(cross(yaxis,xaxis));
vec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);
vec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);
vec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);
mat3 rotMatrix=mat3(row0,row1,row2);
vec3 alignedCorner=rotMatrix*rotatedCorner;
return position+alignedCorner;
}
#ifdef BILLBOARDSTRETCHED
vec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {
vec3 normalizedToCamera=normalize(toCamera);
vec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));
vec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));
vec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);
vec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);
vec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);
mat3 rotMatrix=mat3(row0,row1,row2);
vec3 alignedCorner=rotMatrix*rotatedCorner;
return position+alignedCorner;
}
#endif
void main(void) {
vec2 cornerPos;
cornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;
#ifdef BILLBOARD

vec3 rotatedCorner;
#ifdef BILLBOARDY
rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);
rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);
rotatedCorner.y=0.;
vec3 yaxis=position-eyePosition;
yaxis.y=0.;
vPositionW=rotate(normalize(yaxis),rotatedCorner);
vec3 viewPos=(view*vec4(vPositionW,1.0)).xyz;
#elif defined(BILLBOARDSTRETCHED)
rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);
rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);
rotatedCorner.z=0.;
vec3 toCamera=position-eyePosition;
vPositionW=rotateAlign(toCamera,rotatedCorner);
vec3 viewPos=(view*vec4(vPositionW,1.0)).xyz;
#else
rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);
rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);
rotatedCorner.z=0.;
vec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner;
vPositionW=(invView*vec4(viewPos,1)).xyz;
#endif
#ifdef RAMPGRADIENT
remapRanges=remapData;
#endif

gl_Position=projection*vec4(viewPos,1.0);
#else

vec3 rotatedCorner;
rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);
rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);
rotatedCorner.y=0.;
vec3 yaxis=normalize(direction);
vPositionW=rotate(yaxis,rotatedCorner);
gl_Position=projection*view*vec4(vPositionW,1.0);
#endif
vColor=color;
#ifdef ANIMATESHEET
float rowOffset=floor(cellIndex*particlesInfos.z);
float columnOffset=cellIndex-rowOffset/particlesInfos.z;
vec2 uvScale=particlesInfos.xy;
vec2 uvOffset=vec2(offset.x ,1.0-offset.y);
vUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;
#else
vUV=offset;
#endif

#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)
vec4 worldPos=vec4(vPositionW,1.0);
#endif
#include<clipPlaneVertex>
}`;
ShaderStore.ShadersStore[name$1G] = shader$1G;
var ParticleSystem = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a, s) {
        o === void 0 && (o = null),
        a === void 0 && (a = !1),
        s === void 0 && (s = .01);
        var l = i.call(this, t) || this;
        l._emitterInverseWorldMatrix = Matrix.Identity(),
        l._inheritedVelocityOffset = new Vector3,
        l.onDisposeObservable = new Observable,
        l.onStoppedObservable = new Observable,
        l._particles = new Array,
        l._stockParticles = new Array,
        l._newPartsExcess = 0,
        l._vertexBuffers = {},
        l._scaledColorStep = new Color4(0,0,0,0),
        l._colorDiff = new Color4(0,0,0,0),
        l._scaledDirection = Vector3.Zero(),
        l._scaledGravity = Vector3.Zero(),
        l._currentRenderId = -1,
        l._useInstancing = !1,
        l._started = !1,
        l._stopped = !1,
        l._actualFrame = 0,
        l._currentEmitRate1 = 0,
        l._currentEmitRate2 = 0,
        l._currentStartSize1 = 0,
        l._currentStartSize2 = 0,
        l._rawTextureWidth = 256,
        l._useRampGradients = !1,
        l._disposeEmitterOnDispose = !1,
        l.isLocal = !1,
        l._onBeforeDrawParticlesObservable = null,
        l.recycleParticle = function(c) {
            var h = l._particles.pop();
            h !== c && h.copyTo(c),
            l._stockParticles.push(h)
        }
        ,
        l._createParticle = function() {
            var c;
            if (l._stockParticles.length !== 0 ? (c = l._stockParticles.pop(),
            c._reset()) : c = new Particle(l),
            l._subEmitters && l._subEmitters.length > 0) {
                var h = l._subEmitters[Math.floor(Math.random() * l._subEmitters.length)];
                c._attachedSubEmitters = [],
                h.forEach(function(f) {
                    if (f.type === SubEmitterType.ATTACHED) {
                        var d = f.clone();
                        c._attachedSubEmitters.push(d),
                        d.particleSystem.start()
                    }
                })
            }
            return c
        }
        ,
        l._emitFromParticle = function(c) {
            if (!(!l._subEmitters || l._subEmitters.length === 0)) {
                var h = Math.floor(Math.random() * l._subEmitters.length);
                l._subEmitters[h].forEach(function(f) {
                    if (f.type === SubEmitterType.END) {
                        var d = f.clone();
                        c._inheritParticleInfoToSubEmitter(d),
                        d.particleSystem._rootParticleSystem = l,
                        l.activeSubSystems.push(d.particleSystem),
                        d.particleSystem.start()
                    }
                })
            }
        }
        ,
        l._capacity = r,
        l._epsilon = s,
        l._isAnimationSheetEnabled = a,
        !n || n.getClassName() === "Scene" ? (l._scene = n || EngineStore.LastCreatedScene,
        l._engine = l._scene.getEngine(),
        l.uniqueId = l._scene.getUniqueId(),
        l._scene.particleSystems.push(l)) : (l._engine = n,
        l.defaultProjectionMatrix = Matrix.PerspectiveFovLH(.8, 1, .1, 100, l._engine.isNDCHalfZRange)),
        l._engine.getCaps().vertexArrayObject && (l._vertexArrayObject = null),
        l._attachImageProcessingConfiguration(null),
        l._customWrappers = {
            0: new DrawWrapper(l._engine)
        },
        l._customWrappers[0].effect = o,
        l._drawWrappers = [],
        l._useInstancing = l._engine.getCaps().instancedArrays,
        l._createIndexBuffer(),
        l._createVertexBuffers(),
        l.particleEmitterType = new BoxParticleEmitter;
        var u = null;
        return l.updateFunction = function(c) {
            var h, f = null;
            l.noiseTexture && (f = l.noiseTexture.getSize(),
            (h = l.noiseTexture.getContent()) === null || h === void 0 || h.then(function(m) {
                u = m
            }));
            for (var d = function() {
                _ = c[g];
                var m = l._scaledUpdateSpeed
                  , v = _.age;
                if (_.age += m,
                _.age > _.lifeTime) {
                    var y = _.age - v
                      , b = _.lifeTime - v;
                    m = b * m / y,
                    _.age = _.lifeTime
                }
                var T = _.age / _.lifeTime;
                l._colorGradients && l._colorGradients.length > 0 ? GradientHelper.GetCurrentGradient(T, l._colorGradients, function(x, I, w) {
                    x !== _._currentColorGradient && (_._currentColor1.copyFrom(_._currentColor2),
                    I.getColorToRef(_._currentColor2),
                    _._currentColorGradient = x),
                    Color4.LerpToRef(_._currentColor1, _._currentColor2, w, _.color)
                }) : (_.colorStep.scaleToRef(m, l._scaledColorStep),
                _.color.addInPlace(l._scaledColorStep),
                _.color.a < 0 && (_.color.a = 0)),
                l._angularSpeedGradients && l._angularSpeedGradients.length > 0 && GradientHelper.GetCurrentGradient(T, l._angularSpeedGradients, function(x, I, w) {
                    x !== _._currentAngularSpeedGradient && (_._currentAngularSpeed1 = _._currentAngularSpeed2,
                    _._currentAngularSpeed2 = I.getFactor(),
                    _._currentAngularSpeedGradient = x),
                    _.angularSpeed = Scalar.Lerp(_._currentAngularSpeed1, _._currentAngularSpeed2, w)
                }),
                _.angle += _.angularSpeed * m;
                var C = m;
                if (l._velocityGradients && l._velocityGradients.length > 0 && GradientHelper.GetCurrentGradient(T, l._velocityGradients, function(x, I, w) {
                    x !== _._currentVelocityGradient && (_._currentVelocity1 = _._currentVelocity2,
                    _._currentVelocity2 = I.getFactor(),
                    _._currentVelocityGradient = x),
                    C *= Scalar.Lerp(_._currentVelocity1, _._currentVelocity2, w)
                }),
                _.direction.scaleToRef(C, l._scaledDirection),
                l._limitVelocityGradients && l._limitVelocityGradients.length > 0 && GradientHelper.GetCurrentGradient(T, l._limitVelocityGradients, function(x, I, w) {
                    x !== _._currentLimitVelocityGradient && (_._currentLimitVelocity1 = _._currentLimitVelocity2,
                    _._currentLimitVelocity2 = I.getFactor(),
                    _._currentLimitVelocityGradient = x);
                    var O = Scalar.Lerp(_._currentLimitVelocity1, _._currentLimitVelocity2, w)
                      , D = _.direction.length();
                    D > O && _.direction.scaleInPlace(l.limitVelocityDamping)
                }),
                l._dragGradients && l._dragGradients.length > 0 && GradientHelper.GetCurrentGradient(T, l._dragGradients, function(x, I, w) {
                    x !== _._currentDragGradient && (_._currentDrag1 = _._currentDrag2,
                    _._currentDrag2 = I.getFactor(),
                    _._currentDragGradient = x);
                    var O = Scalar.Lerp(_._currentDrag1, _._currentDrag2, w);
                    l._scaledDirection.scaleInPlace(1 - O)
                }),
                l.isLocal && _._localPosition ? (_._localPosition.addInPlace(l._scaledDirection),
                Vector3.TransformCoordinatesToRef(_._localPosition, l._emitterWorldMatrix, _.position)) : _.position.addInPlace(l._scaledDirection),
                u && f && _._randomNoiseCoordinates1) {
                    var A = l._fetchR(_._randomNoiseCoordinates1.x, _._randomNoiseCoordinates1.y, f.width, f.height, u)
                      , S = l._fetchR(_._randomNoiseCoordinates1.z, _._randomNoiseCoordinates2.x, f.width, f.height, u)
                      , P = l._fetchR(_._randomNoiseCoordinates2.y, _._randomNoiseCoordinates2.z, f.width, f.height, u)
                      , R = TmpVectors.Vector3[0]
                      , M = TmpVectors.Vector3[1];
                    R.copyFromFloats((2 * A - 1) * l.noiseStrength.x, (2 * S - 1) * l.noiseStrength.y, (2 * P - 1) * l.noiseStrength.z),
                    R.scaleToRef(m, M),
                    _.direction.addInPlace(M)
                }
                if (l.gravity.scaleToRef(m, l._scaledGravity),
                _.direction.addInPlace(l._scaledGravity),
                l._sizeGradients && l._sizeGradients.length > 0 && GradientHelper.GetCurrentGradient(T, l._sizeGradients, function(x, I, w) {
                    x !== _._currentSizeGradient && (_._currentSize1 = _._currentSize2,
                    _._currentSize2 = I.getFactor(),
                    _._currentSizeGradient = x),
                    _.size = Scalar.Lerp(_._currentSize1, _._currentSize2, w)
                }),
                l._useRampGradients && (l._colorRemapGradients && l._colorRemapGradients.length > 0 && GradientHelper.GetCurrentGradient(T, l._colorRemapGradients, function(x, I, w) {
                    var O = Scalar.Lerp(x.factor1, I.factor1, w)
                      , D = Scalar.Lerp(x.factor2, I.factor2, w);
                    _.remapData.x = O,
                    _.remapData.y = D - O
                }),
                l._alphaRemapGradients && l._alphaRemapGradients.length > 0 && GradientHelper.GetCurrentGradient(T, l._alphaRemapGradients, function(x, I, w) {
                    var O = Scalar.Lerp(x.factor1, I.factor1, w)
                      , D = Scalar.Lerp(x.factor2, I.factor2, w);
                    _.remapData.z = O,
                    _.remapData.w = D - O
                })),
                l._isAnimationSheetEnabled && _.updateCellIndex(),
                _._inheritParticleInfoToSubEmitters(),
                _.age >= _.lifeTime)
                    return l._emitFromParticle(_),
                    _._attachedSubEmitters && (_._attachedSubEmitters.forEach(function(x) {
                        x.particleSystem.disposeOnStop = !0,
                        x.particleSystem.stop()
                    }),
                    _._attachedSubEmitters = null),
                    l.recycleParticle(_),
                    g--,
                    "continue"
            }, _, g = 0; g < c.length; g++)
                d()
        }
        ,
        l
    }
    return Object.defineProperty(e.prototype, "onDispose", {
        set: function(t) {
            this._onDisposeObserver && this.onDisposeObservable.remove(this._onDisposeObserver),
            this._onDisposeObserver = this.onDisposeObservable.add(t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "useRampGradients", {
        get: function() {
            return this._useRampGradients
        },
        set: function(t) {
            this._useRampGradients !== t && (this._useRampGradients = t,
            this._resetEffect())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "particles", {
        get: function() {
            return this._particles
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getActiveCount = function() {
        return this._particles.length
    }
    ,
    e.prototype.getClassName = function() {
        return "ParticleSystem"
    }
    ,
    e.prototype.isStopping = function() {
        return this._stopped && this.isAlive()
    }
    ,
    e.prototype.getCustomEffect = function(t) {
        var r, n;
        return t === void 0 && (t = 0),
        (n = (r = this._customWrappers[t]) === null || r === void 0 ? void 0 : r.effect) !== null && n !== void 0 ? n : this._customWrappers[0].effect
    }
    ,
    e.prototype._getCustomDrawWrapper = function(t) {
        var r;
        return t === void 0 && (t = 0),
        (r = this._customWrappers[t]) !== null && r !== void 0 ? r : this._customWrappers[0]
    }
    ,
    e.prototype.setCustomEffect = function(t, r) {
        r === void 0 && (r = 0),
        this._customWrappers[r] = new DrawWrapper(this._engine),
        this._customWrappers[r].effect = t,
        this._customWrappers[r].drawContext && (this._customWrappers[r].drawContext.useInstancing = this._useInstancing)
    }
    ,
    Object.defineProperty(e.prototype, "onBeforeDrawParticlesObservable", {
        get: function() {
            return this._onBeforeDrawParticlesObservable || (this._onBeforeDrawParticlesObservable = new Observable),
            this._onBeforeDrawParticlesObservable
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "vertexShaderName", {
        get: function() {
            return "particles"
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._addFactorGradient = function(t, r, n, o) {
        var a = new FactorGradient(r,n,o);
        t.push(a),
        t.sort(function(s, l) {
            return s.gradient < l.gradient ? -1 : s.gradient > l.gradient ? 1 : 0
        })
    }
    ,
    e.prototype._removeFactorGradient = function(t, r) {
        if (!!t)
            for (var n = 0, o = 0, a = t; o < a.length; o++) {
                var s = a[o];
                if (s.gradient === r) {
                    t.splice(n, 1);
                    break
                }
                n++
            }
    }
    ,
    e.prototype.addLifeTimeGradient = function(t, r, n) {
        return this._lifeTimeGradients || (this._lifeTimeGradients = []),
        this._addFactorGradient(this._lifeTimeGradients, t, r, n),
        this
    }
    ,
    e.prototype.removeLifeTimeGradient = function(t) {
        return this._removeFactorGradient(this._lifeTimeGradients, t),
        this
    }
    ,
    e.prototype.addSizeGradient = function(t, r, n) {
        return this._sizeGradients || (this._sizeGradients = []),
        this._addFactorGradient(this._sizeGradients, t, r, n),
        this
    }
    ,
    e.prototype.removeSizeGradient = function(t) {
        return this._removeFactorGradient(this._sizeGradients, t),
        this
    }
    ,
    e.prototype.addColorRemapGradient = function(t, r, n) {
        return this._colorRemapGradients || (this._colorRemapGradients = []),
        this._addFactorGradient(this._colorRemapGradients, t, r, n),
        this
    }
    ,
    e.prototype.removeColorRemapGradient = function(t) {
        return this._removeFactorGradient(this._colorRemapGradients, t),
        this
    }
    ,
    e.prototype.addAlphaRemapGradient = function(t, r, n) {
        return this._alphaRemapGradients || (this._alphaRemapGradients = []),
        this._addFactorGradient(this._alphaRemapGradients, t, r, n),
        this
    }
    ,
    e.prototype.removeAlphaRemapGradient = function(t) {
        return this._removeFactorGradient(this._alphaRemapGradients, t),
        this
    }
    ,
    e.prototype.addAngularSpeedGradient = function(t, r, n) {
        return this._angularSpeedGradients || (this._angularSpeedGradients = []),
        this._addFactorGradient(this._angularSpeedGradients, t, r, n),
        this
    }
    ,
    e.prototype.removeAngularSpeedGradient = function(t) {
        return this._removeFactorGradient(this._angularSpeedGradients, t),
        this
    }
    ,
    e.prototype.addVelocityGradient = function(t, r, n) {
        return this._velocityGradients || (this._velocityGradients = []),
        this._addFactorGradient(this._velocityGradients, t, r, n),
        this
    }
    ,
    e.prototype.removeVelocityGradient = function(t) {
        return this._removeFactorGradient(this._velocityGradients, t),
        this
    }
    ,
    e.prototype.addLimitVelocityGradient = function(t, r, n) {
        return this._limitVelocityGradients || (this._limitVelocityGradients = []),
        this._addFactorGradient(this._limitVelocityGradients, t, r, n),
        this
    }
    ,
    e.prototype.removeLimitVelocityGradient = function(t) {
        return this._removeFactorGradient(this._limitVelocityGradients, t),
        this
    }
    ,
    e.prototype.addDragGradient = function(t, r, n) {
        return this._dragGradients || (this._dragGradients = []),
        this._addFactorGradient(this._dragGradients, t, r, n),
        this
    }
    ,
    e.prototype.removeDragGradient = function(t) {
        return this._removeFactorGradient(this._dragGradients, t),
        this
    }
    ,
    e.prototype.addEmitRateGradient = function(t, r, n) {
        return this._emitRateGradients || (this._emitRateGradients = []),
        this._addFactorGradient(this._emitRateGradients, t, r, n),
        this
    }
    ,
    e.prototype.removeEmitRateGradient = function(t) {
        return this._removeFactorGradient(this._emitRateGradients, t),
        this
    }
    ,
    e.prototype.addStartSizeGradient = function(t, r, n) {
        return this._startSizeGradients || (this._startSizeGradients = []),
        this._addFactorGradient(this._startSizeGradients, t, r, n),
        this
    }
    ,
    e.prototype.removeStartSizeGradient = function(t) {
        return this._removeFactorGradient(this._startSizeGradients, t),
        this
    }
    ,
    e.prototype._createRampGradientTexture = function() {
        if (!(!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture || !this._scene)) {
            for (var t = new Uint8Array(this._rawTextureWidth * 4), r = TmpColors.Color3[0], n = 0; n < this._rawTextureWidth; n++) {
                var o = n / this._rawTextureWidth;
                GradientHelper.GetCurrentGradient(o, this._rampGradients, function(a, s, l) {
                    Color3.LerpToRef(a.color, s.color, l, r),
                    t[n * 4] = r.r * 255,
                    t[n * 4 + 1] = r.g * 255,
                    t[n * 4 + 2] = r.b * 255,
                    t[n * 4 + 3] = 255
                })
            }
            this._rampGradientsTexture = RawTexture.CreateRGBATexture(t, this._rawTextureWidth, 1, this._scene, !1, !1, 1)
        }
    }
    ,
    e.prototype.getRampGradients = function() {
        return this._rampGradients
    }
    ,
    e.prototype.forceRefreshGradients = function() {
        this._syncRampGradientTexture()
    }
    ,
    e.prototype._syncRampGradientTexture = function() {
        !this._rampGradients || (this._rampGradients.sort(function(t, r) {
            return t.gradient < r.gradient ? -1 : t.gradient > r.gradient ? 1 : 0
        }),
        this._rampGradientsTexture && (this._rampGradientsTexture.dispose(),
        this._rampGradientsTexture = null),
        this._createRampGradientTexture())
    }
    ,
    e.prototype.addRampGradient = function(t, r) {
        this._rampGradients || (this._rampGradients = []);
        var n = new Color3Gradient(t,r);
        return this._rampGradients.push(n),
        this._syncRampGradientTexture(),
        this
    }
    ,
    e.prototype.removeRampGradient = function(t) {
        return this._removeGradientAndTexture(t, this._rampGradients, this._rampGradientsTexture),
        this._rampGradientsTexture = null,
        this._rampGradients && this._rampGradients.length > 0 && this._createRampGradientTexture(),
        this
    }
    ,
    e.prototype.addColorGradient = function(t, r, n) {
        this._colorGradients || (this._colorGradients = []);
        var o = new ColorGradient(t,r,n);
        return this._colorGradients.push(o),
        this._colorGradients.sort(function(a, s) {
            return a.gradient < s.gradient ? -1 : a.gradient > s.gradient ? 1 : 0
        }),
        this
    }
    ,
    e.prototype.removeColorGradient = function(t) {
        if (!this._colorGradients)
            return this;
        for (var r = 0, n = 0, o = this._colorGradients; n < o.length; n++) {
            var a = o[n];
            if (a.gradient === t) {
                this._colorGradients.splice(r, 1);
                break
            }
            r++
        }
        return this
    }
    ,
    e.prototype.resetDrawCache = function() {
        for (var t = 0, r = this._drawWrappers; t < r.length; t++) {
            var n = r[t];
            if (n)
                for (var o = 0, a = n; o < a.length; o++) {
                    var s = a[o];
                    s == null || s.dispose()
                }
        }
        this._drawWrappers = []
    }
    ,
    e.prototype._fetchR = function(t, r, n, o, a) {
        t = Math.abs(t) * .5 + .5,
        r = Math.abs(r) * .5 + .5;
        var s = t * n % n | 0
          , l = r * o % o | 0
          , u = (s + l * n) * 4;
        return a[u] / 255
    }
    ,
    e.prototype._reset = function() {
        this._resetEffect()
    }
    ,
    e.prototype._resetEffect = function() {
        this._vertexBuffer && (this._vertexBuffer.dispose(),
        this._vertexBuffer = null),
        this._spriteBuffer && (this._spriteBuffer.dispose(),
        this._spriteBuffer = null),
        this._vertexArrayObject && (this._engine.releaseVertexArrayObject(this._vertexArrayObject),
        this._vertexArrayObject = null),
        this._createVertexBuffers()
    }
    ,
    e.prototype._createVertexBuffers = function() {
        this._vertexBufferSize = this._useInstancing ? 10 : 12,
        this._isAnimationSheetEnabled && (this._vertexBufferSize += 1),
        (!this._isBillboardBased || this.billboardMode === e.BILLBOARDMODE_STRETCHED) && (this._vertexBufferSize += 3),
        this._useRampGradients && (this._vertexBufferSize += 4);
        var t = this._engine;
        this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4)),
        this._vertexBuffer = new Buffer(t,this._vertexData,!0,this._vertexBufferSize);
        var r = 0
          , n = this._vertexBuffer.createVertexBuffer(VertexBuffer.PositionKind, r, 3, this._vertexBufferSize, this._useInstancing);
        this._vertexBuffers[VertexBuffer.PositionKind] = n,
        r += 3;
        var o = this._vertexBuffer.createVertexBuffer(VertexBuffer.ColorKind, r, 4, this._vertexBufferSize, this._useInstancing);
        this._vertexBuffers[VertexBuffer.ColorKind] = o,
        r += 4;
        var a = this._vertexBuffer.createVertexBuffer("angle", r, 1, this._vertexBufferSize, this._useInstancing);
        this._vertexBuffers.angle = a,
        r += 1;
        var s = this._vertexBuffer.createVertexBuffer("size", r, 2, this._vertexBufferSize, this._useInstancing);
        if (this._vertexBuffers.size = s,
        r += 2,
        this._isAnimationSheetEnabled) {
            var l = this._vertexBuffer.createVertexBuffer("cellIndex", r, 1, this._vertexBufferSize, this._useInstancing);
            this._vertexBuffers.cellIndex = l,
            r += 1
        }
        if (!this._isBillboardBased || this.billboardMode === e.BILLBOARDMODE_STRETCHED) {
            var u = this._vertexBuffer.createVertexBuffer("direction", r, 3, this._vertexBufferSize, this._useInstancing);
            this._vertexBuffers.direction = u,
            r += 3
        }
        if (this._useRampGradients) {
            var c = this._vertexBuffer.createVertexBuffer("remapData", r, 4, this._vertexBufferSize, this._useInstancing);
            this._vertexBuffers.remapData = c,
            r += 4
        }
        var h;
        if (this._useInstancing) {
            var f = new Float32Array([0, 0, 1, 0, 0, 1, 1, 1]);
            this._spriteBuffer = new Buffer(t,f,!1,2),
            h = this._spriteBuffer.createVertexBuffer("offset", 0, 2)
        } else
            h = this._vertexBuffer.createVertexBuffer("offset", r, 2, this._vertexBufferSize, this._useInstancing),
            r += 2;
        this._vertexBuffers.offset = h,
        this.resetDrawCache()
    }
    ,
    e.prototype._createIndexBuffer = function() {
        if (!this._useInstancing) {
            for (var t = [], r = 0, n = 0; n < this._capacity; n++)
                t.push(r),
                t.push(r + 1),
                t.push(r + 2),
                t.push(r),
                t.push(r + 2),
                t.push(r + 3),
                r += 4;
            this._indexBuffer = this._engine.createIndexBuffer(t)
        }
    }
    ,
    e.prototype.getCapacity = function() {
        return this._capacity
    }
    ,
    e.prototype.isAlive = function() {
        return this._alive
    }
    ,
    e.prototype.isStarted = function() {
        return this._started
    }
    ,
    e.prototype._prepareSubEmitterInternalArray = function() {
        var t = this;
        this._subEmitters = new Array,
        this.subEmitters && this.subEmitters.forEach(function(r) {
            r instanceof e ? t._subEmitters.push([new SubEmitter(r)]) : r instanceof SubEmitter ? t._subEmitters.push([r]) : r instanceof Array && t._subEmitters.push(r)
        })
    }
    ,
    e.prototype.start = function(t) {
        var r = this, n;
        if (t === void 0 && (t = this.startDelay),
        !this.targetStopDuration && this._hasTargetStopDurationDependantGradient())
            throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
        if (t) {
            setTimeout(function() {
                r.start(0)
            }, t);
            return
        }
        if (this._prepareSubEmitterInternalArray(),
        this._started = !0,
        this._stopped = !1,
        this._actualFrame = 0,
        this._subEmitters && this._subEmitters.length != 0 && (this.activeSubSystems = new Array),
        this._emitRateGradients && (this._emitRateGradients.length > 0 && (this._currentEmitRateGradient = this._emitRateGradients[0],
        this._currentEmitRate1 = this._currentEmitRateGradient.getFactor(),
        this._currentEmitRate2 = this._currentEmitRate1),
        this._emitRateGradients.length > 1 && (this._currentEmitRate2 = this._emitRateGradients[1].getFactor())),
        this._startSizeGradients && (this._startSizeGradients.length > 0 && (this._currentStartSizeGradient = this._startSizeGradients[0],
        this._currentStartSize1 = this._currentStartSizeGradient.getFactor(),
        this._currentStartSize2 = this._currentStartSize1),
        this._startSizeGradients.length > 1 && (this._currentStartSize2 = this._startSizeGradients[1].getFactor())),
        this.preWarmCycles) {
            ((n = this.emitter) === null || n === void 0 ? void 0 : n.getClassName().indexOf("Mesh")) !== -1 && this.emitter.computeWorldMatrix(!0);
            var o = this.noiseTexture;
            if (o && o.onGeneratedObservable)
                o.onGeneratedObservable.addOnce(function() {
                    setTimeout(function() {
                        for (var s = 0; s < r.preWarmCycles; s++)
                            r.animate(!0),
                            o.render()
                    })
                });
            else
                for (var a = 0; a < this.preWarmCycles; a++)
                    this.animate(!0)
        }
        this.beginAnimationOnStart && this.animations && this.animations.length > 0 && this._scene && this._scene.beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop)
    }
    ,
    e.prototype.stop = function(t) {
        t === void 0 && (t = !0),
        !this._stopped && (this.onStoppedObservable.notifyObservers(this),
        this._stopped = !0,
        t && this._stopSubEmitters())
    }
    ,
    e.prototype.reset = function() {
        this._stockParticles = [],
        this._particles = []
    }
    ,
    e.prototype._appendParticleVertex = function(t, r, n, o) {
        var a = t * this._vertexBufferSize;
        if (this._vertexData[a++] = r.position.x + this.worldOffset.x,
        this._vertexData[a++] = r.position.y + this.worldOffset.y,
        this._vertexData[a++] = r.position.z + this.worldOffset.z,
        this._vertexData[a++] = r.color.r,
        this._vertexData[a++] = r.color.g,
        this._vertexData[a++] = r.color.b,
        this._vertexData[a++] = r.color.a,
        this._vertexData[a++] = r.angle,
        this._vertexData[a++] = r.scale.x * r.size,
        this._vertexData[a++] = r.scale.y * r.size,
        this._isAnimationSheetEnabled && (this._vertexData[a++] = r.cellIndex),
        this._isBillboardBased)
            this.billboardMode === e.BILLBOARDMODE_STRETCHED && (this._vertexData[a++] = r.direction.x,
            this._vertexData[a++] = r.direction.y,
            this._vertexData[a++] = r.direction.z);
        else if (r._initialDirection) {
            var s = r._initialDirection;
            this.isLocal && (Vector3.TransformNormalToRef(s, this._emitterWorldMatrix, TmpVectors.Vector3[0]),
            s = TmpVectors.Vector3[0]),
            s.x === 0 && s.z === 0 && (s.x = .001),
            this._vertexData[a++] = s.x,
            this._vertexData[a++] = s.y,
            this._vertexData[a++] = s.z
        } else {
            var l = r.direction;
            this.isLocal && (Vector3.TransformNormalToRef(l, this._emitterWorldMatrix, TmpVectors.Vector3[0]),
            l = TmpVectors.Vector3[0]),
            l.x === 0 && l.z === 0 && (l.x = .001),
            this._vertexData[a++] = l.x,
            this._vertexData[a++] = l.y,
            this._vertexData[a++] = l.z
        }
        this._useRampGradients && r.remapData && (this._vertexData[a++] = r.remapData.x,
        this._vertexData[a++] = r.remapData.y,
        this._vertexData[a++] = r.remapData.z,
        this._vertexData[a++] = r.remapData.w),
        this._useInstancing || (this._isAnimationSheetEnabled && (n === 0 ? n = this._epsilon : n === 1 && (n = 1 - this._epsilon),
        o === 0 ? o = this._epsilon : o === 1 && (o = 1 - this._epsilon)),
        this._vertexData[a++] = n,
        this._vertexData[a++] = o)
    }
    ,
    e.prototype._stopSubEmitters = function() {
        !this.activeSubSystems || (this.activeSubSystems.forEach(function(t) {
            t.stop(!0)
        }),
        this.activeSubSystems = new Array)
    }
    ,
    e.prototype._removeFromRoot = function() {
        if (!!this._rootParticleSystem) {
            var t = this._rootParticleSystem.activeSubSystems.indexOf(this);
            t !== -1 && this._rootParticleSystem.activeSubSystems.splice(t, 1),
            this._rootParticleSystem = null
        }
    }
    ,
    e.prototype._update = function(t) {
        var r = this;
        if (this._alive = this._particles.length > 0,
        this.emitter.position) {
            var n = this.emitter;
            this._emitterWorldMatrix = n.getWorldMatrix()
        } else {
            var o = this.emitter;
            this._emitterWorldMatrix = Matrix.Translation(o.x, o.y, o.z)
        }
        this._emitterWorldMatrix.invertToRef(this._emitterInverseWorldMatrix),
        this.updateFunction(this._particles);
        for (var a, s = function() {
            if (l._particles.length === l._capacity)
                return "break";
            if (a = l._createParticle(),
            l._particles.push(a),
            l.targetStopDuration && l._lifeTimeGradients && l._lifeTimeGradients.length > 0) {
                var f = Scalar.Clamp(l._actualFrame / l.targetStopDuration);
                GradientHelper.GetCurrentGradient(f, l._lifeTimeGradients, function(g, m) {
                    var v = g
                      , y = m
                      , b = v.getFactor()
                      , T = y.getFactor()
                      , C = (f - v.gradient) / (y.gradient - v.gradient);
                    a.lifeTime = Scalar.Lerp(b, T, C)
                })
            } else
                a.lifeTime = Scalar.RandomRange(l.minLifeTime, l.maxLifeTime);
            var d = Scalar.RandomRange(l.minEmitPower, l.maxEmitPower);
            if (l.startPositionFunction ? l.startPositionFunction(l._emitterWorldMatrix, a.position, a, l.isLocal) : l.particleEmitterType.startPositionFunction(l._emitterWorldMatrix, a.position, a, l.isLocal),
            l.isLocal && (a._localPosition ? a._localPosition.copyFrom(a.position) : a._localPosition = a.position.clone(),
            Vector3.TransformCoordinatesToRef(a._localPosition, l._emitterWorldMatrix, a.position)),
            l.startDirectionFunction ? l.startDirectionFunction(l._emitterWorldMatrix, a.direction, a, l.isLocal) : l.particleEmitterType.startDirectionFunction(l._emitterWorldMatrix, a.direction, a, l.isLocal, l._emitterInverseWorldMatrix),
            d === 0 ? a._initialDirection ? a._initialDirection.copyFrom(a.direction) : a._initialDirection = a.direction.clone() : a._initialDirection = null,
            a.direction.scaleInPlace(d),
            !l._sizeGradients || l._sizeGradients.length === 0 ? a.size = Scalar.RandomRange(l.minSize, l.maxSize) : (a._currentSizeGradient = l._sizeGradients[0],
            a._currentSize1 = a._currentSizeGradient.getFactor(),
            a.size = a._currentSize1,
            l._sizeGradients.length > 1 ? a._currentSize2 = l._sizeGradients[1].getFactor() : a._currentSize2 = a._currentSize1),
            a.scale.copyFromFloats(Scalar.RandomRange(l.minScaleX, l.maxScaleX), Scalar.RandomRange(l.minScaleY, l.maxScaleY)),
            l._startSizeGradients && l._startSizeGradients[0] && l.targetStopDuration) {
                var _ = l._actualFrame / l.targetStopDuration;
                GradientHelper.GetCurrentGradient(_, l._startSizeGradients, function(g, m, v) {
                    g !== r._currentStartSizeGradient && (r._currentStartSize1 = r._currentStartSize2,
                    r._currentStartSize2 = m.getFactor(),
                    r._currentStartSizeGradient = g);
                    var y = Scalar.Lerp(r._currentStartSize1, r._currentStartSize2, v);
                    a.scale.scaleInPlace(y)
                })
            }
            !l._angularSpeedGradients || l._angularSpeedGradients.length === 0 ? a.angularSpeed = Scalar.RandomRange(l.minAngularSpeed, l.maxAngularSpeed) : (a._currentAngularSpeedGradient = l._angularSpeedGradients[0],
            a.angularSpeed = a._currentAngularSpeedGradient.getFactor(),
            a._currentAngularSpeed1 = a.angularSpeed,
            l._angularSpeedGradients.length > 1 ? a._currentAngularSpeed2 = l._angularSpeedGradients[1].getFactor() : a._currentAngularSpeed2 = a._currentAngularSpeed1),
            a.angle = Scalar.RandomRange(l.minInitialRotation, l.maxInitialRotation),
            l._velocityGradients && l._velocityGradients.length > 0 && (a._currentVelocityGradient = l._velocityGradients[0],
            a._currentVelocity1 = a._currentVelocityGradient.getFactor(),
            l._velocityGradients.length > 1 ? a._currentVelocity2 = l._velocityGradients[1].getFactor() : a._currentVelocity2 = a._currentVelocity1),
            l._limitVelocityGradients && l._limitVelocityGradients.length > 0 && (a._currentLimitVelocityGradient = l._limitVelocityGradients[0],
            a._currentLimitVelocity1 = a._currentLimitVelocityGradient.getFactor(),
            l._limitVelocityGradients.length > 1 ? a._currentLimitVelocity2 = l._limitVelocityGradients[1].getFactor() : a._currentLimitVelocity2 = a._currentLimitVelocity1),
            l._dragGradients && l._dragGradients.length > 0 && (a._currentDragGradient = l._dragGradients[0],
            a._currentDrag1 = a._currentDragGradient.getFactor(),
            l._dragGradients.length > 1 ? a._currentDrag2 = l._dragGradients[1].getFactor() : a._currentDrag2 = a._currentDrag1),
            !l._colorGradients || l._colorGradients.length === 0 ? (u = Scalar.RandomRange(0, 1),
            Color4.LerpToRef(l.color1, l.color2, u, a.color),
            l.colorDead.subtractToRef(a.color, l._colorDiff),
            l._colorDiff.scaleToRef(1 / a.lifeTime, a.colorStep)) : (a._currentColorGradient = l._colorGradients[0],
            a._currentColorGradient.getColorToRef(a.color),
            a._currentColor1.copyFrom(a.color),
            l._colorGradients.length > 1 ? l._colorGradients[1].getColorToRef(a._currentColor2) : a._currentColor2.copyFrom(a.color)),
            l._isAnimationSheetEnabled && (a._initialStartSpriteCellID = l.startSpriteCellID,
            a._initialEndSpriteCellID = l.endSpriteCellID,
            a._initialSpriteCellLoop = l.spriteCellLoop),
            a.direction.addInPlace(l._inheritedVelocityOffset),
            l._useRampGradients && (a.remapData = new Vector4(0,1,0,1)),
            l.noiseTexture && (a._randomNoiseCoordinates1 ? (a._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random()),
            a._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random())) : (a._randomNoiseCoordinates1 = new Vector3(Math.random(),Math.random(),Math.random()),
            a._randomNoiseCoordinates2 = new Vector3(Math.random(),Math.random(),Math.random()))),
            a._inheritParticleInfoToSubEmitters()
        }, l = this, u, c = 0; c < t; c++) {
            var h = s();
            if (h === "break")
                break
        }
    }
    ,
    e._GetAttributeNamesOrOptions = function(t, r, n) {
        t === void 0 && (t = !1),
        r === void 0 && (r = !1),
        n === void 0 && (n = !1);
        var o = [VertexBuffer.PositionKind, VertexBuffer.ColorKind, "angle", "offset", "size"];
        return t && o.push("cellIndex"),
        r || o.push("direction"),
        n && o.push("remapData"),
        o
    }
    ,
    e._GetEffectCreationOptions = function(t) {
        t === void 0 && (t = !1);
        var r = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "vClipPlane5", "vClipPlane6", "textureMask", "translationPivot", "eyePosition"];
        return t && r.push("particlesInfos"),
        r
    }
    ,
    e.prototype.fillDefines = function(t, r) {
        if (this._scene && (this._scene.clipPlane && t.push("#define CLIPPLANE"),
        this._scene.clipPlane2 && t.push("#define CLIPPLANE2"),
        this._scene.clipPlane3 && t.push("#define CLIPPLANE3"),
        this._scene.clipPlane4 && t.push("#define CLIPPLANE4"),
        this._scene.clipPlane5 && t.push("#define CLIPPLANE5"),
        this._scene.clipPlane6 && t.push("#define CLIPPLANE6")),
        this._isAnimationSheetEnabled && t.push("#define ANIMATESHEET"),
        r === e.BLENDMODE_MULTIPLY && t.push("#define BLENDMULTIPLYMODE"),
        this._useRampGradients && t.push("#define RAMPGRADIENT"),
        this._isBillboardBased)
            switch (t.push("#define BILLBOARD"),
            this.billboardMode) {
            case e.BILLBOARDMODE_Y:
                t.push("#define BILLBOARDY");
                break;
            case e.BILLBOARDMODE_STRETCHED:
                t.push("#define BILLBOARDSTRETCHED");
                break;
            case e.BILLBOARDMODE_ALL:
                t.push("#define BILLBOARDMODE_ALL");
                break
            }
        this._imageProcessingConfiguration && (this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),
        t.push(this._imageProcessingConfigurationDefines.toString()))
    }
    ,
    e.prototype.fillUniformsAttributesAndSamplerNames = function(t, r, n) {
        r.push.apply(r, e._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased && this.billboardMode !== e.BILLBOARDMODE_STRETCHED, this._useRampGradients)),
        t.push.apply(t, e._GetEffectCreationOptions(this._isAnimationSheetEnabled)),
        n.push("diffuseSampler", "rampSampler"),
        this._imageProcessingConfiguration && (ImageProcessingConfiguration.PrepareUniforms(t, this._imageProcessingConfigurationDefines),
        ImageProcessingConfiguration.PrepareSamplers(n, this._imageProcessingConfigurationDefines))
    }
    ,
    e.prototype._getWrapper = function(t) {
        var r = this._getCustomDrawWrapper(t);
        if (r != null && r.effect)
            return r;
        var n = [];
        this.fillDefines(n, t);
        var o = this._engine._features.supportRenderPasses ? this._engine.currentRenderPassId : 0
          , a = this._drawWrappers[o];
        a || (a = this._drawWrappers[o] = []);
        var s = a[t];
        s || (s = new DrawWrapper(this._engine),
        s.drawContext && (s.drawContext.useInstancing = this._useInstancing),
        a[t] = s);
        var l = n.join(`
`);
        if (s.defines !== l) {
            var u = []
              , c = []
              , h = [];
            this.fillUniformsAttributesAndSamplerNames(c, u, h),
            s.setEffect(this._engine.createEffect("particles", u, c, h, l), l)
        }
        return s
    }
    ,
    e.prototype.animate = function(t) {
        var r = this, n;
        if (t === void 0 && (t = !1),
        !!this._started) {
            if (!t && this._scene) {
                if (!this.isReady() || this._currentRenderId === this._scene.getFrameId())
                    return;
                this._currentRenderId = this._scene.getFrameId()
            }
            this._scaledUpdateSpeed = this.updateSpeed * (t ? this.preWarmStepOffset : ((n = this._scene) === null || n === void 0 ? void 0 : n.getAnimationRatio()) || 1);
            var o;
            if (this.manualEmitCount > -1)
                o = this.manualEmitCount,
                this._newPartsExcess = 0,
                this.manualEmitCount = 0;
            else {
                var a = this.emitRate;
                if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
                    var s = this._actualFrame / this.targetStopDuration;
                    GradientHelper.GetCurrentGradient(s, this._emitRateGradients, function(h, f, d) {
                        h !== r._currentEmitRateGradient && (r._currentEmitRate1 = r._currentEmitRate2,
                        r._currentEmitRate2 = f.getFactor(),
                        r._currentEmitRateGradient = h),
                        a = Scalar.Lerp(r._currentEmitRate1, r._currentEmitRate2, d)
                    })
                }
                o = a * this._scaledUpdateSpeed >> 0,
                this._newPartsExcess += a * this._scaledUpdateSpeed - o
            }
            if (this._newPartsExcess > 1 && (o += this._newPartsExcess >> 0,
            this._newPartsExcess -= this._newPartsExcess >> 0),
            this._alive = !1,
            this._stopped ? o = 0 : (this._actualFrame += this._scaledUpdateSpeed,
            this.targetStopDuration && this._actualFrame >= this.targetStopDuration && this.stop()),
            this._update(o),
            this._stopped && (this._alive || (this._started = !1,
            this.onAnimationEnd && this.onAnimationEnd(),
            this.disposeOnStop && this._scene && this._scene._toBeDisposed.push(this))),
            !t) {
                for (var l = 0, u = 0; u < this._particles.length; u++) {
                    var c = this._particles[u];
                    this._appendParticleVertices(l, c),
                    l += this._useInstancing ? 1 : 4
                }
                this._vertexBuffer && this._vertexBuffer.updateDirectly(this._vertexData, 0, this._particles.length)
            }
            this.manualEmitCount === 0 && this.disposeOnStop && this.stop()
        }
    }
    ,
    e.prototype._appendParticleVertices = function(t, r) {
        this._appendParticleVertex(t++, r, 0, 0),
        this._useInstancing || (this._appendParticleVertex(t++, r, 1, 0),
        this._appendParticleVertex(t++, r, 1, 1),
        this._appendParticleVertex(t++, r, 0, 1))
    }
    ,
    e.prototype.rebuild = function() {
        var t, r;
        this._engine.getCaps().vertexArrayObject && (this._vertexArrayObject = null),
        this._createIndexBuffer(),
        (t = this._spriteBuffer) === null || t === void 0 || t._rebuild(),
        (r = this._vertexBuffer) === null || r === void 0 || r._rebuild();
        for (var n in this._vertexBuffers)
            this._vertexBuffers[n]._rebuild();
        this.resetDrawCache()
    }
    ,
    e.prototype.isReady = function() {
        if (!this.emitter || this._imageProcessingConfiguration && !this._imageProcessingConfiguration.isReady() || !this.particleTexture || !this.particleTexture.isReady())
            return !1;
        if (this.blendMode !== e.BLENDMODE_MULTIPLYADD) {
            if (!this._getWrapper(this.blendMode).effect.isReady())
                return !1
        } else if (!this._getWrapper(e.BLENDMODE_MULTIPLY).effect.isReady() || !this._getWrapper(e.BLENDMODE_ADD).effect.isReady())
            return !1;
        return !0
    }
    ,
    e.prototype._render = function(t) {
        var r, n, o = this._getWrapper(t), a = o.effect, s = this._engine;
        s.enableEffect(o);
        var l = (r = this.defaultViewMatrix) !== null && r !== void 0 ? r : this._scene.getViewMatrix();
        if (a.setTexture("diffuseSampler", this.particleTexture),
        a.setMatrix("view", l),
        a.setMatrix("projection", (n = this.defaultProjectionMatrix) !== null && n !== void 0 ? n : this._scene.getProjectionMatrix()),
        this._isAnimationSheetEnabled && this.particleTexture) {
            var u = this.particleTexture.getBaseSize();
            a.setFloat3("particlesInfos", this.spriteCellWidth / u.width, this.spriteCellHeight / u.height, this.spriteCellWidth / u.width)
        }
        if (a.setVector2("translationPivot", this.translationPivot),
        a.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a),
        this._isBillboardBased && this._scene) {
            var c = this._scene.activeCamera;
            a.setVector3("eyePosition", c.globalPosition)
        }
        this._rampGradientsTexture && ((!this._rampGradients || !this._rampGradients.length) && (this._rampGradientsTexture.dispose(),
        this._rampGradientsTexture = null),
        a.setTexture("rampSampler", this._rampGradientsTexture));
        var h = a.defines;
        switch (this._scene && (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4 || this._scene.clipPlane5 || this._scene.clipPlane6) && ThinMaterialHelper.BindClipPlane(a, this._scene),
        h.indexOf("#define BILLBOARDMODE_ALL") >= 0 && (l.invertToRef(TmpVectors.Matrix[0]),
        a.setMatrix("invView", TmpVectors.Matrix[0])),
        this._vertexArrayObject !== void 0 ? (this._vertexArrayObject || (this._vertexArrayObject = this._engine.recordVertexArrayObject(this._vertexBuffers, this._indexBuffer, a)),
        this._engine.bindVertexArrayObject(this._vertexArrayObject, this._indexBuffer)) : s.bindBuffers(this._vertexBuffers, this._indexBuffer, a),
        this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess && this._imageProcessingConfiguration.bind(a),
        t) {
        case e.BLENDMODE_ADD:
            s.setAlphaMode(1);
            break;
        case e.BLENDMODE_ONEONE:
            s.setAlphaMode(6);
            break;
        case e.BLENDMODE_STANDARD:
            s.setAlphaMode(2);
            break;
        case e.BLENDMODE_MULTIPLY:
            s.setAlphaMode(4);
            break
        }
        return this._onBeforeDrawParticlesObservable && this._onBeforeDrawParticlesObservable.notifyObservers(a),
        this._useInstancing ? s.drawArraysType(7, 0, 4, this._particles.length) : s.drawElementsType(0, 0, this._particles.length * 6),
        this._particles.length
    }
    ,
    e.prototype.render = function() {
        if (!this.isReady() || !this._particles.length)
            return 0;
        var t = this._engine;
        t.setState && (t.setState(!1),
        this.forceDepthWrite && t.setDepthWrite(!0));
        var r = 0;
        return this.blendMode === e.BLENDMODE_MULTIPLYADD ? r = this._render(e.BLENDMODE_MULTIPLY) + this._render(e.BLENDMODE_ADD) : r = this._render(this.blendMode),
        this._engine.unbindInstanceAttributes(),
        this._engine.setAlphaMode(0),
        r
    }
    ,
    e.prototype.dispose = function(t) {
        if (t === void 0 && (t = !0),
        this.resetDrawCache(),
        this._vertexBuffer && (this._vertexBuffer.dispose(),
        this._vertexBuffer = null),
        this._spriteBuffer && (this._spriteBuffer.dispose(),
        this._spriteBuffer = null),
        this._indexBuffer && (this._engine._releaseBuffer(this._indexBuffer),
        this._indexBuffer = null),
        this._vertexArrayObject && (this._engine.releaseVertexArrayObject(this._vertexArrayObject),
        this._vertexArrayObject = null),
        t && this.particleTexture && (this.particleTexture.dispose(),
        this.particleTexture = null),
        t && this.noiseTexture && (this.noiseTexture.dispose(),
        this.noiseTexture = null),
        this._rampGradientsTexture && (this._rampGradientsTexture.dispose(),
        this._rampGradientsTexture = null),
        this._removeFromRoot(),
        this._subEmitters && this._subEmitters.length) {
            for (var r = 0; r < this._subEmitters.length; r++)
                for (var n = 0, o = this._subEmitters[r]; n < o.length; n++) {
                    var a = o[n];
                    a.dispose()
                }
            this._subEmitters = [],
            this.subEmitters = []
        }
        if (this._disposeEmitterOnDispose && this.emitter && this.emitter.dispose && this.emitter.dispose(!0),
        this._onBeforeDrawParticlesObservable && this._onBeforeDrawParticlesObservable.clear(),
        this._scene) {
            var r = this._scene.particleSystems.indexOf(this);
            r > -1 && this._scene.particleSystems.splice(r, 1),
            this._scene._activeParticleSystems.dispose()
        }
        this.onDisposeObservable.notifyObservers(this),
        this.onDisposeObservable.clear(),
        this.onStoppedObservable.clear(),
        this.reset()
    }
    ,
    e.prototype.clone = function(t, r) {
        var n = __assign({}, this._customWrappers)
          , o = null
          , a = this._engine;
        if (a.createEffectForParticles && this.customShader != null) {
            o = this.customShader;
            var s = o.shaderOptions.defines.length > 0 ? o.shaderOptions.defines.join(`
`) : "";
            n[0] = a.createEffectForParticles(o.shaderPath.fragmentElement, o.shaderOptions.uniforms, o.shaderOptions.samplers, s)
        }
        var l = this.serialize()
          , u = e.Parse(l, this._scene || this._engine, this._rootUrl);
        return u.name = t,
        u.customShader = o,
        u._customWrappers = n,
        r === void 0 && (r = this.emitter),
        this.noiseTexture && (u.noiseTexture = this.noiseTexture.clone()),
        u.emitter = r,
        this.preventAutoStart || u.start(),
        u
    }
    ,
    e.prototype.serialize = function(t) {
        t === void 0 && (t = !1);
        var r = {};
        if (e._Serialize(r, this, t),
        r.textureMask = this.textureMask.asArray(),
        r.customShader = this.customShader,
        r.preventAutoStart = this.preventAutoStart,
        this.subEmitters) {
            r.subEmitters = [],
            this._subEmitters || this._prepareSubEmitterInternalArray();
            for (var n = 0, o = this._subEmitters; n < o.length; n++) {
                for (var a = o[n], s = [], l = 0, u = a; l < u.length; l++) {
                    var c = u[l];
                    s.push(c.serialize(t))
                }
                r.subEmitters.push(s)
            }
        }
        return r
    }
    ,
    e._Serialize = function(t, r, n) {
        if (t.name = r.name,
        t.id = r.id,
        t.capacity = r.getCapacity(),
        t.disposeOnStop = r.disposeOnStop,
        t.manualEmitCount = r.manualEmitCount,
        r.emitter.position) {
            var o = r.emitter;
            t.emitterId = o.id
        } else {
            var a = r.emitter;
            t.emitter = a.asArray()
        }
        r.particleEmitterType && (t.particleEmitterType = r.particleEmitterType.serialize()),
        r.particleTexture && (n ? t.texture = r.particleTexture.serialize() : (t.textureName = r.particleTexture.name,
        t.invertY = !!r.particleTexture._invertY)),
        t.isLocal = r.isLocal,
        SerializationHelper.AppendSerializedAnimations(r, t),
        t.beginAnimationOnStart = r.beginAnimationOnStart,
        t.beginAnimationFrom = r.beginAnimationFrom,
        t.beginAnimationTo = r.beginAnimationTo,
        t.beginAnimationLoop = r.beginAnimationLoop,
        t.startDelay = r.startDelay,
        t.renderingGroupId = r.renderingGroupId,
        t.isBillboardBased = r.isBillboardBased,
        t.billboardMode = r.billboardMode,
        t.minAngularSpeed = r.minAngularSpeed,
        t.maxAngularSpeed = r.maxAngularSpeed,
        t.minSize = r.minSize,
        t.maxSize = r.maxSize,
        t.minScaleX = r.minScaleX,
        t.maxScaleX = r.maxScaleX,
        t.minScaleY = r.minScaleY,
        t.maxScaleY = r.maxScaleY,
        t.minEmitPower = r.minEmitPower,
        t.maxEmitPower = r.maxEmitPower,
        t.minLifeTime = r.minLifeTime,
        t.maxLifeTime = r.maxLifeTime,
        t.emitRate = r.emitRate,
        t.gravity = r.gravity.asArray(),
        t.noiseStrength = r.noiseStrength.asArray(),
        t.color1 = r.color1.asArray(),
        t.color2 = r.color2.asArray(),
        t.colorDead = r.colorDead.asArray(),
        t.updateSpeed = r.updateSpeed,
        t.targetStopDuration = r.targetStopDuration,
        t.blendMode = r.blendMode,
        t.preWarmCycles = r.preWarmCycles,
        t.preWarmStepOffset = r.preWarmStepOffset,
        t.minInitialRotation = r.minInitialRotation,
        t.maxInitialRotation = r.maxInitialRotation,
        t.startSpriteCellID = r.startSpriteCellID,
        t.spriteCellLoop = r.spriteCellLoop,
        t.endSpriteCellID = r.endSpriteCellID,
        t.spriteCellChangeSpeed = r.spriteCellChangeSpeed,
        t.spriteCellWidth = r.spriteCellWidth,
        t.spriteCellHeight = r.spriteCellHeight,
        t.spriteRandomStartCell = r.spriteRandomStartCell,
        t.isAnimationSheetEnabled = r.isAnimationSheetEnabled;
        var s = r.getColorGradients();
        if (s) {
            t.colorGradients = [];
            for (var l = 0, u = s; l < u.length; l++) {
                var c = u[l]
                  , h = {
                    gradient: c.gradient,
                    color1: c.color1.asArray()
                };
                c.color2 ? h.color2 = c.color2.asArray() : h.color2 = c.color1.asArray(),
                t.colorGradients.push(h)
            }
        }
        var f = r.getRampGradients();
        if (f) {
            t.rampGradients = [];
            for (var d = 0, _ = f; d < _.length; d++) {
                var g = _[d]
                  , h = {
                    gradient: g.gradient,
                    color: g.color.asArray()
                };
                t.rampGradients.push(h)
            }
            t.useRampGradients = r.useRampGradients
        }
        var m = r.getColorRemapGradients();
        if (m) {
            t.colorRemapGradients = [];
            for (var v = 0, y = m; v < y.length; v++) {
                var b = y[v]
                  , h = {
                    gradient: b.gradient,
                    factor1: b.factor1
                };
                b.factor2 !== void 0 ? h.factor2 = b.factor2 : h.factor2 = b.factor1,
                t.colorRemapGradients.push(h)
            }
        }
        var T = r.getAlphaRemapGradients();
        if (T) {
            t.alphaRemapGradients = [];
            for (var C = 0, A = T; C < A.length; C++) {
                var S = A[C]
                  , h = {
                    gradient: S.gradient,
                    factor1: S.factor1
                };
                S.factor2 !== void 0 ? h.factor2 = S.factor2 : h.factor2 = S.factor1,
                t.alphaRemapGradients.push(h)
            }
        }
        var P = r.getSizeGradients();
        if (P) {
            t.sizeGradients = [];
            for (var R = 0, M = P; R < M.length; R++) {
                var x = M[R]
                  , h = {
                    gradient: x.gradient,
                    factor1: x.factor1
                };
                x.factor2 !== void 0 ? h.factor2 = x.factor2 : h.factor2 = x.factor1,
                t.sizeGradients.push(h)
            }
        }
        var I = r.getAngularSpeedGradients();
        if (I) {
            t.angularSpeedGradients = [];
            for (var w = 0, O = I; w < O.length; w++) {
                var D = O[w]
                  , h = {
                    gradient: D.gradient,
                    factor1: D.factor1
                };
                D.factor2 !== void 0 ? h.factor2 = D.factor2 : h.factor2 = D.factor1,
                t.angularSpeedGradients.push(h)
            }
        }
        var F = r.getVelocityGradients();
        if (F) {
            t.velocityGradients = [];
            for (var V = 0, N = F; V < N.length; V++) {
                var L = N[V]
                  , h = {
                    gradient: L.gradient,
                    factor1: L.factor1
                };
                L.factor2 !== void 0 ? h.factor2 = L.factor2 : h.factor2 = L.factor1,
                t.velocityGradients.push(h)
            }
        }
        var k = r.getDragGradients();
        if (k) {
            t.dragGradients = [];
            for (var U = 0, z = k; U < z.length; U++) {
                var H = z[U]
                  , h = {
                    gradient: H.gradient,
                    factor1: H.factor1
                };
                H.factor2 !== void 0 ? h.factor2 = H.factor2 : h.factor2 = H.factor1,
                t.dragGradients.push(h)
            }
        }
        var G = r.getEmitRateGradients();
        if (G) {
            t.emitRateGradients = [];
            for (var W = 0, j = G; W < j.length; W++) {
                var B = j[W]
                  , h = {
                    gradient: B.gradient,
                    factor1: B.factor1
                };
                B.factor2 !== void 0 ? h.factor2 = B.factor2 : h.factor2 = B.factor1,
                t.emitRateGradients.push(h)
            }
        }
        var X = r.getStartSizeGradients();
        if (X) {
            t.startSizeGradients = [];
            for (var $ = 0, Y = X; $ < Y.length; $++) {
                var K = Y[$]
                  , h = {
                    gradient: K.gradient,
                    factor1: K.factor1
                };
                K.factor2 !== void 0 ? h.factor2 = K.factor2 : h.factor2 = K.factor1,
                t.startSizeGradients.push(h)
            }
        }
        var Z = r.getLifeTimeGradients();
        if (Z) {
            t.lifeTimeGradients = [];
            for (var q = 0, J = Z; q < J.length; q++) {
                var Q = J[q]
                  , h = {
                    gradient: Q.gradient,
                    factor1: Q.factor1
                };
                Q.factor2 !== void 0 ? h.factor2 = Q.factor2 : h.factor2 = Q.factor1,
                t.lifeTimeGradients.push(h)
            }
        }
        var te = r.getLimitVelocityGradients();
        if (te) {
            t.limitVelocityGradients = [];
            for (var re = 0, ie = te; re < ie.length; re++) {
                var ee = ie[re]
                  , h = {
                    gradient: ee.gradient,
                    factor1: ee.factor1
                };
                ee.factor2 !== void 0 ? h.factor2 = ee.factor2 : h.factor2 = ee.factor1,
                t.limitVelocityGradients.push(h)
            }
            t.limitVelocityDamping = r.limitVelocityDamping
        }
        r.noiseTexture && (t.noiseTexture = r.noiseTexture.serialize())
    }
    ,
    e._Parse = function(t, r, n, o) {
        var a, s, l, u;
        n instanceof ThinEngine ? u = null : u = n;
        var c = GetClass("BABYLON.Texture");
        if (c && u && (t.texture ? r.particleTexture = c.Parse(t.texture, u, o) : t.textureName && (r.particleTexture = new c(o + t.textureName,u,!1,t.invertY !== void 0 ? t.invertY : !0),
        r.particleTexture.name = t.textureName)),
        !t.emitterId && t.emitterId !== 0 && t.emitter === void 0 ? r.emitter = Vector3.Zero() : t.emitterId && u ? r.emitter = u.getLastMeshById(t.emitterId) : r.emitter = Vector3.FromArray(t.emitter),
        r.isLocal = !!t.isLocal,
        t.renderingGroupId !== void 0 && (r.renderingGroupId = t.renderingGroupId),
        t.isBillboardBased !== void 0 && (r.isBillboardBased = t.isBillboardBased),
        t.billboardMode !== void 0 && (r.billboardMode = t.billboardMode),
        t.animations) {
            for (var h = 0; h < t.animations.length; h++) {
                var f = t.animations[h]
                  , d = GetClass("BABYLON.Animation");
                d && r.animations.push(d.Parse(f))
            }
            r.beginAnimationOnStart = t.beginAnimationOnStart,
            r.beginAnimationFrom = t.beginAnimationFrom,
            r.beginAnimationTo = t.beginAnimationTo,
            r.beginAnimationLoop = t.beginAnimationLoop
        }
        if (t.autoAnimate && u && u.beginAnimation(r, t.autoAnimateFrom, t.autoAnimateTo, t.autoAnimateLoop, t.autoAnimateSpeed || 1),
        r.startDelay = t.startDelay | 0,
        r.minAngularSpeed = t.minAngularSpeed,
        r.maxAngularSpeed = t.maxAngularSpeed,
        r.minSize = t.minSize,
        r.maxSize = t.maxSize,
        t.minScaleX && (r.minScaleX = t.minScaleX,
        r.maxScaleX = t.maxScaleX,
        r.minScaleY = t.minScaleY,
        r.maxScaleY = t.maxScaleY),
        t.preWarmCycles !== void 0 && (r.preWarmCycles = t.preWarmCycles,
        r.preWarmStepOffset = t.preWarmStepOffset),
        t.minInitialRotation !== void 0 && (r.minInitialRotation = t.minInitialRotation,
        r.maxInitialRotation = t.maxInitialRotation),
        r.minLifeTime = t.minLifeTime,
        r.maxLifeTime = t.maxLifeTime,
        r.minEmitPower = t.minEmitPower,
        r.maxEmitPower = t.maxEmitPower,
        r.emitRate = t.emitRate,
        r.gravity = Vector3.FromArray(t.gravity),
        t.noiseStrength && (r.noiseStrength = Vector3.FromArray(t.noiseStrength)),
        r.color1 = Color4.FromArray(t.color1),
        r.color2 = Color4.FromArray(t.color2),
        r.colorDead = Color4.FromArray(t.colorDead),
        r.updateSpeed = t.updateSpeed,
        r.targetStopDuration = t.targetStopDuration,
        r.blendMode = t.blendMode,
        t.colorGradients)
            for (var _ = 0, g = t.colorGradients; _ < g.length; _++) {
                var m = g[_];
                r.addColorGradient(m.gradient, Color4.FromArray(m.color1), m.color2 ? Color4.FromArray(m.color2) : void 0)
            }
        if (t.rampGradients) {
            for (var v = 0, y = t.rampGradients; v < y.length; v++) {
                var b = y[v];
                r.addRampGradient(b.gradient, Color3.FromArray(b.color))
            }
            r.useRampGradients = t.useRampGradients
        }
        if (t.colorRemapGradients)
            for (var T = 0, C = t.colorRemapGradients; T < C.length; T++) {
                var A = C[T];
                r.addColorRemapGradient(A.gradient, A.factor1 !== void 0 ? A.factor1 : A.factor, A.factor2)
            }
        if (t.alphaRemapGradients)
            for (var S = 0, P = t.alphaRemapGradients; S < P.length; S++) {
                var R = P[S];
                r.addAlphaRemapGradient(R.gradient, R.factor1 !== void 0 ? R.factor1 : R.factor, R.factor2)
            }
        if (t.sizeGradients)
            for (var M = 0, x = t.sizeGradients; M < x.length; M++) {
                var I = x[M];
                r.addSizeGradient(I.gradient, I.factor1 !== void 0 ? I.factor1 : I.factor, I.factor2)
            }
        if (t.angularSpeedGradients)
            for (var w = 0, O = t.angularSpeedGradients; w < O.length; w++) {
                var D = O[w];
                r.addAngularSpeedGradient(D.gradient, D.factor1 !== void 0 ? D.factor1 : D.factor, D.factor2)
            }
        if (t.velocityGradients)
            for (var F = 0, V = t.velocityGradients; F < V.length; F++) {
                var N = V[F];
                r.addVelocityGradient(N.gradient, N.factor1 !== void 0 ? N.factor1 : N.factor, N.factor2)
            }
        if (t.dragGradients)
            for (var L = 0, k = t.dragGradients; L < k.length; L++) {
                var U = k[L];
                r.addDragGradient(U.gradient, U.factor1 !== void 0 ? U.factor1 : U.factor, U.factor2)
            }
        if (t.emitRateGradients)
            for (var z = 0, H = t.emitRateGradients; z < H.length; z++) {
                var G = H[z];
                r.addEmitRateGradient(G.gradient, G.factor1 !== void 0 ? G.factor1 : G.factor, G.factor2)
            }
        if (t.startSizeGradients)
            for (var W = 0, j = t.startSizeGradients; W < j.length; W++) {
                var B = j[W];
                r.addStartSizeGradient(B.gradient, B.factor1 !== void 0 ? B.factor1 : B.factor, B.factor2)
            }
        if (t.lifeTimeGradients)
            for (var X = 0, $ = t.lifeTimeGradients; X < $.length; X++) {
                var Y = $[X];
                r.addLifeTimeGradient(Y.gradient, Y.factor1 !== void 0 ? Y.factor1 : Y.factor, Y.factor2)
            }
        if (t.limitVelocityGradients) {
            for (var K = 0, Z = t.limitVelocityGradients; K < Z.length; K++) {
                var q = Z[K];
                r.addLimitVelocityGradient(q.gradient, q.factor1 !== void 0 ? q.factor1 : q.factor, q.factor2)
            }
            r.limitVelocityDamping = t.limitVelocityDamping
        }
        if (t.noiseTexture && u) {
            var J = GetClass("BABYLON.ProceduralTexture");
            r.noiseTexture = J.Parse(t.noiseTexture, u, o)
        }
        var Q;
        if (t.particleEmitterType) {
            switch (t.particleEmitterType.type) {
            case "SphereParticleEmitter":
                Q = new SphereParticleEmitter;
                break;
            case "SphereDirectedParticleEmitter":
                Q = new SphereDirectedParticleEmitter;
                break;
            case "ConeEmitter":
            case "ConeParticleEmitter":
                Q = new ConeParticleEmitter;
                break;
            case "CylinderParticleEmitter":
                Q = new CylinderParticleEmitter;
                break;
            case "CylinderDirectedParticleEmitter":
                Q = new CylinderDirectedParticleEmitter;
                break;
            case "HemisphericParticleEmitter":
                Q = new HemisphericParticleEmitter;
                break;
            case "PointParticleEmitter":
                Q = new PointParticleEmitter;
                break;
            case "MeshParticleEmitter":
                Q = new MeshParticleEmitter;
                break;
            case "BoxEmitter":
            case "BoxParticleEmitter":
            default:
                Q = new BoxParticleEmitter;
                break
            }
            Q.parse(t.particleEmitterType, u)
        } else
            Q = new BoxParticleEmitter,
            Q.parse(t, u);
        r.particleEmitterType = Q,
        r.startSpriteCellID = t.startSpriteCellID,
        r.endSpriteCellID = t.endSpriteCellID,
        r.spriteCellLoop = (a = t.spriteCellLoop) !== null && a !== void 0 ? a : !0,
        r.spriteCellWidth = t.spriteCellWidth,
        r.spriteCellHeight = t.spriteCellHeight,
        r.spriteCellChangeSpeed = t.spriteCellChangeSpeed,
        r.spriteRandomStartCell = t.spriteRandomStartCell,
        r.disposeOnStop = (s = t.disposeOnStop) !== null && s !== void 0 ? s : !1,
        r.manualEmitCount = (l = t.manualEmitCount) !== null && l !== void 0 ? l : -1
    }
    ,
    e.Parse = function(t, r, n, o, a) {
        o === void 0 && (o = !1);
        var s = t.name, l = null, u = null, c, h;
        if (r instanceof ThinEngine ? c = r : (h = r,
        c = h.getEngine()),
        t.customShader && c.createEffectForParticles) {
            u = t.customShader;
            var f = u.shaderOptions.defines.length > 0 ? u.shaderOptions.defines.join(`
`) : "";
            l = c.createEffectForParticles(u.shaderPath.fragmentElement, u.shaderOptions.uniforms, u.shaderOptions.samplers, f)
        }
        var d = new e(s,a || t.capacity,r,l,t.isAnimationSheetEnabled);
        if (d.customShader = u,
        d._rootUrl = n,
        t.id && (d.id = t.id),
        t.subEmitters) {
            d.subEmitters = [];
            for (var _ = 0, g = t.subEmitters; _ < g.length; _++) {
                for (var m = g[_], v = [], y = 0, b = m; y < b.length; y++) {
                    var T = b[y];
                    v.push(SubEmitter.Parse(T, r, n))
                }
                d.subEmitters.push(v)
            }
        }
        return e._Parse(t, d, r, n),
        t.textureMask && (d.textureMask = Color4.FromArray(t.textureMask)),
        t.preventAutoStart && (d.preventAutoStart = t.preventAutoStart),
        !o && !d.preventAutoStart && d.start(),
        d
    }
    ,
    e.BILLBOARDMODE_Y = 2,
    e.BILLBOARDMODE_ALL = 7,
    e.BILLBOARDMODE_STRETCHED = 8,
    e
}(BaseParticleSystem);
SubEmitter._ParseParticleSystem = ParticleSystem.Parse;
var name$1F = "clipPlaneFragmentDeclaration2"
  , shader$1F = `#ifdef CLIPPLANE
in float fClipDistance;
#endif
#ifdef CLIPPLANE2
in float fClipDistance2;
#endif
#ifdef CLIPPLANE3
in float fClipDistance3;
#endif
#ifdef CLIPPLANE4
in float fClipDistance4;
#endif
#ifdef CLIPPLANE5
in float fClipDistance5;
#endif
#ifdef CLIPPLANE6
in float fClipDistance6;
#endif`;
ShaderStore.IncludesShadersStore[name$1F] = shader$1F;
var name$1E = "gpuRenderParticlesPixelShader"
  , shader$1E = `precision highp float;
uniform sampler2D diffuseSampler;
varying vec2 vUV;
varying vec4 vColor;
#include<clipPlaneFragmentDeclaration2>
#include<imageProcessingDeclaration>
#include<helperFunctions>
#include<imageProcessingFunctions>
void main() {
#include<clipPlaneFragment>
vec4 textureColor=texture2D(diffuseSampler,vUV);
gl_FragColor=textureColor*vColor;
#ifdef BLENDMULTIPLYMODE
float alpha=vColor.a*textureColor.a;
gl_FragColor.rgb=gl_FragColor.rgb*alpha+vec3(1.0)*(1.0-alpha);
#endif


#ifdef IMAGEPROCESSINGPOSTPROCESS
gl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb);
#else
#ifdef IMAGEPROCESSING
gl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb);
gl_FragColor=applyImageProcessing(gl_FragColor);
#endif
#endif
}
`;
ShaderStore.ShadersStore[name$1E] = shader$1E;
var name$1D = "clipPlaneVertexDeclaration2"
  , shader$1D = `#ifdef CLIPPLANE
uniform vec4 vClipPlane;
out float fClipDistance;
#endif
#ifdef CLIPPLANE2
uniform vec4 vClipPlane2;
out float fClipDistance2;
#endif
#ifdef CLIPPLANE3
uniform vec4 vClipPlane3;
out float fClipDistance3;
#endif
#ifdef CLIPPLANE4
uniform vec4 vClipPlane4;
out float fClipDistance4;
#endif
#ifdef CLIPPLANE5
uniform vec4 vClipPlane5;
out float fClipDistance5;
#endif
#ifdef CLIPPLANE6
uniform vec4 vClipPlane6;
out float fClipDistance6;
#endif`;
ShaderStore.IncludesShadersStore[name$1D] = shader$1D;
var name$1C = "gpuRenderParticlesVertexShader"
  , shader$1C = `precision highp float;
uniform mat4 view;
uniform mat4 projection;
uniform vec2 translationPivot;
uniform vec3 worldOffset;
#ifdef LOCAL
uniform mat4 emitterWM;
#endif

attribute vec3 position;
attribute float age;
attribute float life;
attribute vec3 size;
#ifndef BILLBOARD
attribute vec3 initialDirection;
#endif
#ifdef BILLBOARDSTRETCHED
attribute vec3 direction;
#endif
attribute float angle;
#ifdef ANIMATESHEET
attribute float cellIndex;
#endif
attribute vec2 offset;
attribute vec2 uv;
varying vec2 vUV;
varying vec4 vColor;
varying vec3 vPositionW;
#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED)
uniform mat4 invView;
#endif
#include<clipPlaneVertexDeclaration2>
#ifdef COLORGRADIENTS
uniform sampler2D colorGradientSampler;
#else
uniform vec4 colorDead;
attribute vec4 color;
#endif
#ifdef ANIMATESHEET
uniform vec3 sheetInfos;
#endif
#ifdef BILLBOARD
uniform vec3 eyePosition;
#endif
vec3 rotate(vec3 yaxis,vec3 rotatedCorner) {
vec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));
vec3 zaxis=normalize(cross(yaxis,xaxis));
vec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);
vec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);
vec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);
mat3 rotMatrix=mat3(row0,row1,row2);
vec3 alignedCorner=rotMatrix*rotatedCorner;
#ifdef LOCAL
return ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner;
#else
return (position+worldOffset)+alignedCorner;
#endif
}
#ifdef BILLBOARDSTRETCHED
vec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {
vec3 normalizedToCamera=normalize(toCamera);
vec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));
vec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));
vec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);
vec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);
vec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);
mat3 rotMatrix=mat3(row0,row1,row2);
vec3 alignedCorner=rotMatrix*rotatedCorner;
#ifdef LOCAL
return ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner;
#else
return (position+worldOffset)+alignedCorner;
#endif
}
#endif
void main() {
#ifdef ANIMATESHEET
float rowOffset=floor(cellIndex/sheetInfos.z);
float columnOffset=cellIndex-rowOffset*sheetInfos.z;
vec2 uvScale=sheetInfos.xy;
vec2 uvOffset=vec2(uv.x ,1.0-uv.y);
vUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;
#else
vUV=uv;
#endif
float ratio=age/life;
#ifdef COLORGRADIENTS
vColor=texture2D(colorGradientSampler,vec2(ratio,0));
#else
vColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);
#endif
vec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;
#ifdef BILLBOARD
vec4 rotatedCorner;
rotatedCorner.w=0.;
#ifdef BILLBOARDY
rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);
rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);
rotatedCorner.y=0.;
vec3 yaxis=(position+worldOffset)-eyePosition;
yaxis.y=0.;
vPositionW=rotate(normalize(yaxis),rotatedCorner.xyz);
vec4 viewPosition=(view*vec4(vPositionW,1.0));
#elif defined(BILLBOARDSTRETCHED)
rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);
rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);
rotatedCorner.z=0.;
vec3 toCamera=(position+worldOffset)-eyePosition;
vPositionW=rotateAlign(toCamera,rotatedCorner.xyz);
vec4 viewPosition=(view*vec4(vPositionW,1.0));
#else

rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);
rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);
rotatedCorner.z=0.;

#ifdef LOCAL
vec4 viewPosition=view*vec4(((emitterWM*vec4(position,1.0)).xyz+worldOffset),1.0)+rotatedCorner;
#else
vec4 viewPosition=view*vec4((position+worldOffset),1.0)+rotatedCorner;
#endif
vPositionW=(invView*viewPosition).xyz;
#endif
#else

vec3 rotatedCorner;
rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);
rotatedCorner.y=0.;
rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);
vec3 yaxis=normalize(initialDirection);
vPositionW=rotate(yaxis,rotatedCorner);

vec4 viewPosition=view*vec4(vPositionW,1.0);
#endif
gl_Position=projection*viewPosition;

#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)
vec4 worldPos=vec4(vPositionW,1.0);
#endif
#include<clipPlaneVertex>
}`;
ShaderStore.ShadersStore[name$1C] = shader$1C;
var GPUParticleSystem = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a) {
        o === void 0 && (o = null),
        a === void 0 && (a = !1);
        var s = i.call(this, t) || this;
        if (s.layerMask = 268435455,
        s._accumulatedCount = 0,
        s._targetIndex = 0,
        s._currentRenderId = -1,
        s._currentRenderingCameraUniqueId = -1,
        s._started = !1,
        s._stopped = !1,
        s._timeDelta = 0,
        s._actualFrame = 0,
        s._rawTextureWidth = 256,
        s.onDisposeObservable = new Observable,
        s.onStoppedObservable = new Observable,
        s.forceDepthWrite = !1,
        s._preWarmDone = !1,
        s.isLocal = !1,
        s._onBeforeDrawParticlesObservable = null,
        !n || n.getClassName() === "Scene" ? (s._scene = n || EngineStore.LastCreatedScene,
        s._engine = s._scene.getEngine(),
        s.uniqueId = s._scene.getUniqueId(),
        s._scene.particleSystems.push(s)) : (s._engine = n,
        s.defaultProjectionMatrix = Matrix.PerspectiveFovLH(.8, 1, .1, 100, s._engine.isNDCHalfZRange)),
        s._engine.getCaps().supportComputeShaders) {
            if (!GetClass("BABYLON.ComputeShaderParticleSystem"))
                throw new Error("The ComputeShaderParticleSystem class is not available! Make sure you have imported it.");
            s._platform = new (GetClass("BABYLON.ComputeShaderParticleSystem"))(s,s._engine)
        } else {
            if (!GetClass("BABYLON.WebGL2ParticleSystem"))
                throw new Error("The WebGL2ParticleSystem class is not available! Make sure you have imported it.");
            s._platform = new (GetClass("BABYLON.WebGL2ParticleSystem"))(s,s._engine)
        }
        s._customWrappers = {
            0: new DrawWrapper(s._engine)
        },
        s._customWrappers[0].effect = o,
        s._drawWrappers = {
            0: new DrawWrapper(s._engine)
        },
        s._drawWrappers[0].drawContext && (s._drawWrappers[0].drawContext.useInstancing = !0),
        s._attachImageProcessingConfiguration(null),
        r = r != null ? r : {},
        r.randomTextureSize || delete r.randomTextureSize;
        var l = __assign({
            capacity: 5e4,
            randomTextureSize: s._engine.getCaps().maxTextureSize
        }, r)
          , u = r;
        isFinite(u) && (l.capacity = u),
        s._capacity = l.capacity,
        s._activeCount = l.capacity,
        s._currentActiveCount = 0,
        s._isAnimationSheetEnabled = a,
        s.particleEmitterType = new BoxParticleEmitter;
        for (var c = Math.min(s._engine.getCaps().maxTextureSize, l.randomTextureSize), h = [], f = 0; f < c; ++f)
            h.push(Math.random()),
            h.push(Math.random()),
            h.push(Math.random()),
            h.push(Math.random());
        s._randomTexture = new RawTexture(new Float32Array(h),c,1,5,n,!1,!1,1,1),
        s._randomTexture.name = "GPUParticleSystem_random1",
        s._randomTexture.wrapU = 1,
        s._randomTexture.wrapV = 1,
        h = [];
        for (var f = 0; f < c; ++f)
            h.push(Math.random()),
            h.push(Math.random()),
            h.push(Math.random()),
            h.push(Math.random());
        return s._randomTexture2 = new RawTexture(new Float32Array(h),c,1,5,n,!1,!1,1,1),
        s._randomTexture2.name = "GPUParticleSystem_random2",
        s._randomTexture2.wrapU = 1,
        s._randomTexture2.wrapV = 1,
        s._randomTextureSize = c,
        s
    }
    return Object.defineProperty(e, "IsSupported", {
        get: function() {
            return EngineStore.LastCreatedEngine ? EngineStore.LastCreatedEngine.name === "WebGL" && EngineStore.LastCreatedEngine.version > 1 || EngineStore.LastCreatedEngine.getCaps().supportComputeShaders : !1
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getCapacity = function() {
        return this._capacity
    }
    ,
    Object.defineProperty(e.prototype, "activeParticleCount", {
        get: function() {
            return this._activeCount
        },
        set: function(t) {
            this._activeCount = Math.min(t, this._capacity)
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.isReady = function() {
        if (!this.emitter || this._imageProcessingConfiguration && !this._imageProcessingConfiguration.isReady() || !this.particleTexture || !this.particleTexture.isReady())
            return !1;
        if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) {
            if (!this._getWrapper(this.blendMode).effect.isReady())
                return !1
        } else if (!this._getWrapper(ParticleSystem.BLENDMODE_MULTIPLY).effect.isReady() || !this._getWrapper(ParticleSystem.BLENDMODE_ADD).effect.isReady())
            return !1;
        return this._platform.isUpdateBufferCreated() ? this._platform.isUpdateBufferReady() : (this._recreateUpdateEffect(),
        !1)
    }
    ,
    e.prototype.isStarted = function() {
        return this._started
    }
    ,
    e.prototype.isStopped = function() {
        return this._stopped
    }
    ,
    e.prototype.isStopping = function() {
        return !1
    }
    ,
    e.prototype.getActiveCount = function() {
        return this._currentActiveCount
    }
    ,
    e.prototype.start = function(t) {
        var r = this;
        if (t === void 0 && (t = this.startDelay),
        !this.targetStopDuration && this._hasTargetStopDurationDependantGradient())
            throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
        if (t) {
            setTimeout(function() {
                r.start(0)
            }, t);
            return
        }
        this._started = !0,
        this._stopped = !1,
        this._preWarmDone = !1,
        this.beginAnimationOnStart && this.animations && this.animations.length > 0 && this._scene && this._scene.beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop)
    }
    ,
    e.prototype.stop = function() {
        this._stopped || (this._stopped = !0)
    }
    ,
    e.prototype.reset = function() {
        this._releaseBuffers(),
        this._platform.releaseVertexBuffers(),
        this._currentActiveCount = 0,
        this._targetIndex = 0
    }
    ,
    e.prototype.getClassName = function() {
        return "GPUParticleSystem"
    }
    ,
    e.prototype.getCustomEffect = function(t) {
        var r, n;
        return t === void 0 && (t = 0),
        (n = (r = this._customWrappers[t]) === null || r === void 0 ? void 0 : r.effect) !== null && n !== void 0 ? n : this._customWrappers[0].effect
    }
    ,
    e.prototype._getCustomDrawWrapper = function(t) {
        var r;
        return t === void 0 && (t = 0),
        (r = this._customWrappers[t]) !== null && r !== void 0 ? r : this._customWrappers[0]
    }
    ,
    e.prototype.setCustomEffect = function(t, r) {
        r === void 0 && (r = 0),
        this._customWrappers[r] = new DrawWrapper(this._engine),
        this._customWrappers[r].effect = t
    }
    ,
    Object.defineProperty(e.prototype, "onBeforeDrawParticlesObservable", {
        get: function() {
            return this._onBeforeDrawParticlesObservable || (this._onBeforeDrawParticlesObservable = new Observable),
            this._onBeforeDrawParticlesObservable
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "vertexShaderName", {
        get: function() {
            return "gpuRenderParticles"
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._removeGradientAndTexture = function(t, r, n) {
        return i.prototype._removeGradientAndTexture.call(this, t, r, n),
        this._releaseBuffers(),
        this
    }
    ,
    e.prototype.addColorGradient = function(t, r, n) {
        this._colorGradients || (this._colorGradients = []);
        var o = new ColorGradient(t,r);
        return this._colorGradients.push(o),
        this._refreshColorGradient(!0),
        this._releaseBuffers(),
        this
    }
    ,
    e.prototype._refreshColorGradient = function(t) {
        t === void 0 && (t = !1),
        this._colorGradients && (t && this._colorGradients.sort(function(r, n) {
            return r.gradient < n.gradient ? -1 : r.gradient > n.gradient ? 1 : 0
        }),
        this._colorGradientsTexture && (this._colorGradientsTexture.dispose(),
        this._colorGradientsTexture = null))
    }
    ,
    e.prototype.forceRefreshGradients = function() {
        this._refreshColorGradient(),
        this._refreshFactorGradient(this._sizeGradients, "_sizeGradientsTexture"),
        this._refreshFactorGradient(this._angularSpeedGradients, "_angularSpeedGradientsTexture"),
        this._refreshFactorGradient(this._velocityGradients, "_velocityGradientsTexture"),
        this._refreshFactorGradient(this._limitVelocityGradients, "_limitVelocityGradientsTexture"),
        this._refreshFactorGradient(this._dragGradients, "_dragGradientsTexture"),
        this.reset()
    }
    ,
    e.prototype.removeColorGradient = function(t) {
        return this._removeGradientAndTexture(t, this._colorGradients, this._colorGradientsTexture),
        this._colorGradientsTexture = null,
        this
    }
    ,
    e.prototype.resetDrawCache = function() {
        var t;
        for (var r in this._drawWrappers) {
            var n = this._drawWrappers[r];
            (t = n.drawContext) === null || t === void 0 || t.reset()
        }
    }
    ,
    e.prototype._addFactorGradient = function(t, r, n) {
        var o = new FactorGradient(r,n);
        t.push(o),
        this._releaseBuffers()
    }
    ,
    e.prototype.addSizeGradient = function(t, r) {
        return this._sizeGradients || (this._sizeGradients = []),
        this._addFactorGradient(this._sizeGradients, t, r),
        this._refreshFactorGradient(this._sizeGradients, "_sizeGradientsTexture", !0),
        this._releaseBuffers(),
        this
    }
    ,
    e.prototype.removeSizeGradient = function(t) {
        return this._removeGradientAndTexture(t, this._sizeGradients, this._sizeGradientsTexture),
        this._sizeGradientsTexture = null,
        this
    }
    ,
    e.prototype._refreshFactorGradient = function(t, r, n) {
        if (n === void 0 && (n = !1),
        !!t) {
            n && t.sort(function(a, s) {
                return a.gradient < s.gradient ? -1 : a.gradient > s.gradient ? 1 : 0
            });
            var o = this;
            o[r] && (o[r].dispose(),
            o[r] = null)
        }
    }
    ,
    e.prototype.addAngularSpeedGradient = function(t, r) {
        return this._angularSpeedGradients || (this._angularSpeedGradients = []),
        this._addFactorGradient(this._angularSpeedGradients, t, r),
        this._refreshFactorGradient(this._angularSpeedGradients, "_angularSpeedGradientsTexture", !0),
        this._releaseBuffers(),
        this
    }
    ,
    e.prototype.removeAngularSpeedGradient = function(t) {
        return this._removeGradientAndTexture(t, this._angularSpeedGradients, this._angularSpeedGradientsTexture),
        this._angularSpeedGradientsTexture = null,
        this
    }
    ,
    e.prototype.addVelocityGradient = function(t, r) {
        return this._velocityGradients || (this._velocityGradients = []),
        this._addFactorGradient(this._velocityGradients, t, r),
        this._refreshFactorGradient(this._velocityGradients, "_velocityGradientsTexture", !0),
        this._releaseBuffers(),
        this
    }
    ,
    e.prototype.removeVelocityGradient = function(t) {
        return this._removeGradientAndTexture(t, this._velocityGradients, this._velocityGradientsTexture),
        this._velocityGradientsTexture = null,
        this
    }
    ,
    e.prototype.addLimitVelocityGradient = function(t, r) {
        return this._limitVelocityGradients || (this._limitVelocityGradients = []),
        this._addFactorGradient(this._limitVelocityGradients, t, r),
        this._refreshFactorGradient(this._limitVelocityGradients, "_limitVelocityGradientsTexture", !0),
        this._releaseBuffers(),
        this
    }
    ,
    e.prototype.removeLimitVelocityGradient = function(t) {
        return this._removeGradientAndTexture(t, this._limitVelocityGradients, this._limitVelocityGradientsTexture),
        this._limitVelocityGradientsTexture = null,
        this
    }
    ,
    e.prototype.addDragGradient = function(t, r) {
        return this._dragGradients || (this._dragGradients = []),
        this._addFactorGradient(this._dragGradients, t, r),
        this._refreshFactorGradient(this._dragGradients, "_dragGradientsTexture", !0),
        this._releaseBuffers(),
        this
    }
    ,
    e.prototype.removeDragGradient = function(t) {
        return this._removeGradientAndTexture(t, this._dragGradients, this._dragGradientsTexture),
        this._dragGradientsTexture = null,
        this
    }
    ,
    e.prototype.addEmitRateGradient = function(t, r, n) {
        return this
    }
    ,
    e.prototype.removeEmitRateGradient = function(t) {
        return this
    }
    ,
    e.prototype.addStartSizeGradient = function(t, r, n) {
        return this
    }
    ,
    e.prototype.removeStartSizeGradient = function(t) {
        return this
    }
    ,
    e.prototype.addColorRemapGradient = function(t, r, n) {
        return this
    }
    ,
    e.prototype.removeColorRemapGradient = function() {
        return this
    }
    ,
    e.prototype.addAlphaRemapGradient = function(t, r, n) {
        return this
    }
    ,
    e.prototype.removeAlphaRemapGradient = function() {
        return this
    }
    ,
    e.prototype.addRampGradient = function(t, r) {
        return this
    }
    ,
    e.prototype.removeRampGradient = function() {
        return this
    }
    ,
    e.prototype.getRampGradients = function() {
        return null
    }
    ,
    Object.defineProperty(e.prototype, "useRampGradients", {
        get: function() {
            return !1
        },
        set: function(t) {},
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.addLifeTimeGradient = function(t, r, n) {
        return this
    }
    ,
    e.prototype.removeLifeTimeGradient = function(t) {
        return this
    }
    ,
    e.prototype._reset = function() {
        this._releaseBuffers()
    }
    ,
    e.prototype._createVertexBuffers = function(t, r, n) {
        var o = {};
        o.position = r.createVertexBuffer("position", 0, 3, this._attributesStrideSize, !0);
        var a = 3;
        o.age = r.createVertexBuffer("age", a, 1, this._attributesStrideSize, !0),
        a += 1,
        o.size = r.createVertexBuffer("size", a, 3, this._attributesStrideSize, !0),
        a += 3,
        o.life = r.createVertexBuffer("life", a, 1, this._attributesStrideSize, !0),
        a += 1,
        a += 4,
        this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED && (o.direction = r.createVertexBuffer("direction", a, 3, this._attributesStrideSize, !0)),
        a += 3,
        this._platform.alignDataInBuffer && (a += 1),
        this.particleEmitterType instanceof CustomParticleEmitter && (a += 3,
        this._platform.alignDataInBuffer && (a += 1)),
        this._colorGradientsTexture || (o.color = r.createVertexBuffer("color", a, 4, this._attributesStrideSize, !0),
        a += 4),
        this._isBillboardBased || (o.initialDirection = r.createVertexBuffer("initialDirection", a, 3, this._attributesStrideSize, !0),
        a += 3,
        this._platform.alignDataInBuffer && (a += 1)),
        this.noiseTexture && (o.noiseCoordinates1 = r.createVertexBuffer("noiseCoordinates1", a, 3, this._attributesStrideSize, !0),
        a += 3,
        this._platform.alignDataInBuffer && (a += 1),
        o.noiseCoordinates2 = r.createVertexBuffer("noiseCoordinates2", a, 3, this._attributesStrideSize, !0),
        a += 3,
        this._platform.alignDataInBuffer && (a += 1)),
        o.angle = r.createVertexBuffer("angle", a, 1, this._attributesStrideSize, !0),
        this._angularSpeedGradientsTexture ? a++ : a += 2,
        this._isAnimationSheetEnabled && (o.cellIndex = r.createVertexBuffer("cellIndex", a, 1, this._attributesStrideSize, !0),
        a += 1,
        this.spriteRandomStartCell && (o.cellStartOffset = r.createVertexBuffer("cellStartOffset", a, 1, this._attributesStrideSize, !0),
        a += 1)),
        o.offset = n.createVertexBuffer("offset", 0, 2),
        o.uv = n.createVertexBuffer("uv", 2, 2),
        this._platform.createVertexBuffers(t, o),
        this.resetDrawCache()
    }
    ,
    e.prototype._initialize = function(t) {
        if (t === void 0 && (t = !1),
        !(this._buffer0 && !t)) {
            var r = this._engine
              , n = new Array;
            this._attributesStrideSize = 21,
            this._targetIndex = 0,
            this._platform.alignDataInBuffer && (this._attributesStrideSize += 1),
            this.particleEmitterType instanceof CustomParticleEmitter && (this._attributesStrideSize += 3,
            this._platform.alignDataInBuffer && (this._attributesStrideSize += 1)),
            this.isBillboardBased || (this._attributesStrideSize += 3,
            this._platform.alignDataInBuffer && (this._attributesStrideSize += 1)),
            this._colorGradientsTexture && (this._attributesStrideSize -= 4),
            this._angularSpeedGradientsTexture && (this._attributesStrideSize -= 1),
            this._isAnimationSheetEnabled && (this._attributesStrideSize += 1,
            this.spriteRandomStartCell && (this._attributesStrideSize += 1)),
            this.noiseTexture && (this._attributesStrideSize += 6,
            this._platform.alignDataInBuffer && (this._attributesStrideSize += 2)),
            this._platform.alignDataInBuffer && (this._attributesStrideSize += 3 - (this._attributesStrideSize + 3 & 3));
            for (var o = this.particleEmitterType instanceof CustomParticleEmitter, a = TmpVectors.Vector3[0], s = 0, l = 0; l < this._capacity; l++)
                if (n.push(0),
                n.push(0),
                n.push(0),
                n.push(0),
                n.push(0),
                n.push(0),
                n.push(0),
                n.push(0),
                n.push(Math.random()),
                n.push(Math.random()),
                n.push(Math.random()),
                n.push(Math.random()),
                o ? (this.particleEmitterType.particleDestinationGenerator(l, null, a),
                n.push(a.x),
                n.push(a.y),
                n.push(a.z)) : (n.push(0),
                n.push(0),
                n.push(0)),
                this._platform.alignDataInBuffer && n.push(0),
                s += 16,
                o && (this.particleEmitterType.particlePositionGenerator(l, null, a),
                n.push(a.x),
                n.push(a.y),
                n.push(a.z),
                this._platform.alignDataInBuffer && n.push(0),
                s += 4),
                this._colorGradientsTexture || (n.push(0),
                n.push(0),
                n.push(0),
                n.push(0),
                s += 4),
                this.isBillboardBased || (n.push(0),
                n.push(0),
                n.push(0),
                this._platform.alignDataInBuffer && n.push(0),
                s += 4),
                this.noiseTexture && (n.push(Math.random()),
                n.push(Math.random()),
                n.push(Math.random()),
                this._platform.alignDataInBuffer && n.push(0),
                n.push(Math.random()),
                n.push(Math.random()),
                n.push(Math.random()),
                this._platform.alignDataInBuffer && n.push(0),
                s += 8),
                n.push(0),
                s += 1,
                this._angularSpeedGradientsTexture || (n.push(0),
                s += 1),
                this._isAnimationSheetEnabled && (n.push(0),
                s += 1,
                this.spriteRandomStartCell && (n.push(0),
                s += 1)),
                this._platform.alignDataInBuffer) {
                    var u = 3 - (s + 3 & 3);
                    for (s += u; u-- > 0; )
                        n.push(0)
                }
            var c = new Float32Array([.5, .5, 1, 1, -.5, .5, 0, 1, .5, -.5, 1, 0, -.5, -.5, 0, 0])
              , h = this._platform.createParticleBuffer(n)
              , f = this._platform.createParticleBuffer(n);
            this._buffer0 = new Buffer(r,h,!1,this._attributesStrideSize),
            this._buffer1 = new Buffer(r,f,!1,this._attributesStrideSize),
            this._spriteBuffer = new Buffer(r,c,!1,4),
            this._createVertexBuffers(this._buffer0, this._buffer1, this._spriteBuffer),
            this._createVertexBuffers(this._buffer1, this._buffer0, this._spriteBuffer),
            this._sourceBuffer = this._buffer0,
            this._targetBuffer = this._buffer1
        }
    }
    ,
    e.prototype._recreateUpdateEffect = function() {
        var t = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
        this._isBillboardBased && (t += `
#define BILLBOARD`),
        this._colorGradientsTexture && (t += `
#define COLORGRADIENTS`),
        this._sizeGradientsTexture && (t += `
#define SIZEGRADIENTS`),
        this._angularSpeedGradientsTexture && (t += `
#define ANGULARSPEEDGRADIENTS`),
        this._velocityGradientsTexture && (t += `
#define VELOCITYGRADIENTS`),
        this._limitVelocityGradientsTexture && (t += `
#define LIMITVELOCITYGRADIENTS`),
        this._dragGradientsTexture && (t += `
#define DRAGGRADIENTS`),
        this.isAnimationSheetEnabled && (t += `
#define ANIMATESHEET`,
        this.spriteRandomStartCell && (t += `
#define ANIMATESHEETRANDOMSTART`)),
        this.noiseTexture && (t += `
#define NOISE`),
        this.isLocal && (t += `
#define LOCAL`),
        !(this._platform.isUpdateBufferCreated() && this._cachedUpdateDefines === t) && (this._cachedUpdateDefines = t,
        this._updateBuffer = this._platform.createUpdateBuffer(t))
    }
    ,
    e.prototype._getWrapper = function(t) {
        var r = this._getCustomDrawWrapper(t);
        if (r != null && r.effect)
            return r;
        var n = [];
        this.fillDefines(n, t);
        var o = this._drawWrappers[t];
        o || (o = new DrawWrapper(this._engine),
        o.drawContext && (o.drawContext.useInstancing = !0),
        this._drawWrappers[t] = o);
        var a = n.join(`
`);
        if (o.defines !== a) {
            var s = []
              , l = []
              , u = [];
            this.fillUniformsAttributesAndSamplerNames(l, s, u),
            o.setEffect(this._engine.createEffect("gpuRenderParticles", s, l, u, a), a)
        }
        return o
    }
    ,
    e._GetAttributeNamesOrOptions = function(t, r, n, o) {
        t === void 0 && (t = !1),
        r === void 0 && (r = !1),
        n === void 0 && (n = !1),
        o === void 0 && (o = !1);
        var a = [VertexBuffer.PositionKind, "age", "life", "size", "angle"];
        return t || a.push(VertexBuffer.ColorKind),
        r && a.push("cellIndex"),
        n || a.push("initialDirection"),
        o || a.push("direction"),
        a.push("offset", VertexBuffer.UVKind),
        a
    }
    ,
    e._GetEffectCreationOptions = function(t) {
        t === void 0 && (t = !1);
        var r = ["emitterWM", "worldOffset", "view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "vClipPlane5", "vClipPlane6", "translationPivot", "eyePosition"];
        return t && r.push("sheetInfos"),
        r
    }
    ,
    e.prototype.fillDefines = function(t, r) {
        if (r === void 0 && (r = 0),
        this._scene && (this._scene.clipPlane && t.push("#define CLIPPLANE"),
        this._scene.clipPlane2 && t.push("#define CLIPPLANE2"),
        this._scene.clipPlane3 && t.push("#define CLIPPLANE3"),
        this._scene.clipPlane4 && t.push("#define CLIPPLANE4"),
        this._scene.clipPlane5 && t.push("#define CLIPPLANE5"),
        this._scene.clipPlane6 && t.push("#define CLIPPLANE6")),
        r === ParticleSystem.BLENDMODE_MULTIPLY && t.push("#define BLENDMULTIPLYMODE"),
        this.isLocal && t.push("#define LOCAL"),
        this._isBillboardBased)
            switch (t.push("#define BILLBOARD"),
            this.billboardMode) {
            case ParticleSystem.BILLBOARDMODE_Y:
                t.push("#define BILLBOARDY");
                break;
            case ParticleSystem.BILLBOARDMODE_STRETCHED:
                t.push("#define BILLBOARDSTRETCHED");
                break;
            case ParticleSystem.BILLBOARDMODE_ALL:
                t.push("#define BILLBOARDMODE_ALL");
                break
            }
        this._colorGradientsTexture && t.push("#define COLORGRADIENTS"),
        this.isAnimationSheetEnabled && t.push("#define ANIMATESHEET"),
        this._imageProcessingConfiguration && (this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),
        t.push("" + this._imageProcessingConfigurationDefines.toString()))
    }
    ,
    e.prototype.fillUniformsAttributesAndSamplerNames = function(t, r, n) {
        r.push.apply(r, e._GetAttributeNamesOrOptions(!!this._colorGradientsTexture, this._isAnimationSheetEnabled, this._isBillboardBased, this._isBillboardBased && this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED)),
        t.push.apply(t, e._GetEffectCreationOptions(this._isAnimationSheetEnabled)),
        n.push("diffuseSampler", "colorGradientSampler"),
        this._imageProcessingConfiguration && (ImageProcessingConfiguration.PrepareUniforms(t, this._imageProcessingConfigurationDefines),
        ImageProcessingConfiguration.PrepareSamplers(n, this._imageProcessingConfigurationDefines))
    }
    ,
    e.prototype.animate = function(t) {
        var r;
        t === void 0 && (t = !1),
        this._timeDelta = this.updateSpeed * (t ? this.preWarmStepOffset : ((r = this._scene) === null || r === void 0 ? void 0 : r.getAnimationRatio()) || 1),
        this._actualFrame += this._timeDelta,
        this._stopped || this.targetStopDuration && this._actualFrame >= this.targetStopDuration && this.stop()
    }
    ,
    e.prototype._createFactorGradientTexture = function(t, r) {
        var n = this[r];
        if (!(!t || !t.length || n)) {
            for (var o = new Float32Array(this._rawTextureWidth), a = 0; a < this._rawTextureWidth; a++) {
                var s = a / this._rawTextureWidth;
                GradientHelper.GetCurrentGradient(s, t, function(l, u, c) {
                    o[a] = Scalar.Lerp(l.factor1, u.factor1, c)
                })
            }
            this[r] = RawTexture.CreateRTexture(o, this._rawTextureWidth, 1, this._scene || this._engine, !1, !1, 1)
        }
    }
    ,
    e.prototype._createSizeGradientTexture = function() {
        this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture")
    }
    ,
    e.prototype._createAngularSpeedGradientTexture = function() {
        this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture")
    }
    ,
    e.prototype._createVelocityGradientTexture = function() {
        this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture")
    }
    ,
    e.prototype._createLimitVelocityGradientTexture = function() {
        this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture")
    }
    ,
    e.prototype._createDragGradientTexture = function() {
        this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture")
    }
    ,
    e.prototype._createColorGradientTexture = function() {
        if (!(!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture)) {
            for (var t = new Uint8Array(this._rawTextureWidth * 4), r = TmpColors.Color4[0], n = 0; n < this._rawTextureWidth; n++) {
                var o = n / this._rawTextureWidth;
                GradientHelper.GetCurrentGradient(o, this._colorGradients, function(a, s, l) {
                    Color4.LerpToRef(a.color1, s.color1, l, r),
                    t[n * 4] = r.r * 255,
                    t[n * 4 + 1] = r.g * 255,
                    t[n * 4 + 2] = r.b * 255,
                    t[n * 4 + 3] = r.a * 255
                })
            }
            this._colorGradientsTexture = RawTexture.CreateRGBATexture(t, this._rawTextureWidth, 1, this._scene, !1, !1, 1)
        }
    }
    ,
    e.prototype._render = function(t, r) {
        var n, o, a = this._getWrapper(t), s = a.effect;
        this._engine.enableEffect(a);
        var l = ((n = this._scene) === null || n === void 0 ? void 0 : n.getViewMatrix()) || Matrix.IdentityReadOnly;
        if (s.setMatrix("view", l),
        s.setMatrix("projection", (o = this.defaultProjectionMatrix) !== null && o !== void 0 ? o : this._scene.getProjectionMatrix()),
        s.setTexture("diffuseSampler", this.particleTexture),
        s.setVector2("translationPivot", this.translationPivot),
        s.setVector3("worldOffset", this.worldOffset),
        this.isLocal && s.setMatrix("emitterWM", r),
        this._colorGradientsTexture ? s.setTexture("colorGradientSampler", this._colorGradientsTexture) : s.setDirectColor4("colorDead", this.colorDead),
        this._isAnimationSheetEnabled && this.particleTexture) {
            var u = this.particleTexture.getBaseSize();
            s.setFloat3("sheetInfos", this.spriteCellWidth / u.width, this.spriteCellHeight / u.height, u.width / this.spriteCellWidth)
        }
        if (this._isBillboardBased && this._scene) {
            var c = this._scene.activeCamera;
            s.setVector3("eyePosition", c.globalPosition)
        }
        var h = s.defines;
        if (this._scene && (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4 || this._scene.clipPlane5 || this._scene.clipPlane6) && MaterialHelper.BindClipPlane(s, this._scene),
        h.indexOf("#define BILLBOARDMODE_ALL") >= 0) {
            var f = l.clone();
            f.invert(),
            s.setMatrix("invView", f)
        }
        switch (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess && this._imageProcessingConfiguration.bind(s),
        t) {
        case ParticleSystem.BLENDMODE_ADD:
            this._engine.setAlphaMode(1);
            break;
        case ParticleSystem.BLENDMODE_ONEONE:
            this._engine.setAlphaMode(6);
            break;
        case ParticleSystem.BLENDMODE_STANDARD:
            this._engine.setAlphaMode(2);
            break;
        case ParticleSystem.BLENDMODE_MULTIPLY:
            this._engine.setAlphaMode(4);
            break
        }
        return this._platform.bindDrawBuffers(this._targetIndex, s),
        this._onBeforeDrawParticlesObservable && this._onBeforeDrawParticlesObservable.notifyObservers(s),
        this._engine.drawArraysType(7, 0, 4, this._currentActiveCount),
        this._engine.setAlphaMode(0),
        this._currentActiveCount
    }
    ,
    e.prototype.render = function(t, r) {
        if (t === void 0 && (t = !1),
        r === void 0 && (r = !1),
        !this._started || (this._createColorGradientTexture(),
        this._createSizeGradientTexture(),
        this._createAngularSpeedGradientTexture(),
        this._createVelocityGradientTexture(),
        this._createLimitVelocityGradientTexture(),
        this._createDragGradientTexture(),
        this._recreateUpdateEffect(),
        !this.isReady()))
            return 0;
        if (!t && this._scene) {
            if (!this._preWarmDone && this.preWarmCycles) {
                for (var n = 0; n < this.preWarmCycles; n++)
                    this.animate(!0),
                    this.render(!0, !0);
                this._preWarmDone = !0
            }
            if (this._currentRenderId === this._scene.getFrameId() && (!this._scene.activeCamera || this._scene.activeCamera && this._currentRenderingCameraUniqueId === this._scene.activeCamera.uniqueId))
                return 0;
            this._currentRenderId = this._scene.getFrameId(),
            this._scene.activeCamera && (this._currentRenderingCameraUniqueId = this._scene.activeCamera.uniqueId)
        }
        if (this._initialize(),
        this._accumulatedCount += this.emitRate * this._timeDelta,
        this._accumulatedCount > 1) {
            var o = this._accumulatedCount | 0;
            this._accumulatedCount -= o,
            this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + o)
        }
        if (!this._currentActiveCount)
            return 0;
        var a;
        if (this.emitter.position) {
            var s = this.emitter;
            a = s.getWorldMatrix()
        } else {
            var l = this.emitter;
            a = Matrix.Translation(l.x, l.y, l.z)
        }
        var u = this._engine;
        this._platform.preUpdateParticleBuffer(),
        this._updateBuffer.setFloat("currentCount", this._currentActiveCount),
        this._updateBuffer.setFloat("timeDelta", this._timeDelta),
        this._updateBuffer.setFloat("stopFactor", this._stopped ? 0 : 1),
        this._updateBuffer.setInt("randomTextureSize", this._randomTextureSize),
        this._updateBuffer.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime),
        this._updateBuffer.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower),
        this._colorGradientsTexture || (this._updateBuffer.setDirectColor4("color1", this.color1),
        this._updateBuffer.setDirectColor4("color2", this.color2)),
        this._updateBuffer.setFloat2("sizeRange", this.minSize, this.maxSize),
        this._updateBuffer.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY),
        this._updateBuffer.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation),
        this._updateBuffer.setVector3("gravity", this.gravity),
        this._limitVelocityGradientsTexture && this._updateBuffer.setFloat("limitVelocityDamping", this.limitVelocityDamping),
        this.particleEmitterType && this.particleEmitterType.applyToShader(this._updateBuffer),
        this._isAnimationSheetEnabled && this._updateBuffer.setFloat4("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed, this.spriteCellLoop ? 1 : 0),
        this.noiseTexture && this._updateBuffer.setVector3("noiseStrength", this.noiseStrength),
        this.isLocal || this._updateBuffer.setMatrix("emitterWM", a),
        this._platform.updateParticleBuffer(this._targetIndex, this._targetBuffer, this._currentActiveCount);
        var c = 0;
        !t && !r && (u.setState(!1),
        this.forceDepthWrite && u.setDepthWrite(!0),
        this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD ? c = this._render(ParticleSystem.BLENDMODE_MULTIPLY, a) + this._render(ParticleSystem.BLENDMODE_ADD, a) : c = this._render(this.blendMode, a),
        this._engine.setAlphaMode(0)),
        this._targetIndex++,
        this._targetIndex === 2 && (this._targetIndex = 0);
        var h = this._sourceBuffer;
        return this._sourceBuffer = this._targetBuffer,
        this._targetBuffer = h,
        c
    }
    ,
    e.prototype.rebuild = function() {
        this._initialize(!0)
    }
    ,
    e.prototype._releaseBuffers = function() {
        this._buffer0 && (this._buffer0.dispose(),
        this._buffer0 = null),
        this._buffer1 && (this._buffer1.dispose(),
        this._buffer1 = null),
        this._spriteBuffer && (this._spriteBuffer.dispose(),
        this._spriteBuffer = null),
        this._platform.releaseBuffers()
    }
    ,
    e.prototype.dispose = function(t) {
        t === void 0 && (t = !0);
        for (var r in this._drawWrappers) {
            var n = this._drawWrappers[r];
            n.dispose()
        }
        if (this._drawWrappers = {},
        this._scene) {
            var o = this._scene.particleSystems.indexOf(this);
            o > -1 && this._scene.particleSystems.splice(o, 1)
        }
        this._releaseBuffers(),
        this._platform.releaseVertexBuffers(),
        this._colorGradientsTexture && (this._colorGradientsTexture.dispose(),
        this._colorGradientsTexture = null),
        this._sizeGradientsTexture && (this._sizeGradientsTexture.dispose(),
        this._sizeGradientsTexture = null),
        this._angularSpeedGradientsTexture && (this._angularSpeedGradientsTexture.dispose(),
        this._angularSpeedGradientsTexture = null),
        this._velocityGradientsTexture && (this._velocityGradientsTexture.dispose(),
        this._velocityGradientsTexture = null),
        this._limitVelocityGradientsTexture && (this._limitVelocityGradientsTexture.dispose(),
        this._limitVelocityGradientsTexture = null),
        this._dragGradientsTexture && (this._dragGradientsTexture.dispose(),
        this._dragGradientsTexture = null),
        this._randomTexture && (this._randomTexture.dispose(),
        this._randomTexture = null),
        this._randomTexture2 && (this._randomTexture2.dispose(),
        this._randomTexture2 = null),
        t && this.particleTexture && (this.particleTexture.dispose(),
        this.particleTexture = null),
        t && this.noiseTexture && (this.noiseTexture.dispose(),
        this.noiseTexture = null),
        this.onStoppedObservable.clear(),
        this.onDisposeObservable.notifyObservers(this),
        this.onDisposeObservable.clear()
    }
    ,
    e.prototype.clone = function(t, r) {
        var n = __assign({}, this._customWrappers)
          , o = null
          , a = this._engine;
        if (a.createEffectForParticles && this.customShader != null) {
            o = this.customShader;
            var s = o.shaderOptions.defines.length > 0 ? o.shaderOptions.defines.join(`
`) : "";
            n[0] = a.createEffectForParticles(o.shaderPath.fragmentElement, o.shaderOptions.uniforms, o.shaderOptions.samplers, s, void 0, void 0, void 0, this)
        }
        var l = this.serialize()
          , u = e.Parse(l, this._scene || this._engine, this._rootUrl);
        return u.name = t,
        u.customShader = o,
        u._customWrappers = n,
        r === void 0 && (r = this.emitter),
        this.noiseTexture && (u.noiseTexture = this.noiseTexture.clone()),
        u.emitter = r,
        u
    }
    ,
    e.prototype.serialize = function(t) {
        t === void 0 && (t = !1);
        var r = {};
        return ParticleSystem._Serialize(r, this, t),
        r.activeParticleCount = this.activeParticleCount,
        r.randomTextureSize = this._randomTextureSize,
        r.customShader = this.customShader,
        r
    }
    ,
    e.Parse = function(t, r, n, o, a) {
        o === void 0 && (o = !1);
        var s = t.name, l, u;
        r instanceof ThinEngine ? l = r : (u = r,
        l = u.getEngine());
        var c = new e(s,{
            capacity: a || t.capacity,
            randomTextureSize: t.randomTextureSize
        },r,null,t.isAnimationSheetEnabled);
        if (c._rootUrl = n,
        t.customShader && l.createEffectForParticles) {
            var h = t.customShader
              , f = h.shaderOptions.defines.length > 0 ? h.shaderOptions.defines.join(`
`) : ""
              , d = l.createEffectForParticles(h.shaderPath.fragmentElement, h.shaderOptions.uniforms, h.shaderOptions.samplers, f, void 0, void 0, void 0, c);
            c.setCustomEffect(d, 0),
            c.customShader = h
        }
        return t.id && (c.id = t.id),
        t.activeParticleCount && (c.activeParticleCount = t.activeParticleCount),
        ParticleSystem._Parse(t, c, r, n),
        t.preventAutoStart && (c.preventAutoStart = t.preventAutoStart),
        !o && !c.preventAutoStart && c.start(),
        c
    }
    ,
    e
}(BaseParticleSystem)
  , ParticleSystemSet = function() {
    function i() {
        this._emitterNodeIsOwned = !0,
        this.systems = new Array
    }
    return Object.defineProperty(i.prototype, "emitterNode", {
        get: function() {
            return this._emitterNode
        },
        set: function(e) {
            this._emitterNodeIsOwned && this._emitterNode && (this._emitterNode.dispose && this._emitterNode.dispose(),
            this._emitterNodeIsOwned = !1);
            for (var t = 0, r = this.systems; t < r.length; t++) {
                var n = r[t];
                n.emitter = e
            }
            this._emitterNode = e
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.setEmitterAsSphere = function(e, t, r) {
        this._emitterNodeIsOwned && this._emitterNode && this._emitterNode.dispose && this._emitterNode.dispose(),
        this._emitterNodeIsOwned = !0,
        this._emitterCreationOptions = {
            kind: "Sphere",
            options: e,
            renderingGroupId: t
        };
        var n = CreateSphere("emitterSphere", {
            diameter: e.diameter,
            segments: e.segments
        }, r);
        n.renderingGroupId = t;
        var o = new StandardMaterial("emitterSphereMaterial",r);
        o.emissiveColor = e.color,
        n.material = o;
        for (var a = 0, s = this.systems; a < s.length; a++) {
            var l = s[a];
            l.emitter = n
        }
        this._emitterNode = n
    }
    ,
    i.prototype.start = function(e) {
        for (var t = 0, r = this.systems; t < r.length; t++) {
            var n = r[t];
            e && (n.emitter = e),
            n.start()
        }
    }
    ,
    i.prototype.dispose = function() {
        for (var e = 0, t = this.systems; e < t.length; e++) {
            var r = t[e];
            r.dispose()
        }
        this.systems = [],
        this._emitterNode && (this._emitterNode.dispose && this._emitterNode.dispose(),
        this._emitterNode = null)
    }
    ,
    i.prototype.serialize = function(e) {
        e === void 0 && (e = !1);
        var t = {};
        t.systems = [];
        for (var r = 0, n = this.systems; r < n.length; r++) {
            var o = n[r];
            t.systems.push(o.serialize(e))
        }
        return this._emitterNode && (t.emitter = this._emitterCreationOptions),
        t
    }
    ,
    i.Parse = function(e, t, r, n) {
        r === void 0 && (r = !1);
        var o = new i
          , a = this.BaseAssetsUrl + "/textures/";
        t = t || EngineStore.LastCreatedScene;
        for (var s = 0, l = e.systems; s < l.length; s++) {
            var u = l[s];
            o.systems.push(r ? GPUParticleSystem.Parse(u, t, a, !0, n) : ParticleSystem.Parse(u, t, a, !0, n))
        }
        if (e.emitter) {
            var c = e.emitter.options;
            switch (e.emitter.kind) {
            case "Sphere":
                o.setEmitterAsSphere({
                    diameter: c.diameter,
                    segments: c.segments,
                    color: Color3.FromArray(c.color)
                }, e.emitter.renderingGroupId, t);
                break
            }
        }
        return o
    }
    ,
    i.BaseAssetsUrl = "https://assets.babylonjs.com/particles",
    i
}()
  , ProceduralTextureSceneComponent = function() {
    function i(e) {
        this.name = SceneComponentConstants.NAME_PROCEDURALTEXTURE,
        this.scene = e,
        this.scene.proceduralTextures = new Array
    }
    return i.prototype.register = function() {
        this.scene._beforeClearStage.registerStep(SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear)
    }
    ,
    i.prototype.rebuild = function() {}
    ,
    i.prototype.dispose = function() {}
    ,
    i.prototype._beforeClear = function() {
        if (this.scene.proceduralTexturesEnabled) {
            Tools.StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
            for (var e = 0; e < this.scene.proceduralTextures.length; e++) {
                var t = this.scene.proceduralTextures[e];
                t._shouldRender() && t.render()
            }
            Tools.EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0)
        }
    }
    ,
    i
}()
  , name$1B = "proceduralVertexShader"
  , shader$1B = `
attribute vec2 position;

varying vec2 vPosition;
varying vec2 vUV;
const vec2 madd=vec2(0.5,0.5);
void main(void) {
vPosition=position;
vUV=position*madd+madd;
gl_Position=vec4(position,0.0,1.0);
}`;
ShaderStore.ShadersStore[name$1B] = shader$1B;
var ProceduralTexture = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a, s, l, u) {
        a === void 0 && (a = null),
        s === void 0 && (s = !0),
        l === void 0 && (l = !1),
        u === void 0 && (u = 0);
        var c = i.call(this, null, o, !s) || this;
        c.isEnabled = !0,
        c.autoClear = !0,
        c.onGeneratedObservable = new Observable,
        c.onBeforeGenerationObservable = new Observable,
        c.nodeMaterialSource = null,
        c._textures = {},
        c._currentRefreshId = -1,
        c._frameId = -1,
        c._refreshRate = 1,
        c._vertexBuffers = {},
        c._uniforms = new Array,
        c._samplers = new Array,
        c._floats = {},
        c._ints = {},
        c._floatsArrays = {},
        c._colors3 = {},
        c._colors4 = {},
        c._vectors2 = {},
        c._vectors3 = {},
        c._matrices = {},
        c._fallbackTextureUsed = !1,
        c._cachedDefines = null,
        c._contentUpdateId = -1,
        c._rtWrapper = null,
        o = c.getScene() || EngineStore.LastCreatedScene;
        var h = o._getComponent(SceneComponentConstants.NAME_PROCEDURALTEXTURE);
        h || (h = new ProceduralTextureSceneComponent(o),
        o._addComponent(h)),
        o.proceduralTextures.push(c),
        c._fullEngine = o.getEngine(),
        c.name = t,
        c.isRenderTarget = !0,
        c._size = r,
        c._textureType = u,
        c._generateMipMaps = s,
        c._drawWrapper = new DrawWrapper(c._fullEngine),
        c.setFragment(n),
        c._fallbackTexture = a,
        l ? (c._rtWrapper = c._fullEngine.createRenderTargetCubeTexture(r, {
            generateMipMaps: s,
            generateDepthBuffer: !1,
            generateStencilBuffer: !1,
            type: u
        }),
        c.setFloat("face", 0)) : c._rtWrapper = c._fullEngine.createRenderTargetTexture(r, {
            generateMipMaps: s,
            generateDepthBuffer: !1,
            generateStencilBuffer: !1,
            type: u
        }),
        c._texture = c._rtWrapper.texture;
        var f = [];
        return f.push(1, 1),
        f.push(-1, 1),
        f.push(-1, -1),
        f.push(1, -1),
        c._vertexBuffers[VertexBuffer.PositionKind] = new VertexBuffer(c._fullEngine,f,VertexBuffer.PositionKind,!1,!1,2),
        c._createIndexBuffer(),
        c
    }
    return e.prototype.getEffect = function() {
        return this._drawWrapper.effect
    }
    ,
    e.prototype._setEffect = function(t) {
        this._drawWrapper.effect = t
    }
    ,
    e.prototype.getContent = function() {
        var t = this;
        return this._contentData && this._frameId === this._contentUpdateId ? this._contentData : (this._contentData ? this._contentData.then(function(r) {
            t._contentData = t.readPixels(0, 0, r),
            t._contentUpdateId = t._frameId
        }) : (this._contentData = this.readPixels(0, 0),
        this._contentUpdateId = this._frameId),
        this._contentData)
    }
    ,
    e.prototype._createIndexBuffer = function() {
        var t = this._fullEngine
          , r = [];
        r.push(0),
        r.push(1),
        r.push(2),
        r.push(0),
        r.push(2),
        r.push(3),
        this._indexBuffer = t.createIndexBuffer(r)
    }
    ,
    e.prototype._rebuild = function() {
        var t = this._vertexBuffers[VertexBuffer.PositionKind];
        t && t._rebuild(),
        this._createIndexBuffer(),
        this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE && (this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE)
    }
    ,
    e.prototype.reset = function() {
        var t;
        (t = this._drawWrapper.effect) === null || t === void 0 || t.dispose()
    }
    ,
    e.prototype._getDefines = function() {
        return ""
    }
    ,
    e.prototype.isReady = function() {
        var t = this, r = this._fullEngine, n;
        if (this.nodeMaterialSource)
            return this._drawWrapper.effect.isReady();
        if (!this._fragment)
            return !1;
        if (this._fallbackTextureUsed)
            return !0;
        var o = this._getDefines();
        return this._drawWrapper.effect && o === this._cachedDefines && this._drawWrapper.effect.isReady() ? !0 : (this._fragment.fragmentElement !== void 0 ? n = {
            vertex: "procedural",
            fragmentElement: this._fragment.fragmentElement
        } : n = {
            vertex: "procedural",
            fragment: this._fragment
        },
        this._cachedDefines !== o && (this._cachedDefines = o,
        this._drawWrapper.effect = r.createEffect(n, [VertexBuffer.PositionKind], this._uniforms, this._samplers, o, void 0, void 0, function() {
            var a;
            (a = t._rtWrapper) === null || a === void 0 || a.dispose(),
            t._rtWrapper = t._texture = null,
            t._fallbackTexture && (t._texture = t._fallbackTexture._texture,
            t._texture && t._texture.incrementReferences()),
            t._fallbackTextureUsed = !0
        })),
        this._drawWrapper.effect.isReady())
    }
    ,
    e.prototype.resetRefreshCounter = function() {
        this._currentRefreshId = -1
    }
    ,
    e.prototype.setFragment = function(t) {
        this._fragment = t
    }
    ,
    Object.defineProperty(e.prototype, "refreshRate", {
        get: function() {
            return this._refreshRate
        },
        set: function(t) {
            this._refreshRate = t,
            this.resetRefreshCounter()
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._shouldRender = function() {
        return !this.isEnabled || !this.isReady() || !this._texture ? (this._texture && (this._texture.isReady = !1),
        !1) : this._fallbackTextureUsed ? !1 : this._currentRefreshId === -1 ? (this._currentRefreshId = 1,
        this._frameId++,
        !0) : this.refreshRate === this._currentRefreshId ? (this._currentRefreshId = 1,
        this._frameId++,
        !0) : (this._currentRefreshId++,
        !1)
    }
    ,
    e.prototype.getRenderSize = function() {
        return this._size
    }
    ,
    e.prototype.resize = function(t, r) {
        var n;
        this._fallbackTextureUsed || ((n = this._rtWrapper) === null || n === void 0 || n.dispose(),
        this._rtWrapper = this._fullEngine.createRenderTargetTexture(t, {
            generateMipMaps: r,
            generateDepthBuffer: !1,
            generateStencilBuffer: !1,
            type: this._textureType
        }),
        this._texture = this._rtWrapper.texture,
        this._size = t,
        this._generateMipMaps = r)
    }
    ,
    e.prototype._checkUniform = function(t) {
        this._uniforms.indexOf(t) === -1 && this._uniforms.push(t)
    }
    ,
    e.prototype.setTexture = function(t, r) {
        return this._samplers.indexOf(t) === -1 && this._samplers.push(t),
        this._textures[t] = r,
        this
    }
    ,
    e.prototype.setFloat = function(t, r) {
        return this._checkUniform(t),
        this._floats[t] = r,
        this
    }
    ,
    e.prototype.setInt = function(t, r) {
        return this._checkUniform(t),
        this._ints[t] = r,
        this
    }
    ,
    e.prototype.setFloats = function(t, r) {
        return this._checkUniform(t),
        this._floatsArrays[t] = r,
        this
    }
    ,
    e.prototype.setColor3 = function(t, r) {
        return this._checkUniform(t),
        this._colors3[t] = r,
        this
    }
    ,
    e.prototype.setColor4 = function(t, r) {
        return this._checkUniform(t),
        this._colors4[t] = r,
        this
    }
    ,
    e.prototype.setVector2 = function(t, r) {
        return this._checkUniform(t),
        this._vectors2[t] = r,
        this
    }
    ,
    e.prototype.setVector3 = function(t, r) {
        return this._checkUniform(t),
        this._vectors3[t] = r,
        this
    }
    ,
    e.prototype.setMatrix = function(t, r) {
        return this._checkUniform(t),
        this._matrices[t] = r,
        this
    }
    ,
    e.prototype.render = function(t) {
        var r, n, o = this.getScene();
        if (!!o) {
            var a = this._fullEngine;
            if (a.enableEffect(this._drawWrapper),
            this.onBeforeGenerationObservable.notifyObservers(this),
            a.setState(!1),
            !this.nodeMaterialSource) {
                for (var s in this._textures)
                    this._drawWrapper.effect.setTexture(s, this._textures[s]);
                for (s in this._ints)
                    this._drawWrapper.effect.setInt(s, this._ints[s]);
                for (s in this._floats)
                    this._drawWrapper.effect.setFloat(s, this._floats[s]);
                for (s in this._floatsArrays)
                    this._drawWrapper.effect.setArray(s, this._floatsArrays[s]);
                for (s in this._colors3)
                    this._drawWrapper.effect.setColor3(s, this._colors3[s]);
                for (s in this._colors4) {
                    var l = this._colors4[s];
                    this._drawWrapper.effect.setFloat4(s, l.r, l.g, l.b, l.a)
                }
                for (s in this._vectors2)
                    this._drawWrapper.effect.setVector2(s, this._vectors2[s]);
                for (s in this._vectors3)
                    this._drawWrapper.effect.setVector3(s, this._vectors3[s]);
                for (s in this._matrices)
                    this._drawWrapper.effect.setMatrix(s, this._matrices[s])
            }
            if (!(!this._texture || !this._rtWrapper)) {
                if ((r = a._debugPushGroup) === null || r === void 0 || r.call(a, "procedural texture generation for " + this.name, 1),
                this.isCube)
                    for (var u = 0; u < 6; u++)
                        a.bindFramebuffer(this._rtWrapper, u, void 0, void 0, !0),
                        a.bindBuffers(this._vertexBuffers, this._indexBuffer, this._drawWrapper.effect),
                        this._drawWrapper.effect.setFloat("face", u),
                        this.autoClear && a.clear(o.clearColor, !0, !1, !1),
                        a.drawElementsType(Material.TriangleFillMode, 0, 6);
                else
                    a.bindFramebuffer(this._rtWrapper, 0, void 0, void 0, !0),
                    a.bindBuffers(this._vertexBuffers, this._indexBuffer, this._drawWrapper.effect),
                    this.autoClear && a.clear(o.clearColor, !0, !1, !1),
                    a.drawElementsType(Material.TriangleFillMode, 0, 6);
                a.unBindFramebuffer(this._rtWrapper, this.isCube),
                this.isCube && a.generateMipMapsForCubemap(this._texture),
                (n = a._debugPopGroup) === null || n === void 0 || n.call(a, 1),
                this.onGenerated && this.onGenerated(),
                this.onGeneratedObservable.notifyObservers(this)
            }
        }
    }
    ,
    e.prototype.clone = function() {
        var t = this.getSize()
          , r = new e(this.name,t.width,this._fragment,this.getScene(),this._fallbackTexture,this._generateMipMaps);
        return r.hasAlpha = this.hasAlpha,
        r.level = this.level,
        r.coordinatesMode = this.coordinatesMode,
        r
    }
    ,
    e.prototype.dispose = function() {
        var t = this.getScene();
        if (!!t) {
            var r = t.proceduralTextures.indexOf(this);
            r >= 0 && t.proceduralTextures.splice(r, 1);
            var n = this._vertexBuffers[VertexBuffer.PositionKind];
            n && (n.dispose(),
            this._vertexBuffers[VertexBuffer.PositionKind] = null),
            this._indexBuffer && this._fullEngine._releaseBuffer(this._indexBuffer) && (this._indexBuffer = null),
            this.onGeneratedObservable.clear(),
            this.onBeforeGenerationObservable.clear(),
            i.prototype.dispose.call(this)
        }
    }
    ,
    __decorate([serialize()], e.prototype, "isEnabled", void 0),
    __decorate([serialize()], e.prototype, "autoClear", void 0),
    __decorate([serialize()], e.prototype, "_generateMipMaps", void 0),
    __decorate([serialize()], e.prototype, "_size", void 0),
    __decorate([serialize()], e.prototype, "refreshRate", null),
    e
}(Texture);
RegisterClass("BABYLON.ProceduralTexture", ProceduralTexture);
var name$1A = "noisePixelShader"
  , shader$1A = `

uniform float brightness;
uniform float persistence;
uniform float timeScale;

varying vec2 vUV;

vec2 hash22(vec2 p)
{
p=p*mat2(127.1,311.7,269.5,183.3);
p=-1.0+2.0*fract(sin(p)*43758.5453123);
return sin(p*6.283+timeScale);
}
float interpolationNoise(vec2 p)
{
vec2 pi=floor(p);
vec2 pf=p-pi;
vec2 w=pf*pf*(3.-2.*pf);
float f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));
float f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));
float f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));
float f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));
float xm1=mix(f00,f10,w.x);
float xm2=mix(f01,f11,w.x);
float ym=mix(xm1,xm2,w.y);
return ym;
}
float perlinNoise2D(float x,float y)
{
float sum=0.0;
float frequency=0.0;
float amplitude=0.0;
for(int i=0; i<OCTAVES; i++)
{
frequency=pow(2.0,float(i));
amplitude=pow(persistence,float(i));
sum=sum+interpolationNoise(vec2(x*frequency,y*frequency))*amplitude;
}
return sum;
}

void main(void)
{
float x=abs(vUV.x);
float y=abs(vUV.y);
float noise=brightness+(1.0-brightness)*perlinNoise2D(x,y);
gl_FragColor=vec4(noise,noise,noise,1.0);
}
`;
ShaderStore.ShadersStore[name$1A] = shader$1A;
var NoiseProceduralTexture = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a) {
        r === void 0 && (r = 256),
        n === void 0 && (n = EngineStore.LastCreatedScene);
        var s = i.call(this, t, r, "noise", n, o, a) || this;
        return s.time = 0,
        s.brightness = .2,
        s.octaves = 3,
        s.persistence = .8,
        s.animationSpeedFactor = 1,
        s.autoClear = !1,
        s._updateShaderUniforms(),
        s
    }
    return e.prototype._updateShaderUniforms = function() {
        var t = this.getScene();
        !t || (this.time += t.getAnimationRatio() * this.animationSpeedFactor * .01,
        this.setFloat("brightness", this.brightness),
        this.setFloat("persistence", this.persistence),
        this.setFloat("timeScale", this.time))
    }
    ,
    e.prototype._getDefines = function() {
        return "#define OCTAVES " + (this.octaves | 0)
    }
    ,
    e.prototype.render = function(t) {
        this._updateShaderUniforms(),
        i.prototype.render.call(this, t)
    }
    ,
    e.prototype.serialize = function() {
        var t = {};
        return t.customType = "BABYLON.NoiseProceduralTexture",
        t.brightness = this.brightness,
        t.octaves = this.octaves,
        t.persistence = this.persistence,
        t.animationSpeedFactor = this.animationSpeedFactor,
        t.size = this.getSize().width,
        t.generateMipMaps = this._generateMipMaps,
        t.time = this.time,
        t
    }
    ,
    e.prototype.clone = function() {
        var t = this.getSize()
          , r = new e(this.name,t.width,this.getScene(),this._fallbackTexture ? this._fallbackTexture : void 0,this._generateMipMaps);
        return r.hasAlpha = this.hasAlpha,
        r.level = this.level,
        r.coordinatesMode = this.coordinatesMode,
        r.brightness = this.brightness,
        r.octaves = this.octaves,
        r.persistence = this.persistence,
        r.animationSpeedFactor = this.animationSpeedFactor,
        r.time = this.time,
        r
    }
    ,
    e.Parse = function(t, r) {
        var n, o = new e(t.name,t.size,r,void 0,t.generateMipMaps);
        return o.brightness = t.brightness,
        o.octaves = t.octaves,
        o.persistence = t.persistence,
        o.animationSpeedFactor = t.animationSpeedFactor,
        o.time = (n = t.time) !== null && n !== void 0 ? n : 0,
        o
    }
    ,
    e
}(ProceduralTexture);
RegisterClass("BABYLON.NoiseProceduralTexture", NoiseProceduralTexture);
var NodeMaterialBlockTargets;
(function(i) {
    i[i.Vertex = 1] = "Vertex",
    i[i.Fragment = 2] = "Fragment",
    i[i.Neutral = 4] = "Neutral",
    i[i.VertexAndFragment = 3] = "VertexAndFragment"
}
)(NodeMaterialBlockTargets || (NodeMaterialBlockTargets = {}));
var NodeMaterialBlockConnectionPointTypes;
(function(i) {
    i[i.Float = 1] = "Float",
    i[i.Int = 2] = "Int",
    i[i.Vector2 = 4] = "Vector2",
    i[i.Vector3 = 8] = "Vector3",
    i[i.Vector4 = 16] = "Vector4",
    i[i.Color3 = 32] = "Color3",
    i[i.Color4 = 64] = "Color4",
    i[i.Matrix = 128] = "Matrix",
    i[i.Object = 256] = "Object",
    i[i.AutoDetect = 1024] = "AutoDetect",
    i[i.BasedOnInput = 2048] = "BasedOnInput"
}
)(NodeMaterialBlockConnectionPointTypes || (NodeMaterialBlockConnectionPointTypes = {}));
var NodeMaterialBlockConnectionPointMode;
(function(i) {
    i[i.Uniform = 0] = "Uniform",
    i[i.Attribute = 1] = "Attribute",
    i[i.Varying = 2] = "Varying",
    i[i.Undefined = 3] = "Undefined"
}
)(NodeMaterialBlockConnectionPointMode || (NodeMaterialBlockConnectionPointMode = {}));
var NodeMaterialSystemValues;
(function(i) {
    i[i.World = 1] = "World",
    i[i.View = 2] = "View",
    i[i.Projection = 3] = "Projection",
    i[i.ViewProjection = 4] = "ViewProjection",
    i[i.WorldView = 5] = "WorldView",
    i[i.WorldViewProjection = 6] = "WorldViewProjection",
    i[i.CameraPosition = 7] = "CameraPosition",
    i[i.FogColor = 8] = "FogColor",
    i[i.DeltaTime = 9] = "DeltaTime",
    i[i.CameraParameters = 10] = "CameraParameters"
}
)(NodeMaterialSystemValues || (NodeMaterialSystemValues = {}));
var NodeMaterialModes;
(function(i) {
    i[i.Material = 0] = "Material",
    i[i.PostProcess = 1] = "PostProcess",
    i[i.Particle = 2] = "Particle",
    i[i.ProceduralTexture = 3] = "ProceduralTexture"
}
)(NodeMaterialModes || (NodeMaterialModes = {}));
var NodeMaterialConnectionPointCompatibilityStates;
(function(i) {
    i[i.Compatible = 0] = "Compatible",
    i[i.TypeIncompatible = 1] = "TypeIncompatible",
    i[i.TargetIncompatible = 2] = "TargetIncompatible",
    i[i.HierarchyIssue = 3] = "HierarchyIssue"
}
)(NodeMaterialConnectionPointCompatibilityStates || (NodeMaterialConnectionPointCompatibilityStates = {}));
var NodeMaterialConnectionPointDirection;
(function(i) {
    i[i.Input = 0] = "Input",
    i[i.Output = 1] = "Output"
}
)(NodeMaterialConnectionPointDirection || (NodeMaterialConnectionPointDirection = {}));
var NodeMaterialConnectionPoint = function() {
    function i(e, t, r) {
        this._connectedPoint = null,
        this._endpoints = new Array,
        this._typeConnectionSource = null,
        this._defaultConnectionPointType = null,
        this._linkedConnectionSource = null,
        this._acceptedConnectionPointType = null,
        this._type = NodeMaterialBlockConnectionPointTypes.Float,
        this._enforceAssociatedVariableName = !1,
        this.needDualDirectionValidation = !1,
        this.acceptedConnectionPointTypes = new Array,
        this.excludedConnectionPointTypes = new Array,
        this.onConnectionObservable = new Observable,
        this.isExposedOnFrame = !1,
        this.exposedPortPosition = -1,
        this._prioritizeVertex = !1,
        this._target = NodeMaterialBlockTargets.VertexAndFragment,
        this._ownerBlock = t,
        this.name = e,
        this._direction = r
    }
    return i.AreEquivalentTypes = function(e, t) {
        switch (e) {
        case NodeMaterialBlockConnectionPointTypes.Vector3:
            {
                if (t === NodeMaterialBlockConnectionPointTypes.Color3)
                    return !0;
                break
            }
        case NodeMaterialBlockConnectionPointTypes.Vector4:
            {
                if (t === NodeMaterialBlockConnectionPointTypes.Color4)
                    return !0;
                break
            }
        case NodeMaterialBlockConnectionPointTypes.Color3:
            {
                if (t === NodeMaterialBlockConnectionPointTypes.Vector3)
                    return !0;
                break
            }
        case NodeMaterialBlockConnectionPointTypes.Color4:
            {
                if (t === NodeMaterialBlockConnectionPointTypes.Vector4)
                    return !0;
                break
            }
        }
        return !1
    }
    ,
    Object.defineProperty(i.prototype, "direction", {
        get: function() {
            return this._direction
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "associatedVariableName", {
        get: function() {
            return this._ownerBlock.isInput ? this._ownerBlock.associatedVariableName : (!this._enforceAssociatedVariableName || !this._associatedVariableName) && this._connectedPoint ? this._connectedPoint.associatedVariableName : this._associatedVariableName
        },
        set: function(e) {
            this._associatedVariableName = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "innerType", {
        get: function() {
            return this._linkedConnectionSource && this._linkedConnectionSource.isConnected ? this.type : this._type
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "type", {
        get: function() {
            if (this._type === NodeMaterialBlockConnectionPointTypes.AutoDetect) {
                if (this._ownerBlock.isInput)
                    return this._ownerBlock.type;
                if (this._connectedPoint)
                    return this._connectedPoint.type;
                if (this._linkedConnectionSource && this._linkedConnectionSource.isConnected)
                    return this._linkedConnectionSource.type
            }
            if (this._type === NodeMaterialBlockConnectionPointTypes.BasedOnInput) {
                if (this._typeConnectionSource)
                    return !this._typeConnectionSource.isConnected && this._defaultConnectionPointType ? this._defaultConnectionPointType : this._typeConnectionSource.type;
                if (this._defaultConnectionPointType)
                    return this._defaultConnectionPointType
            }
            return this._type
        },
        set: function(e) {
            this._type = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "target", {
        get: function() {
            return !this._prioritizeVertex || !this._ownerBlock ? this._target : this._target !== NodeMaterialBlockTargets.VertexAndFragment ? this._target : this._ownerBlock.target === NodeMaterialBlockTargets.Fragment ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.Vertex
        },
        set: function(e) {
            this._target = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "isConnected", {
        get: function() {
            return this.connectedPoint !== null || this.hasEndpoints
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "isConnectedToInputBlock", {
        get: function() {
            return this.connectedPoint !== null && this.connectedPoint.ownerBlock.isInput
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "connectInputBlock", {
        get: function() {
            return this.isConnectedToInputBlock ? this.connectedPoint.ownerBlock : null
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "connectedPoint", {
        get: function() {
            return this._connectedPoint
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "ownerBlock", {
        get: function() {
            return this._ownerBlock
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "sourceBlock", {
        get: function() {
            return this._connectedPoint ? this._connectedPoint.ownerBlock : null
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "connectedBlocks", {
        get: function() {
            return this._endpoints.length === 0 ? [] : this._endpoints.map(function(e) {
                return e.ownerBlock
            })
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "endpoints", {
        get: function() {
            return this._endpoints
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "hasEndpoints", {
        get: function() {
            return this._endpoints && this._endpoints.length > 0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "isDirectlyConnectedToVertexOutput", {
        get: function() {
            if (!this.hasEndpoints)
                return !1;
            for (var e = 0, t = this._endpoints; e < t.length; e++) {
                var r = t[e];
                if (r.ownerBlock.target === NodeMaterialBlockTargets.Vertex || (r.ownerBlock.target === NodeMaterialBlockTargets.Neutral || r.ownerBlock.target === NodeMaterialBlockTargets.VertexAndFragment) && r.ownerBlock.outputs.some(function(n) {
                    return n.isDirectlyConnectedToVertexOutput
                }))
                    return !0
            }
            return !1
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "isConnectedInVertexShader", {
        get: function() {
            if (this.target === NodeMaterialBlockTargets.Vertex)
                return !0;
            if (!this.hasEndpoints)
                return !1;
            for (var e = 0, t = this._endpoints; e < t.length; e++) {
                var r = t[e];
                if (r.ownerBlock.target === NodeMaterialBlockTargets.Vertex || r.target === NodeMaterialBlockTargets.Vertex || (r.ownerBlock.target === NodeMaterialBlockTargets.Neutral || r.ownerBlock.target === NodeMaterialBlockTargets.VertexAndFragment) && r.ownerBlock.outputs.some(function(n) {
                    return n.isConnectedInVertexShader
                }))
                    return !0
            }
            return !1
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "isConnectedInFragmentShader", {
        get: function() {
            if (this.target === NodeMaterialBlockTargets.Fragment)
                return !0;
            if (!this.hasEndpoints)
                return !1;
            for (var e = 0, t = this._endpoints; e < t.length; e++) {
                var r = t[e];
                if (r.ownerBlock.target === NodeMaterialBlockTargets.Fragment || (r.ownerBlock.target === NodeMaterialBlockTargets.Neutral || r.ownerBlock.target === NodeMaterialBlockTargets.VertexAndFragment) && r.ownerBlock.outputs.some(function(n) {
                    return n.isConnectedInFragmentShader
                }))
                    return !0
            }
            return !1
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.createCustomInputBlock = function() {
        return null
    }
    ,
    i.prototype.getClassName = function() {
        return "NodeMaterialConnectionPoint"
    }
    ,
    i.prototype.canConnectTo = function(e) {
        return this.checkCompatibilityState(e) === NodeMaterialConnectionPointCompatibilityStates.Compatible
    }
    ,
    i.prototype.checkCompatibilityState = function(e) {
        var t = this._ownerBlock
          , r = e.ownerBlock;
        if (t.target === NodeMaterialBlockTargets.Fragment) {
            if (r.target === NodeMaterialBlockTargets.Vertex)
                return NodeMaterialConnectionPointCompatibilityStates.TargetIncompatible;
            for (var n = 0, o = r.outputs; n < o.length; n++) {
                var a = o[n];
                if (a.ownerBlock.target != NodeMaterialBlockTargets.Neutral && a.isConnectedInVertexShader)
                    return NodeMaterialConnectionPointCompatibilityStates.TargetIncompatible
            }
        }
        if (this.type !== e.type && e.innerType !== NodeMaterialBlockConnectionPointTypes.AutoDetect)
            return i.AreEquivalentTypes(this.type, e.type) || e.acceptedConnectionPointTypes && e.acceptedConnectionPointTypes.indexOf(this.type) !== -1 || e._acceptedConnectionPointType && i.AreEquivalentTypes(e._acceptedConnectionPointType.type, this.type) ? NodeMaterialConnectionPointCompatibilityStates.Compatible : NodeMaterialConnectionPointCompatibilityStates.TypeIncompatible;
        if (e.excludedConnectionPointTypes && e.excludedConnectionPointTypes.indexOf(this.type) !== -1)
            return NodeMaterialConnectionPointCompatibilityStates.TypeIncompatible;
        var s = r
          , l = t;
        return this.direction === NodeMaterialConnectionPointDirection.Input && (s = t,
        l = r),
        s.isAnAncestorOf(l) ? NodeMaterialConnectionPointCompatibilityStates.HierarchyIssue : NodeMaterialConnectionPointCompatibilityStates.Compatible
    }
    ,
    i.prototype.connectTo = function(e, t) {
        if (t === void 0 && (t = !1),
        !t && !this.canConnectTo(e))
            throw "Cannot connect these two connectors.";
        return this._endpoints.push(e),
        e._connectedPoint = this,
        this._enforceAssociatedVariableName = !1,
        this.onConnectionObservable.notifyObservers(e),
        e.onConnectionObservable.notifyObservers(this),
        this
    }
    ,
    i.prototype.disconnectFrom = function(e) {
        var t = this._endpoints.indexOf(e);
        return t === -1 ? this : (this._endpoints.splice(t, 1),
        e._connectedPoint = null,
        this._enforceAssociatedVariableName = !1,
        e._enforceAssociatedVariableName = !1,
        this)
    }
    ,
    i.prototype.serialize = function(e) {
        e === void 0 && (e = !0);
        var t = {};
        return t.name = this.name,
        t.displayName = this.displayName,
        e && this.connectedPoint && (t.inputName = this.name,
        t.targetBlockId = this.connectedPoint.ownerBlock.uniqueId,
        t.targetConnectionName = this.connectedPoint.name,
        t.isExposedOnFrame = !0,
        t.exposedPortPosition = this.exposedPortPosition),
        (this.isExposedOnFrame || this.exposedPortPosition >= 0) && (t.isExposedOnFrame = !0,
        t.exposedPortPosition = this.exposedPortPosition),
        t
    }
    ,
    i.prototype.dispose = function() {
        this.onConnectionObservable.clear()
    }
    ,
    i
}()
  , NodeMaterialBlock = function() {
    function i(e, t, r, n) {
        t === void 0 && (t = NodeMaterialBlockTargets.Vertex),
        r === void 0 && (r = !1),
        n === void 0 && (n = !1),
        this._isFinalMerger = !1,
        this._isInput = !1,
        this._name = "",
        this._isUnique = !1,
        this.inputsAreExclusive = !1,
        this._codeVariableName = "",
        this._inputs = new Array,
        this._outputs = new Array,
        this.comments = "",
        this.visibleInInspector = !1,
        this.visibleOnFrame = !1,
        this._target = t,
        this._originalTargetIsNeutral = t === NodeMaterialBlockTargets.Neutral,
        this._isFinalMerger = r,
        this._isInput = n,
        this._name = e,
        this.uniqueId = UniqueIdGenerator.UniqueId
    }
    return Object.defineProperty(i.prototype, "name", {
        get: function() {
            return this._name
        },
        set: function(e) {
            !this.validateBlockName(e) || (this._name = e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "isUnique", {
        get: function() {
            return this._isUnique
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "isFinalMerger", {
        get: function() {
            return this._isFinalMerger
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "isInput", {
        get: function() {
            return this._isInput
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "buildId", {
        get: function() {
            return this._buildId
        },
        set: function(e) {
            this._buildId = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "target", {
        get: function() {
            return this._target
        },
        set: function(e) {
            (this._target & e) === 0 && (this._target = e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "inputs", {
        get: function() {
            return this._inputs
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "outputs", {
        get: function() {
            return this._outputs
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.getInputByName = function(e) {
        var t = this._inputs.filter(function(r) {
            return r.name === e
        });
        return t.length ? t[0] : null
    }
    ,
    i.prototype.getOutputByName = function(e) {
        var t = this._outputs.filter(function(r) {
            return r.name === e
        });
        return t.length ? t[0] : null
    }
    ,
    i.prototype.initialize = function(e) {}
    ,
    i.prototype.bind = function(e, t, r, n) {}
    ,
    i.prototype._declareOutput = function(e, t) {
        return t._getGLType(e.type) + " " + e.associatedVariableName
    }
    ,
    i.prototype._writeVariable = function(e) {
        var t = e.connectedPoint;
        return t ? "" + e.associatedVariableName : "0."
    }
    ,
    i.prototype._writeFloat = function(e) {
        var t = e.toString();
        return t.indexOf(".") === -1 && (t += ".0"),
        "" + t
    }
    ,
    i.prototype.getClassName = function() {
        return "NodeMaterialBlock"
    }
    ,
    i.prototype.registerInput = function(e, t, r, n, o) {
        return r === void 0 && (r = !1),
        o = o != null ? o : new NodeMaterialConnectionPoint(e,this,NodeMaterialConnectionPointDirection.Input),
        o.type = t,
        o.isOptional = r,
        n && (o.target = n),
        this._inputs.push(o),
        this
    }
    ,
    i.prototype.registerOutput = function(e, t, r, n) {
        return n = n != null ? n : new NodeMaterialConnectionPoint(e,this,NodeMaterialConnectionPointDirection.Output),
        n.type = t,
        r && (n.target = r),
        this._outputs.push(n),
        this
    }
    ,
    i.prototype.getFirstAvailableInput = function(e) {
        e === void 0 && (e = null);
        for (var t = 0, r = this._inputs; t < r.length; t++) {
            var n = r[t];
            if (!n.connectedPoint && (!e || e.type === n.type || n.type === NodeMaterialBlockConnectionPointTypes.AutoDetect))
                return n
        }
        return null
    }
    ,
    i.prototype.getFirstAvailableOutput = function(e) {
        e === void 0 && (e = null);
        for (var t = 0, r = this._outputs; t < r.length; t++) {
            var n = r[t];
            if (!e || !e.target || e.target === NodeMaterialBlockTargets.Neutral || (e.target & n.target) !== 0)
                return n
        }
        return null
    }
    ,
    i.prototype.getSiblingOutput = function(e) {
        var t = this._outputs.indexOf(e);
        return t === -1 || t >= this._outputs.length ? null : this._outputs[t + 1]
    }
    ,
    i.prototype.isAnAncestorOf = function(e) {
        for (var t = 0, r = this._outputs; t < r.length; t++) {
            var n = r[t];
            if (!!n.hasEndpoints)
                for (var o = 0, a = n.endpoints; o < a.length; o++) {
                    var s = a[o];
                    if (s.ownerBlock === e || s.ownerBlock.isAnAncestorOf(e))
                        return !0
                }
        }
        return !1
    }
    ,
    i.prototype.connectTo = function(e, t) {
        if (this._outputs.length !== 0) {
            for (var r = t && t.output ? this.getOutputByName(t.output) : this.getFirstAvailableOutput(e), n = !0; n; ) {
                var o = t && t.input ? e.getInputByName(t.input) : e.getFirstAvailableInput(r);
                if (r && o && r.canConnectTo(o))
                    r.connectTo(o),
                    n = !1;
                else if (r)
                    r = this.getSiblingOutput(r);
                else
                    throw "Unable to find a compatible match"
            }
            return this
        }
    }
    ,
    i.prototype._buildBlock = function(e) {}
    ,
    i.prototype.updateUniformsAndSamples = function(e, t, r, n) {}
    ,
    i.prototype.provideFallbacks = function(e, t) {}
    ,
    i.prototype.initializeDefines = function(e, t, r, n) {}
    ,
    i.prototype.prepareDefines = function(e, t, r, n, o) {}
    ,
    i.prototype.autoConfigure = function(e) {}
    ,
    i.prototype.replaceRepeatableContent = function(e, t, r, n) {}
    ,
    Object.defineProperty(i.prototype, "willBeGeneratedIntoVertexShaderFromFragmentShader", {
        get: function() {
            return this.isInput || this.isFinalMerger || this._outputs.some(function(e) {
                return e.isDirectlyConnectedToVertexOutput
            }) ? !1 : !!(this.target === NodeMaterialBlockTargets.Vertex || (this.target === NodeMaterialBlockTargets.VertexAndFragment || this.target === NodeMaterialBlockTargets.Neutral) && this._outputs.some(function(e) {
                return e.isConnectedInVertexShader
            }))
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.isReady = function(e, t, r, n) {
        return !0
    }
    ,
    i.prototype._linkConnectionTypes = function(e, t, r) {
        r === void 0 && (r = !1),
        r ? this._inputs[t]._acceptedConnectionPointType = this._inputs[e] : this._inputs[e]._linkedConnectionSource = this._inputs[t],
        this._inputs[t]._linkedConnectionSource = this._inputs[e]
    }
    ,
    i.prototype._processBuild = function(e, t, r, n) {
        e.build(t, n);
        var o = t._vertexState != null
          , a = e._buildTarget === NodeMaterialBlockTargets.Vertex && e.target !== NodeMaterialBlockTargets.VertexAndFragment;
        if (o && ((e.target & e._buildTarget) === 0 || (e.target & r.target) === 0 || this.target !== NodeMaterialBlockTargets.VertexAndFragment && a) && (!e.isInput && t.target !== e._buildTarget || e.isInput && e.isAttribute && !e._noContextSwitch)) {
            var s = r.connectedPoint;
            t._vertexState._emitVaryingFromString("v_" + s.associatedVariableName, t._getGLType(s.type)) && (t._vertexState.compilationString += "v_" + s.associatedVariableName + " = " + s.associatedVariableName + `;\r
`),
            r.associatedVariableName = "v_" + s.associatedVariableName,
            r._enforceAssociatedVariableName = !0
        }
    }
    ,
    i.prototype.validateBlockName = function(e) {
        for (var t = ["position", "normal", "tangent", "particle_positionw", "uv", "uv2", "uv3", "uv4", "uv5", "uv6", "position2d", "particle_uv", "matricesIndices", "matricesWeights", "world0", "world1", "world2", "world3", "particle_color", "particle_texturemask"], r = 0, n = t; r < n.length; r++) {
            var o = n[r];
            if (e === o)
                return !1
        }
        return !0
    }
    ,
    i.prototype.build = function(e, t) {
        if (this._buildId === e.sharedData.buildId)
            return !0;
        if (!this.isInput)
            for (var r = 0, n = this._outputs; r < n.length; r++) {
                var o = n[r];
                o.associatedVariableName || (o.associatedVariableName = e._getFreeVariableName(o.name))
            }
        for (var a = 0, s = this._inputs; a < s.length; a++) {
            var l = s[a];
            if (!l.connectedPoint) {
                l.isOptional || e.sharedData.checks.notConnectedNonOptionalInputs.push(l);
                continue
            }
            if (!(this.target !== NodeMaterialBlockTargets.Neutral && ((l.target & this.target) === 0 || (l.target & e.target) === 0))) {
                var u = l.connectedPoint.ownerBlock;
                u && u !== this && this._processBuild(u, e, l, t)
            }
        }
        if (this._buildId === e.sharedData.buildId)
            return !0;
        if (e.sharedData.verbose && console.log((e.target === NodeMaterialBlockTargets.Vertex ? "Vertex shader" : "Fragment shader") + ": Building " + this.name + " [" + this.getClassName() + "]"),
        this.isFinalMerger)
            switch (e.target) {
            case NodeMaterialBlockTargets.Vertex:
                e.sharedData.checks.emitVertex = !0;
                break;
            case NodeMaterialBlockTargets.Fragment:
                e.sharedData.checks.emitFragment = !0;
                break
            }
        !this.isInput && e.sharedData.emitComments && (e.compilationString += `\r
//` + this.name + `\r
`),
        this._buildBlock(e),
        this._buildId = e.sharedData.buildId,
        this._buildTarget = e.target;
        for (var c = 0, h = this._outputs; c < h.length; c++) {
            var o = h[c];
            if ((o.target & e.target) !== 0)
                for (var f = 0, d = o.endpoints; f < d.length; f++) {
                    var _ = d[f]
                      , u = _.ownerBlock;
                    u && (u.target & e.target) !== 0 && t.indexOf(u) !== -1 && this._processBuild(u, e, _, t)
                }
        }
        return !1
    }
    ,
    i.prototype._inputRename = function(e) {
        return e
    }
    ,
    i.prototype._outputRename = function(e) {
        return e
    }
    ,
    i.prototype._dumpPropertiesCode = function() {
        var e = this._codeVariableName;
        return e + ".visibleInInspector = " + this.visibleInInspector + `;\r
` + e + ".visibleOnFrame = " + this.visibleOnFrame + `;\r
` + e + ".target = " + this.target + `;\r
`
    }
    ,
    i.prototype._dumpCode = function(e, t) {
        t.push(this);
        var r, n = this.name.replace(/[^A-Za-z_]+/g, "");
        if (this._codeVariableName = n || this.getClassName() + "_" + this.uniqueId,
        e.indexOf(this._codeVariableName) !== -1) {
            var o = 0;
            do
                o++,
                this._codeVariableName = n + o;
            while (e.indexOf(this._codeVariableName) !== -1)
        }
        e.push(this._codeVariableName),
        r = `\r
// ` + this.getClassName() + `\r
`,
        this.comments && (r += "// " + this.comments + `\r
`),
        r += "var " + this._codeVariableName + " = new BABYLON." + this.getClassName() + '("' + this.name + `");\r
`,
        r += this._dumpPropertiesCode();
        for (var a = 0, s = this.inputs; a < s.length; a++) {
            var l = s[a];
            if (!!l.isConnected) {
                var u = l.connectedPoint
                  , c = u.ownerBlock;
                t.indexOf(c) === -1 && (r += c._dumpCode(e, t))
            }
        }
        for (var h = 0, f = this.outputs; h < f.length; h++) {
            var d = f[h];
            if (!!d.hasEndpoints)
                for (var _ = 0, g = d.endpoints; _ < g.length; _++) {
                    var m = g[_]
                      , c = m.ownerBlock;
                    c && t.indexOf(c) === -1 && (r += c._dumpCode(e, t))
                }
        }
        return r
    }
    ,
    i.prototype._dumpCodeForOutputConnections = function(e) {
        var t = "";
        if (e.indexOf(this) !== -1)
            return t;
        e.push(this);
        for (var r = 0, n = this.inputs; r < n.length; r++) {
            var o = n[r];
            if (!!o.isConnected) {
                var a = o.connectedPoint
                  , s = a.ownerBlock;
                t += s._dumpCodeForOutputConnections(e),
                t += s._codeVariableName + "." + s._outputRename(a.name) + ".connectTo(" + this._codeVariableName + "." + this._inputRename(o.name) + `);\r
`
            }
        }
        return t
    }
    ,
    i.prototype.clone = function(e, t) {
        t === void 0 && (t = "");
        var r = this.serialize()
          , n = GetClass(r.customType);
        if (n) {
            var o = new n;
            return o._deserialize(r, e, t),
            o
        }
        return null
    }
    ,
    i.prototype.serialize = function() {
        var e = {};
        e.customType = "BABYLON." + this.getClassName(),
        e.id = this.uniqueId,
        e.name = this.name,
        e.comments = this.comments,
        e.visibleInInspector = this.visibleInInspector,
        e.visibleOnFrame = this.visibleOnFrame,
        e.target = this.target,
        e.inputs = [],
        e.outputs = [];
        for (var t = 0, r = this.inputs; t < r.length; t++) {
            var n = r[t];
            e.inputs.push(n.serialize())
        }
        for (var o = 0, a = this.outputs; o < a.length; o++) {
            var s = a[o];
            e.outputs.push(s.serialize(!1))
        }
        return e
    }
    ,
    i.prototype._deserialize = function(e, t, r) {
        var n;
        this.name = e.name,
        this.comments = e.comments,
        this.visibleInInspector = !!e.visibleInInspector,
        this.visibleOnFrame = !!e.visibleOnFrame,
        this._target = (n = e.target) !== null && n !== void 0 ? n : this.target,
        this._deserializePortDisplayNamesAndExposedOnFrame(e)
    }
    ,
    i.prototype._deserializePortDisplayNamesAndExposedOnFrame = function(e) {
        var t = this
          , r = e.inputs
          , n = e.outputs;
        r && r.forEach(function(o, a) {
            o.displayName && (t.inputs[a].displayName = o.displayName),
            o.isExposedOnFrame && (t.inputs[a].isExposedOnFrame = o.isExposedOnFrame,
            t.inputs[a].exposedPortPosition = o.exposedPortPosition)
        }),
        n && n.forEach(function(o, a) {
            o.displayName && (t.outputs[a].displayName = o.displayName),
            o.isExposedOnFrame && (t.outputs[a].isExposedOnFrame = o.isExposedOnFrame,
            t.outputs[a].exposedPortPosition = o.exposedPortPosition)
        })
    }
    ,
    i.prototype.dispose = function() {
        for (var e = 0, t = this.inputs; e < t.length; e++) {
            var r = t[e];
            r.dispose()
        }
        for (var n = 0, o = this.outputs; n < o.length; n++) {
            var a = o[n];
            a.dispose()
        }
    }
    ,
    i
}()
  , NodeMaterialBuildState = function() {
    function i() {
        this.supportUniformBuffers = !1,
        this.attributes = new Array,
        this.uniforms = new Array,
        this.constants = new Array,
        this.samplers = new Array,
        this.functions = {},
        this.extensions = {},
        this.counters = {},
        this._attributeDeclaration = "",
        this._uniformDeclaration = "",
        this._constantDeclaration = "",
        this._samplerDeclaration = "",
        this._varyingTransfer = "",
        this._injectAtEnd = "",
        this._repeatableContentAnchorIndex = 0,
        this._builtCompilationString = "",
        this.compilationString = ""
    }
    return i.prototype.finalize = function(e) {
        var t = e.sharedData.emitComments
          , r = this.target === NodeMaterialBlockTargets.Fragment;
        this.compilationString = `\r
` + (t ? `//Entry point\r
` : "") + `void main(void) {\r
` + this.compilationString,
        this._constantDeclaration && (this.compilationString = `\r
` + (t ? `//Constants\r
` : "") + this._constantDeclaration + `\r
` + this.compilationString);
        var n = "";
        for (var o in this.functions)
            n += this.functions[o] + `\r
`;
        this.compilationString = `\r
` + n + `\r
` + this.compilationString,
        !r && this._varyingTransfer && (this.compilationString = this.compilationString + `\r
` + this._varyingTransfer),
        this._injectAtEnd && (this.compilationString = this.compilationString + `\r
` + this._injectAtEnd),
        this.compilationString = this.compilationString + `\r
}`,
        this.sharedData.varyingDeclaration && (this.compilationString = `\r
` + (t ? `//Varyings\r
` : "") + this.sharedData.varyingDeclaration + `\r
` + this.compilationString),
        this._samplerDeclaration && (this.compilationString = `\r
` + (t ? `//Samplers\r
` : "") + this._samplerDeclaration + `\r
` + this.compilationString),
        this._uniformDeclaration && (this.compilationString = `\r
` + (t ? `//Uniforms\r
` : "") + this._uniformDeclaration + `\r
` + this.compilationString),
        this._attributeDeclaration && !r && (this.compilationString = `\r
` + (t ? `//Attributes\r
` : "") + this._attributeDeclaration + `\r
` + this.compilationString),
        this.compilationString = `precision highp float;\r
` + this.compilationString;
        for (var a in this.extensions) {
            var s = this.extensions[a];
            this.compilationString = `\r
` + s + `\r
` + this.compilationString
        }
        this._builtCompilationString = this.compilationString
    }
    ,
    Object.defineProperty(i.prototype, "_repeatableContentAnchor", {
        get: function() {
            return "###___ANCHOR" + this._repeatableContentAnchorIndex++ + "___###"
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype._getFreeVariableName = function(e) {
        return e = e.replace(/[^a-zA-Z_]+/g, ""),
        this.sharedData.variableNames[e] === void 0 ? (this.sharedData.variableNames[e] = 0,
        e === "output" || e === "texture" ? e + this.sharedData.variableNames[e] : e) : (this.sharedData.variableNames[e]++,
        e + this.sharedData.variableNames[e])
    }
    ,
    i.prototype._getFreeDefineName = function(e) {
        return this.sharedData.defineNames[e] === void 0 ? this.sharedData.defineNames[e] = 0 : this.sharedData.defineNames[e]++,
        e + this.sharedData.defineNames[e]
    }
    ,
    i.prototype._excludeVariableName = function(e) {
        this.sharedData.variableNames[e] = 0
    }
    ,
    i.prototype._emit2DSampler = function(e) {
        this.samplers.indexOf(e) < 0 && (this._samplerDeclaration += "uniform sampler2D " + e + `;\r
`,
        this.samplers.push(e))
    }
    ,
    i.prototype._getGLType = function(e) {
        switch (e) {
        case NodeMaterialBlockConnectionPointTypes.Float:
            return "float";
        case NodeMaterialBlockConnectionPointTypes.Int:
            return "int";
        case NodeMaterialBlockConnectionPointTypes.Vector2:
            return "vec2";
        case NodeMaterialBlockConnectionPointTypes.Color3:
        case NodeMaterialBlockConnectionPointTypes.Vector3:
            return "vec3";
        case NodeMaterialBlockConnectionPointTypes.Color4:
        case NodeMaterialBlockConnectionPointTypes.Vector4:
            return "vec4";
        case NodeMaterialBlockConnectionPointTypes.Matrix:
            return "mat4"
        }
        return ""
    }
    ,
    i.prototype._emitExtension = function(e, t, r) {
        r === void 0 && (r = ""),
        !this.extensions[e] && (r && (t = "#if " + r + `\r
` + t + `\r
#endif`),
        this.extensions[e] = t)
    }
    ,
    i.prototype._emitFunction = function(e, t, r) {
        this.functions[e] || (this.sharedData.emitComments && (t = r + `\r
` + t),
        this.functions[e] = t)
    }
    ,
    i.prototype._emitCodeFromInclude = function(e, t, r) {
        if (r && r.repeatKey)
            return "#include<" + e + ">[0.." + r.repeatKey + `]\r
`;
        var n = Effect.IncludesShadersStore[e] + `\r
`;
        if (this.sharedData.emitComments && (n = t + `\r
` + n),
        !r)
            return n;
        if (r.replaceStrings)
            for (var o = 0; o < r.replaceStrings.length; o++) {
                var a = r.replaceStrings[o];
                n = n.replace(a.search, a.replace)
            }
        return n
    }
    ,
    i.prototype._emitFunctionFromInclude = function(e, t, r, n) {
        n === void 0 && (n = "");
        var o = e + n;
        if (!this.functions[o]) {
            if (!r || !r.removeAttributes && !r.removeUniforms && !r.removeVaryings && !r.removeIfDef && !r.replaceStrings) {
                r && r.repeatKey ? this.functions[o] = "#include<" + e + ">[0.." + r.repeatKey + `]\r
` : this.functions[o] = "#include<" + e + `>\r
`,
                this.sharedData.emitComments && (this.functions[o] = t + `\r
` + this.functions[o]);
                return
            }
            if (this.functions[o] = Effect.IncludesShadersStore[e],
            this.sharedData.emitComments && (this.functions[o] = t + `\r
` + this.functions[o]),
            r.removeIfDef && (this.functions[o] = this.functions[o].replace(/^\s*?#ifdef.+$/gm, ""),
            this.functions[o] = this.functions[o].replace(/^\s*?#endif.*$/gm, ""),
            this.functions[o] = this.functions[o].replace(/^\s*?#else.*$/gm, ""),
            this.functions[o] = this.functions[o].replace(/^\s*?#elif.*$/gm, "")),
            r.removeAttributes && (this.functions[o] = this.functions[o].replace(/^\s*?attribute.+$/gm, "")),
            r.removeUniforms && (this.functions[o] = this.functions[o].replace(/^\s*?uniform.+$/gm, "")),
            r.removeVaryings && (this.functions[o] = this.functions[o].replace(/^\s*?varying.+$/gm, "")),
            r.replaceStrings)
                for (var a = 0; a < r.replaceStrings.length; a++) {
                    var s = r.replaceStrings[a];
                    this.functions[o] = this.functions[o].replace(s.search, s.replace)
                }
        }
    }
    ,
    i.prototype._registerTempVariable = function(e) {
        return this.sharedData.temps.indexOf(e) !== -1 ? !1 : (this.sharedData.temps.push(e),
        !0)
    }
    ,
    i.prototype._emitVaryingFromString = function(e, t, r, n) {
        return r === void 0 && (r = ""),
        n === void 0 && (n = !1),
        this.sharedData.varyings.indexOf(e) !== -1 ? !1 : (this.sharedData.varyings.push(e),
        r && (StartsWith(r, "defined(") ? this.sharedData.varyingDeclaration += "#if " + r + `\r
` : this.sharedData.varyingDeclaration += (n ? "#ifndef" : "#ifdef") + " " + r + `\r
`),
        this.sharedData.varyingDeclaration += "varying " + t + " " + e + `;\r
`,
        r && (this.sharedData.varyingDeclaration += `#endif\r
`),
        !0)
    }
    ,
    i.prototype._emitUniformFromString = function(e, t, r, n) {
        r === void 0 && (r = ""),
        n === void 0 && (n = !1),
        this.uniforms.indexOf(e) === -1 && (this.uniforms.push(e),
        r && (StartsWith(r, "defined(") ? this._uniformDeclaration += "#if " + r + `\r
` : this._uniformDeclaration += (n ? "#ifndef" : "#ifdef") + " " + r + `\r
`),
        this._uniformDeclaration += "uniform " + t + " " + e + `;\r
`,
        r && (this._uniformDeclaration += `#endif\r
`))
    }
    ,
    i.prototype._emitFloat = function(e) {
        return e.toString() === e.toFixed(0) ? e + ".0" : e.toString()
    }
    ,
    i
}()
  , NodeMaterialBuildStateSharedData = function() {
    function i() {
        this.temps = new Array,
        this.varyings = new Array,
        this.varyingDeclaration = "",
        this.inputBlocks = new Array,
        this.textureBlocks = new Array,
        this.bindableBlocks = new Array,
        this.forcedBindableBlocks = new Array,
        this.blocksWithFallbacks = new Array,
        this.blocksWithDefines = new Array,
        this.repeatableContentBlocks = new Array,
        this.dynamicUniformBlocks = new Array,
        this.blockingBlocks = new Array,
        this.animatedInputs = new Array,
        this.variableNames = {},
        this.defineNames = {},
        this.hints = {
            needWorldViewMatrix: !1,
            needWorldViewProjectionMatrix: !1,
            needAlphaBlending: !1,
            needAlphaTesting: !1
        },
        this.checks = {
            emitVertex: !1,
            emitFragment: !1,
            notConnectedNonOptionalInputs: new Array
        },
        this.allowEmptyVertexProgram = !1,
        this.variableNames.position = 0,
        this.variableNames.normal = 0,
        this.variableNames.tangent = 0,
        this.variableNames.uv = 0,
        this.variableNames.uv2 = 0,
        this.variableNames.uv3 = 0,
        this.variableNames.uv4 = 0,
        this.variableNames.uv5 = 0,
        this.variableNames.uv6 = 0,
        this.variableNames.color = 0,
        this.variableNames.matricesIndices = 0,
        this.variableNames.matricesWeights = 0,
        this.variableNames.matricesIndicesExtra = 0,
        this.variableNames.matricesWeightsExtra = 0,
        this.variableNames.diffuseBase = 0,
        this.variableNames.specularBase = 0,
        this.variableNames.worldPos = 0,
        this.variableNames.shadow = 0,
        this.variableNames.view = 0,
        this.variableNames.vTBN = 0,
        this.defineNames.MAINUV0 = 0,
        this.defineNames.MAINUV1 = 0,
        this.defineNames.MAINUV2 = 0,
        this.defineNames.MAINUV3 = 0,
        this.defineNames.MAINUV4 = 0,
        this.defineNames.MAINUV5 = 0,
        this.defineNames.MAINUV6 = 0,
        this.defineNames.MAINUV7 = 0
    }
    return i.prototype.emitErrors = function() {
        var e = "";
        !this.checks.emitVertex && !this.allowEmptyVertexProgram && (e += `NodeMaterial does not have a vertex output. You need to at least add a block that generates a glPosition value.\r
`),
        this.checks.emitFragment || (e += `NodeMaterial does not have a fragment output. You need to at least add a block that generates a glFragColor value.\r
`);
        for (var t = 0, r = this.checks.notConnectedNonOptionalInputs; t < r.length; t++) {
            var n = r[t];
            e += "input " + n.name + " from block " + n.ownerBlock.name + "[" + n.ownerBlock.getClassName() + `] is not connected and is not optional.\r
`
        }
        if (e)
            throw `Build of NodeMaterial failed:\r
` + e
    }
    ,
    i
}()
  , TransformBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Neutral) || this;
        return r.complementW = 1,
        r.complementZ = 0,
        r.target = NodeMaterialBlockTargets.Vertex,
        r.registerInput("vector", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        r.registerInput("transform", NodeMaterialBlockConnectionPointTypes.Matrix),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector4),
        r.registerOutput("xyz", NodeMaterialBlockConnectionPointTypes.Vector3),
        r._inputs[0].onConnectionObservable.add(function(n) {
            if (n.ownerBlock.isInput) {
                var o = n.ownerBlock;
                (o.name === "normal" || o.name === "tangent") && (r.complementW = 0)
            }
        }),
        r
    }
    return e.prototype.getClassName = function() {
        return "TransformBlock"
    }
    ,
    Object.defineProperty(e.prototype, "vector", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "xyz", {
        get: function() {
            return this._outputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "transform", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = this.vector
          , n = this.transform;
        if (r.connectedPoint) {
            if (this.complementW === 0) {
                var o = "//" + this.name;
                t._emitFunctionFromInclude("helperFunctions", o),
                t.sharedData.blocksWithDefines.push(this);
                var a = t._getFreeVariableName(n.associatedVariableName + "_NUS");
                switch (t.compilationString += "mat3 " + a + " = mat3(" + n.associatedVariableName + `);\r
`,
                t.compilationString += `#ifdef NONUNIFORMSCALING\r
`,
                t.compilationString += a + " = transposeMat3(inverseMat3(" + a + `));\r
`,
                t.compilationString += `#endif\r
`,
                r.connectedPoint.type) {
                case NodeMaterialBlockConnectionPointTypes.Vector2:
                    t.compilationString += this._declareOutput(this.output, t) + (" = vec4(" + a + " * vec3(" + r.associatedVariableName + ", " + this._writeFloat(this.complementZ) + "), " + this._writeFloat(this.complementW) + `);\r
`);
                    break;
                case NodeMaterialBlockConnectionPointTypes.Vector3:
                case NodeMaterialBlockConnectionPointTypes.Color3:
                    t.compilationString += this._declareOutput(this.output, t) + (" = vec4(" + a + " * " + r.associatedVariableName + ", " + this._writeFloat(this.complementW) + `);\r
`);
                    break;
                default:
                    t.compilationString += this._declareOutput(this.output, t) + (" = vec4(" + a + " * " + r.associatedVariableName + ".xyz, " + this._writeFloat(this.complementW) + `);\r
`);
                    break
                }
            } else {
                var a = n.associatedVariableName;
                switch (r.connectedPoint.type) {
                case NodeMaterialBlockConnectionPointTypes.Vector2:
                    t.compilationString += this._declareOutput(this.output, t) + (" = " + a + " * vec4(" + r.associatedVariableName + ", " + this._writeFloat(this.complementZ) + ", " + this._writeFloat(this.complementW) + `);\r
`);
                    break;
                case NodeMaterialBlockConnectionPointTypes.Vector3:
                case NodeMaterialBlockConnectionPointTypes.Color3:
                    t.compilationString += this._declareOutput(this.output, t) + (" = " + a + " * vec4(" + r.associatedVariableName + ", " + this._writeFloat(this.complementW) + `);\r
`);
                    break;
                default:
                    t.compilationString += this._declareOutput(this.output, t) + (" = " + a + " * " + r.associatedVariableName + `;\r
`);
                    break
                }
            }
            this.xyz.hasEndpoints && (t.compilationString += this._declareOutput(this.xyz, t) + (" = " + this.output.associatedVariableName + `.xyz;\r
`))
        }
        return this
    }
    ,
    e.prototype.prepareDefines = function(t, r, n, o, a) {
        t.nonUniformScaling && n.setValue("NONUNIFORMSCALING", !0)
    }
    ,
    e.prototype.serialize = function() {
        var t = i.prototype.serialize.call(this);
        return t.complementZ = this.complementZ,
        t.complementW = this.complementW,
        t
    }
    ,
    e.prototype._deserialize = function(t, r, n) {
        i.prototype._deserialize.call(this, t, r, n),
        this.complementZ = t.complementZ !== void 0 ? t.complementZ : 0,
        this.complementW = t.complementW !== void 0 ? t.complementW : 1
    }
    ,
    e.prototype._dumpPropertiesCode = function() {
        var t = i.prototype._dumpPropertiesCode.call(this) + (this._codeVariableName + ".complementZ = " + this.complementZ + `;\r
`);
        return t += this._codeVariableName + ".complementW = " + this.complementW + `;\r
`,
        t
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.TransformBlock", TransformBlock);
var VertexOutputBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Vertex, !0) || this;
        return r.registerInput("vector", NodeMaterialBlockConnectionPointTypes.Vector4),
        r
    }
    return e.prototype.getClassName = function() {
        return "VertexOutputBlock"
    }
    ,
    Object.defineProperty(e.prototype, "vector", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._isLogarithmicDepthEnabled = function(t) {
        for (var r = 0, n = t; r < n.length; r++) {
            var o = n[r];
            if (o.useLogarithmicDepth)
                return !0
        }
        return !1
    }
    ,
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = this.vector;
        return t.compilationString += "gl_Position = " + r.associatedVariableName + `;\r
`,
        this._isLogarithmicDepthEnabled(t.sharedData.fragmentOutputNodes) && (t._emitUniformFromString("logarithmicDepthConstant", "float"),
        t._emitVaryingFromString("vFragmentDepth", "float"),
        t.compilationString += `vFragmentDepth = 1.0 + gl_Position.w;\r
`,
        t.compilationString += `gl_Position.z = log2(max(0.000001, vFragmentDepth)) * logarithmicDepthConstant;\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.VertexOutputBlock", VertexOutputBlock);
var PropertyTypeForEdition;
(function(i) {
    i[i.Boolean = 0] = "Boolean",
    i[i.Float = 1] = "Float",
    i[i.Int = 2] = "Int",
    i[i.Vector2 = 3] = "Vector2",
    i[i.List = 4] = "List"
}
)(PropertyTypeForEdition || (PropertyTypeForEdition = {}));
function editableInPropertyPage(i, e, t, r) {
    return e === void 0 && (e = PropertyTypeForEdition.Boolean),
    t === void 0 && (t = "PROPERTIES"),
    function(n, o) {
        var a = n._propStore;
        a || (a = [],
        n._propStore = a),
        a.push({
            propertyName: o,
            displayName: i,
            type: e,
            groupName: t,
            options: r != null ? r : {}
        })
    }
}
var FragmentOutputBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Fragment, !0) || this;
        return r.convertToGammaSpace = !1,
        r.convertToLinearSpace = !1,
        r.useLogarithmicDepth = !1,
        r.registerInput("rgba", NodeMaterialBlockConnectionPointTypes.Color4, !0),
        r.registerInput("rgb", NodeMaterialBlockConnectionPointTypes.Color3, !0),
        r.registerInput("a", NodeMaterialBlockConnectionPointTypes.Float, !0),
        r.rgb.acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float),
        r
    }
    return e.prototype.getClassName = function() {
        return "FragmentOutputBlock"
    }
    ,
    e.prototype.initialize = function(t) {
        t._excludeVariableName("logarithmicDepthConstant"),
        t._excludeVariableName("vFragmentDepth")
    }
    ,
    Object.defineProperty(e.prototype, "rgba", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "rgb", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "a", {
        get: function() {
            return this._inputs[2]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.prepareDefines = function(t, r, n) {
        n.setValue(this._linearDefineName, this.convertToLinearSpace, !0),
        n.setValue(this._gammaDefineName, this.convertToGammaSpace, !0)
    }
    ,
    e.prototype.bind = function(t, r, n) {
        this.useLogarithmicDepth && n && MaterialHelper.BindLogDepth(void 0, t, n.getScene())
    }
    ,
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = this.rgba
          , n = this.rgb
          , o = this.a;
        t.sharedData.hints.needAlphaBlending = r.isConnected || o.isConnected,
        t.sharedData.blocksWithDefines.push(this),
        this.useLogarithmicDepth && (t._emitUniformFromString("logarithmicDepthConstant", "float"),
        t._emitVaryingFromString("vFragmentDepth", "float"),
        t.sharedData.bindableBlocks.push(this)),
        this._linearDefineName = t._getFreeDefineName("CONVERTTOLINEAR"),
        this._gammaDefineName = t._getFreeDefineName("CONVERTTOGAMMA");
        var a = "//" + this.name;
        if (t._emitFunctionFromInclude("helperFunctions", a),
        r.connectedPoint)
            o.isConnected ? t.compilationString += "gl_FragColor = vec4(" + r.associatedVariableName + ".rgb, " + o.associatedVariableName + `);\r
` : t.compilationString += "gl_FragColor = " + r.associatedVariableName + `;\r
`;
        else if (n.connectedPoint) {
            var s = "1.0";
            o.connectedPoint && (s = o.associatedVariableName),
            n.connectedPoint.type === NodeMaterialBlockConnectionPointTypes.Float ? t.compilationString += "gl_FragColor = vec4(" + n.associatedVariableName + ", " + n.associatedVariableName + ", " + n.associatedVariableName + ", " + s + `);\r
` : t.compilationString += "gl_FragColor = vec4(" + n.associatedVariableName + ", " + s + `);\r
`
        } else
            t.sharedData.checks.notConnectedNonOptionalInputs.push(r);
        return t.compilationString += "#ifdef " + this._linearDefineName + `\r
`,
        t.compilationString += `gl_FragColor = toLinearSpace(gl_FragColor);\r
`,
        t.compilationString += `#endif\r
`,
        t.compilationString += "#ifdef " + this._gammaDefineName + `\r
`,
        t.compilationString += `gl_FragColor = toGammaSpace(gl_FragColor);\r
`,
        t.compilationString += `#endif\r
`,
        this.useLogarithmicDepth && (t.compilationString += `gl_FragDepthEXT = log2(vFragmentDepth) * logarithmicDepthConstant * 0.5;\r
`),
        this
    }
    ,
    e.prototype._dumpPropertiesCode = function() {
        var t = i.prototype._dumpPropertiesCode.call(this);
        return t += this._codeVariableName + ".convertToGammaSpace = " + this.convertToGammaSpace + `;\r
`,
        t += this._codeVariableName + ".convertToLinearSpace = " + this.convertToLinearSpace + `;\r
`,
        t += this._codeVariableName + ".useLogarithmicDepth = " + this.useLogarithmicDepth + `;\r
`,
        t
    }
    ,
    e.prototype.serialize = function() {
        var t = i.prototype.serialize.call(this);
        return t.convertToGammaSpace = this.convertToGammaSpace,
        t.convertToLinearSpace = this.convertToLinearSpace,
        t.useLogarithmicDepth = this.useLogarithmicDepth,
        t
    }
    ,
    e.prototype._deserialize = function(t, r, n) {
        var o;
        i.prototype._deserialize.call(this, t, r, n),
        this.convertToGammaSpace = t.convertToGammaSpace,
        this.convertToLinearSpace = t.convertToLinearSpace,
        this.useLogarithmicDepth = (o = t.useLogarithmicDepth) !== null && o !== void 0 ? o : !1
    }
    ,
    __decorate([editableInPropertyPage("Convert to gamma space", PropertyTypeForEdition.Boolean, "PROPERTIES", {
        notifiers: {
            update: !0
        }
    })], e.prototype, "convertToGammaSpace", void 0),
    __decorate([editableInPropertyPage("Convert to linear space", PropertyTypeForEdition.Boolean, "PROPERTIES", {
        notifiers: {
            update: !0
        }
    })], e.prototype, "convertToLinearSpace", void 0),
    __decorate([editableInPropertyPage("Use logarithmic depth", PropertyTypeForEdition.Boolean, "PROPERTIES")], e.prototype, "useLogarithmicDepth", void 0),
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.FragmentOutputBlock", FragmentOutputBlock);
var AnimatedInputBlockTypes;
(function(i) {
    i[i.None = 0] = "None",
    i[i.Time = 1] = "Time"
}
)(AnimatedInputBlockTypes || (AnimatedInputBlockTypes = {}));
var remapAttributeName = {
    position2d: "position",
    particle_uv: "vUV",
    particle_color: "vColor",
    particle_texturemask: "textureMask",
    particle_positionw: "vPositionW"
}
  , attributeInFragmentOnly = {
    particle_uv: !0,
    particle_color: !0,
    particle_texturemask: !0,
    particle_positionw: !0
}
  , attributeAsUniform = {
    particle_texturemask: !0
}
  , InputBlock = function(i) {
    __extends(e, i);
    function e(t, r, n) {
        r === void 0 && (r = NodeMaterialBlockTargets.Vertex),
        n === void 0 && (n = NodeMaterialBlockConnectionPointTypes.AutoDetect);
        var o = i.call(this, t, r, !1, !0) || this;
        return o._mode = NodeMaterialBlockConnectionPointMode.Undefined,
        o._animationType = AnimatedInputBlockTypes.None,
        o.min = 0,
        o.max = 0,
        o.isBoolean = !1,
        o.matrixMode = 0,
        o._systemValue = null,
        o.isConstant = !1,
        o.groupInInspector = "",
        o.onValueChangedObservable = new Observable,
        o.convertToGammaSpace = !1,
        o.convertToLinearSpace = !1,
        o._type = n,
        o.setDefaultValue(),
        o.registerOutput("output", n),
        o
    }
    return Object.defineProperty(e.prototype, "type", {
        get: function() {
            if (this._type === NodeMaterialBlockConnectionPointTypes.AutoDetect) {
                if (this.isUniform && this.value != null) {
                    if (!isNaN(this.value))
                        return this._type = NodeMaterialBlockConnectionPointTypes.Float,
                        this._type;
                    switch (this.value.getClassName()) {
                    case "Vector2":
                        return this._type = NodeMaterialBlockConnectionPointTypes.Vector2,
                        this._type;
                    case "Vector3":
                        return this._type = NodeMaterialBlockConnectionPointTypes.Vector3,
                        this._type;
                    case "Vector4":
                        return this._type = NodeMaterialBlockConnectionPointTypes.Vector4,
                        this._type;
                    case "Color3":
                        return this._type = NodeMaterialBlockConnectionPointTypes.Color3,
                        this._type;
                    case "Color4":
                        return this._type = NodeMaterialBlockConnectionPointTypes.Color4,
                        this._type;
                    case "Matrix":
                        return this._type = NodeMaterialBlockConnectionPointTypes.Matrix,
                        this._type
                    }
                }
                if (this.isAttribute)
                    switch (this.name) {
                    case "position":
                    case "normal":
                    case "tangent":
                    case "particle_positionw":
                        return this._type = NodeMaterialBlockConnectionPointTypes.Vector3,
                        this._type;
                    case "uv":
                    case "uv2":
                    case "uv3":
                    case "uv4":
                    case "uv5":
                    case "uv6":
                    case "position2d":
                    case "particle_uv":
                        return this._type = NodeMaterialBlockConnectionPointTypes.Vector2,
                        this._type;
                    case "matricesIndices":
                    case "matricesWeights":
                    case "world0":
                    case "world1":
                    case "world2":
                    case "world3":
                        return this._type = NodeMaterialBlockConnectionPointTypes.Vector4,
                        this._type;
                    case "color":
                    case "particle_color":
                    case "particle_texturemask":
                        return this._type = NodeMaterialBlockConnectionPointTypes.Color4,
                        this._type
                    }
                if (this.isSystemValue)
                    switch (this._systemValue) {
                    case NodeMaterialSystemValues.World:
                    case NodeMaterialSystemValues.WorldView:
                    case NodeMaterialSystemValues.WorldViewProjection:
                    case NodeMaterialSystemValues.View:
                    case NodeMaterialSystemValues.ViewProjection:
                    case NodeMaterialSystemValues.Projection:
                        return this._type = NodeMaterialBlockConnectionPointTypes.Matrix,
                        this._type;
                    case NodeMaterialSystemValues.CameraPosition:
                        return this._type = NodeMaterialBlockConnectionPointTypes.Vector3,
                        this._type;
                    case NodeMaterialSystemValues.FogColor:
                        return this._type = NodeMaterialBlockConnectionPointTypes.Color3,
                        this._type;
                    case NodeMaterialSystemValues.DeltaTime:
                        return this._type = NodeMaterialBlockConnectionPointTypes.Float,
                        this._type;
                    case NodeMaterialSystemValues.CameraParameters:
                        return this._type = NodeMaterialBlockConnectionPointTypes.Vector4,
                        this._type
                    }
            }
            return this._type
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.validateBlockName = function(t) {
        return this.isAttribute ? !0 : i.prototype.validateBlockName.call(this, t)
    }
    ,
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.setAsAttribute = function(t) {
        return this._mode = NodeMaterialBlockConnectionPointMode.Attribute,
        t && (this.name = t),
        this
    }
    ,
    e.prototype.setAsSystemValue = function(t) {
        return this.systemValue = t,
        this
    }
    ,
    Object.defineProperty(e.prototype, "value", {
        get: function() {
            return this._storedValue
        },
        set: function(t) {
            this.type === NodeMaterialBlockConnectionPointTypes.Float && (this.isBoolean ? t = t ? 1 : 0 : this.min !== this.max && (t = Math.max(this.min, t),
            t = Math.min(this.max, t))),
            this._storedValue = t,
            this._mode = NodeMaterialBlockConnectionPointMode.Uniform,
            this.onValueChangedObservable.notifyObservers(this)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "valueCallback", {
        get: function() {
            return this._valueCallback
        },
        set: function(t) {
            this._valueCallback = t,
            this._mode = NodeMaterialBlockConnectionPointMode.Uniform
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "associatedVariableName", {
        get: function() {
            return this._associatedVariableName
        },
        set: function(t) {
            this._associatedVariableName = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "animationType", {
        get: function() {
            return this._animationType
        },
        set: function(t) {
            this._animationType = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "isUndefined", {
        get: function() {
            return this._mode === NodeMaterialBlockConnectionPointMode.Undefined
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "isUniform", {
        get: function() {
            return this._mode === NodeMaterialBlockConnectionPointMode.Uniform
        },
        set: function(t) {
            this._mode = t ? NodeMaterialBlockConnectionPointMode.Uniform : NodeMaterialBlockConnectionPointMode.Undefined,
            this.associatedVariableName = ""
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "isAttribute", {
        get: function() {
            return this._mode === NodeMaterialBlockConnectionPointMode.Attribute
        },
        set: function(t) {
            this._mode = t ? NodeMaterialBlockConnectionPointMode.Attribute : NodeMaterialBlockConnectionPointMode.Undefined,
            this.associatedVariableName = ""
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "isVarying", {
        get: function() {
            return this._mode === NodeMaterialBlockConnectionPointMode.Varying
        },
        set: function(t) {
            this._mode = t ? NodeMaterialBlockConnectionPointMode.Varying : NodeMaterialBlockConnectionPointMode.Undefined,
            this.associatedVariableName = ""
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "isSystemValue", {
        get: function() {
            return this._systemValue != null
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "systemValue", {
        get: function() {
            return this._systemValue
        },
        set: function(t) {
            this._mode = NodeMaterialBlockConnectionPointMode.Uniform,
            this.associatedVariableName = "",
            this._systemValue = t
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getClassName = function() {
        return "InputBlock"
    }
    ,
    e.prototype.animate = function(t) {
        switch (this._animationType) {
        case AnimatedInputBlockTypes.Time:
            {
                this.type === NodeMaterialBlockConnectionPointTypes.Float && (this.value += t.getAnimationRatio() * .01);
                break
            }
        }
    }
    ,
    e.prototype._emitDefine = function(t) {
        return t[0] === "!" ? "#ifndef " + t.substring(1) + `\r
` : "#ifdef " + t + `\r
`
    }
    ,
    e.prototype.initialize = function(t) {
        this.associatedVariableName = ""
    }
    ,
    e.prototype.setDefaultValue = function() {
        switch (this.type) {
        case NodeMaterialBlockConnectionPointTypes.Float:
            this.value = 0;
            break;
        case NodeMaterialBlockConnectionPointTypes.Vector2:
            this.value = Vector2.Zero();
            break;
        case NodeMaterialBlockConnectionPointTypes.Vector3:
            this.value = Vector3.Zero();
            break;
        case NodeMaterialBlockConnectionPointTypes.Vector4:
            this.value = Vector4.Zero();
            break;
        case NodeMaterialBlockConnectionPointTypes.Color3:
            this.value = Color3.White();
            break;
        case NodeMaterialBlockConnectionPointTypes.Color4:
            this.value = new Color4(1,1,1,1);
            break;
        case NodeMaterialBlockConnectionPointTypes.Matrix:
            this.value = Matrix.Identity();
            break
        }
    }
    ,
    e.prototype._emitConstant = function(t) {
        switch (this.type) {
        case NodeMaterialBlockConnectionPointTypes.Float:
            return "" + t._emitFloat(this.value);
        case NodeMaterialBlockConnectionPointTypes.Vector2:
            return "vec2(" + this.value.x + ", " + this.value.y + ")";
        case NodeMaterialBlockConnectionPointTypes.Vector3:
            return "vec3(" + this.value.x + ", " + this.value.y + ", " + this.value.z + ")";
        case NodeMaterialBlockConnectionPointTypes.Vector4:
            return "vec4(" + this.value.x + ", " + this.value.y + ", " + this.value.z + ", " + this.value.w + ")";
        case NodeMaterialBlockConnectionPointTypes.Color3:
            return TmpColors.Color3[0].set(this.value.r, this.value.g, this.value.b),
            this.convertToGammaSpace && TmpColors.Color3[0].toGammaSpaceToRef(TmpColors.Color3[0]),
            this.convertToLinearSpace && TmpColors.Color3[0].toLinearSpaceToRef(TmpColors.Color3[0]),
            "vec3(" + TmpColors.Color3[0].r + ", " + TmpColors.Color3[0].g + ", " + TmpColors.Color3[0].b + ")";
        case NodeMaterialBlockConnectionPointTypes.Color4:
            return TmpColors.Color4[0].set(this.value.r, this.value.g, this.value.b, this.value.a),
            this.convertToGammaSpace && TmpColors.Color4[0].toGammaSpaceToRef(TmpColors.Color4[0]),
            this.convertToLinearSpace && TmpColors.Color4[0].toLinearSpaceToRef(TmpColors.Color4[0]),
            "vec4(" + TmpColors.Color4[0].r + ", " + TmpColors.Color4[0].g + ", " + TmpColors.Color4[0].b + ", " + TmpColors.Color4[0].a + ")"
        }
        return ""
    }
    ,
    Object.defineProperty(e.prototype, "_noContextSwitch", {
        get: function() {
            return attributeInFragmentOnly[this.name]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._emit = function(t, r) {
        var n;
        if (this.isUniform) {
            if (this.associatedVariableName || (this.associatedVariableName = t._getFreeVariableName("u_" + this.name)),
            this.isConstant) {
                if (t.constants.indexOf(this.associatedVariableName) !== -1)
                    return;
                t.constants.push(this.associatedVariableName),
                t._constantDeclaration += this._declareOutput(this.output, t) + (" = " + this._emitConstant(t) + `;\r
`);
                return
            }
            if (t.uniforms.indexOf(this.associatedVariableName) !== -1)
                return;
            t.uniforms.push(this.associatedVariableName),
            r && (t._uniformDeclaration += this._emitDefine(r)),
            t._uniformDeclaration += "uniform " + t._getGLType(this.type) + " " + this.associatedVariableName + `;\r
`,
            r && (t._uniformDeclaration += `#endif\r
`);
            var o = t.sharedData.hints;
            if (this._systemValue !== null && this._systemValue !== void 0)
                switch (this._systemValue) {
                case NodeMaterialSystemValues.WorldView:
                    o.needWorldViewMatrix = !0;
                    break;
                case NodeMaterialSystemValues.WorldViewProjection:
                    o.needWorldViewProjectionMatrix = !0;
                    break
                }
            else
                this._animationType !== AnimatedInputBlockTypes.None && t.sharedData.animatedInputs.push(this);
            return
        }
        if (this.isAttribute) {
            if (this.associatedVariableName = (n = remapAttributeName[this.name]) !== null && n !== void 0 ? n : this.name,
            this.target === NodeMaterialBlockTargets.Vertex && t._vertexState) {
                attributeInFragmentOnly[this.name] ? attributeAsUniform[this.name] ? t._emitUniformFromString(this.associatedVariableName, t._getGLType(this.type), r) : t._emitVaryingFromString(this.associatedVariableName, t._getGLType(this.type), r) : this._emit(t._vertexState, r);
                return
            }
            if (t.attributes.indexOf(this.associatedVariableName) !== -1)
                return;
            t.attributes.push(this.associatedVariableName),
            attributeInFragmentOnly[this.name] ? attributeAsUniform[this.name] ? t._emitUniformFromString(this.associatedVariableName, t._getGLType(this.type), r) : t._emitVaryingFromString(this.associatedVariableName, t._getGLType(this.type), r) : (r && (t._attributeDeclaration += this._emitDefine(r)),
            t._attributeDeclaration += "attribute " + t._getGLType(this.type) + " " + this.associatedVariableName + `;\r
`,
            r && (t._attributeDeclaration += `#endif\r
`))
        }
    }
    ,
    e.prototype._transmitWorld = function(t, r, n, o) {
        if (!!this._systemValue) {
            var a = this.associatedVariableName;
            switch (this._systemValue) {
            case NodeMaterialSystemValues.World:
                t.setMatrix(a, r);
                break;
            case NodeMaterialSystemValues.WorldView:
                t.setMatrix(a, n);
                break;
            case NodeMaterialSystemValues.WorldViewProjection:
                t.setMatrix(a, o);
                break
            }
        }
    }
    ,
    e.prototype._transmit = function(t, r) {
        if (!this.isAttribute) {
            var n = this.associatedVariableName;
            if (this._systemValue) {
                switch (this._systemValue) {
                case NodeMaterialSystemValues.World:
                case NodeMaterialSystemValues.WorldView:
                case NodeMaterialSystemValues.WorldViewProjection:
                    return;
                case NodeMaterialSystemValues.View:
                    t.setMatrix(n, r.getViewMatrix());
                    break;
                case NodeMaterialSystemValues.Projection:
                    t.setMatrix(n, r.getProjectionMatrix());
                    break;
                case NodeMaterialSystemValues.ViewProjection:
                    t.setMatrix(n, r.getTransformMatrix());
                    break;
                case NodeMaterialSystemValues.CameraPosition:
                    r.bindEyePosition(t, n, !0);
                    break;
                case NodeMaterialSystemValues.FogColor:
                    t.setColor3(n, r.fogColor);
                    break;
                case NodeMaterialSystemValues.DeltaTime:
                    t.setFloat(n, r.deltaTime / 1e3);
                case NodeMaterialSystemValues.CameraParameters:
                    r.activeCamera && t.setFloat4(n, r.getEngine().hasOriginBottomLeft ? -1 : 1, r.activeCamera.minZ, r.activeCamera.maxZ, 1 / r.activeCamera.maxZ);
                    break
                }
                return
            }
            var o = this._valueCallback ? this._valueCallback() : this._storedValue;
            if (o !== null)
                switch (this.type) {
                case NodeMaterialBlockConnectionPointTypes.Float:
                    t.setFloat(n, o);
                    break;
                case NodeMaterialBlockConnectionPointTypes.Int:
                    t.setInt(n, o);
                    break;
                case NodeMaterialBlockConnectionPointTypes.Color3:
                    TmpColors.Color3[0].set(this.value.r, this.value.g, this.value.b),
                    this.convertToGammaSpace && TmpColors.Color3[0].toGammaSpaceToRef(TmpColors.Color3[0]),
                    this.convertToLinearSpace && TmpColors.Color3[0].toLinearSpaceToRef(TmpColors.Color3[0]),
                    t.setColor3(n, TmpColors.Color3[0]);
                    break;
                case NodeMaterialBlockConnectionPointTypes.Color4:
                    TmpColors.Color4[0].set(this.value.r, this.value.g, this.value.b, this.value.a),
                    this.convertToGammaSpace && TmpColors.Color4[0].toGammaSpaceToRef(TmpColors.Color4[0]),
                    this.convertToLinearSpace && TmpColors.Color4[0].toLinearSpaceToRef(TmpColors.Color4[0]),
                    t.setDirectColor4(n, TmpColors.Color4[0]);
                    break;
                case NodeMaterialBlockConnectionPointTypes.Vector2:
                    t.setVector2(n, o);
                    break;
                case NodeMaterialBlockConnectionPointTypes.Vector3:
                    t.setVector3(n, o);
                    break;
                case NodeMaterialBlockConnectionPointTypes.Vector4:
                    t.setVector4(n, o);
                    break;
                case NodeMaterialBlockConnectionPointTypes.Matrix:
                    t.setMatrix(n, o);
                    break
                }
        }
    }
    ,
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t),
        (this.isUniform || this.isSystemValue) && t.sharedData.inputBlocks.push(this),
        this._emit(t)
    }
    ,
    e.prototype._dumpPropertiesCode = function() {
        var t = this._codeVariableName;
        if (this.isAttribute)
            return i.prototype._dumpPropertiesCode.call(this) + (t + '.setAsAttribute("' + this.name + `");\r
`);
        if (this.isSystemValue)
            return i.prototype._dumpPropertiesCode.call(this) + (t + ".setAsSystemValue(BABYLON.NodeMaterialSystemValues." + NodeMaterialSystemValues[this._systemValue] + `);\r
`);
        if (this.isUniform) {
            var r = []
              , n = "";
            switch (this.type) {
            case NodeMaterialBlockConnectionPointTypes.Float:
                n = "" + this.value;
                break;
            case NodeMaterialBlockConnectionPointTypes.Vector2:
                n = "new BABYLON.Vector2(" + this.value.x + ", " + this.value.y + ")";
                break;
            case NodeMaterialBlockConnectionPointTypes.Vector3:
                n = "new BABYLON.Vector3(" + this.value.x + ", " + this.value.y + ", " + this.value.z + ")";
                break;
            case NodeMaterialBlockConnectionPointTypes.Vector4:
                n = "new BABYLON.Vector4(" + this.value.x + ", " + this.value.y + ", " + this.value.z + ", " + this.value.w + ")";
                break;
            case NodeMaterialBlockConnectionPointTypes.Color3:
                n = "new BABYLON.Color3(" + this.value.r + ", " + this.value.g + ", " + this.value.b + ")",
                this.convertToGammaSpace && (n += ".toGammaSpace()"),
                this.convertToLinearSpace && (n += ".toLinearSpace()");
                break;
            case NodeMaterialBlockConnectionPointTypes.Color4:
                n = "new BABYLON.Color4(" + this.value.r + ", " + this.value.g + ", " + this.value.b + ", " + this.value.a + ")",
                this.convertToGammaSpace && (n += ".toGammaSpace()"),
                this.convertToLinearSpace && (n += ".toLinearSpace()");
                break;
            case NodeMaterialBlockConnectionPointTypes.Matrix:
                n = "BABYLON.Matrix.FromArray([" + this.value.m + "])";
                break
            }
            return r.push(t + ".value = " + n),
            this.type === NodeMaterialBlockConnectionPointTypes.Float && r.push(t + ".min = " + this.min, t + ".max = " + this.max, t + ".isBoolean = " + this.isBoolean, t + ".matrixMode = " + this.matrixMode, t + ".animationType = BABYLON.AnimatedInputBlockTypes." + AnimatedInputBlockTypes[this.animationType]),
            r.push(t + ".isConstant = " + this.isConstant),
            r.push(""),
            i.prototype._dumpPropertiesCode.call(this) + r.join(`;\r
`)
        }
        return i.prototype._dumpPropertiesCode.call(this)
    }
    ,
    e.prototype.dispose = function() {
        this.onValueChangedObservable.clear(),
        i.prototype.dispose.call(this)
    }
    ,
    e.prototype.serialize = function() {
        var t = i.prototype.serialize.call(this);
        return t.type = this.type,
        t.mode = this._mode,
        t.systemValue = this._systemValue,
        t.animationType = this._animationType,
        t.min = this.min,
        t.max = this.max,
        t.isBoolean = this.isBoolean,
        t.matrixMode = this.matrixMode,
        t.isConstant = this.isConstant,
        t.groupInInspector = this.groupInInspector,
        t.convertToGammaSpace = this.convertToGammaSpace,
        t.convertToLinearSpace = this.convertToLinearSpace,
        this._storedValue != null && this._mode === NodeMaterialBlockConnectionPointMode.Uniform && (this._storedValue.asArray ? (t.valueType = "BABYLON." + this._storedValue.getClassName(),
        t.value = this._storedValue.asArray()) : (t.valueType = "number",
        t.value = this._storedValue)),
        t
    }
    ,
    e.prototype._deserialize = function(t, r, n) {
        if (this._mode = t.mode,
        i.prototype._deserialize.call(this, t, r, n),
        this._type = t.type,
        this._systemValue = t.systemValue || t.wellKnownValue,
        this._animationType = t.animationType,
        this.min = t.min || 0,
        this.max = t.max || 0,
        this.isBoolean = !!t.isBoolean,
        this.matrixMode = t.matrixMode || 0,
        this.isConstant = !!t.isConstant,
        this.groupInInspector = t.groupInInspector || "",
        this.convertToGammaSpace = !!t.convertToGammaSpace,
        this.convertToLinearSpace = !!t.convertToLinearSpace,
        !!t.valueType)
            if (t.valueType === "number")
                this._storedValue = t.value;
            else {
                var o = GetClass(t.valueType);
                o && (this._storedValue = o.FromArray(t.value))
            }
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.InputBlock", InputBlock);
var CurrentScreenBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.VertexAndFragment) || this;
        return r._samplerName = "textureSampler",
        r.convertToGammaSpace = !1,
        r.convertToLinearSpace = !1,
        r._isUnique = !1,
        r.registerInput("uv", NodeMaterialBlockConnectionPointTypes.Vector2, !1, NodeMaterialBlockTargets.VertexAndFragment),
        r.registerOutput("rgba", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Neutral),
        r.registerOutput("rgb", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Neutral),
        r.registerOutput("r", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral),
        r.registerOutput("g", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral),
        r.registerOutput("b", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral),
        r.registerOutput("a", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral),
        r._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector3),
        r._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector4),
        r._inputs[0]._prioritizeVertex = !1,
        r
    }
    return e.prototype.getClassName = function() {
        return "CurrentScreenBlock"
    }
    ,
    Object.defineProperty(e.prototype, "uv", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "rgba", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "rgb", {
        get: function() {
            return this._outputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "r", {
        get: function() {
            return this._outputs[2]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "g", {
        get: function() {
            return this._outputs[3]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "b", {
        get: function() {
            return this._outputs[4]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "a", {
        get: function() {
            return this._outputs[5]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.initialize = function(t) {
        t._excludeVariableName("textureSampler")
    }
    ,
    Object.defineProperty(e.prototype, "target", {
        get: function() {
            return !this.uv.isConnected || this.uv.sourceBlock.isInput ? NodeMaterialBlockTargets.VertexAndFragment : NodeMaterialBlockTargets.Fragment
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.prepareDefines = function(t, r, n) {
        n.setValue(this._linearDefineName, this.convertToGammaSpace, !0),
        n.setValue(this._gammaDefineName, this.convertToLinearSpace, !0)
    }
    ,
    e.prototype.isReady = function() {
        return !(this.texture && !this.texture.isReadyOrNotBlocking())
    }
    ,
    e.prototype._injectVertexCode = function(t) {
        var r = this.uv;
        if (r.connectedPoint.ownerBlock.isInput) {
            var n = r.connectedPoint.ownerBlock;
            n.isAttribute || t._emitUniformFromString(r.associatedVariableName, "vec2")
        }
        if (this._mainUVName = "vMain" + r.associatedVariableName,
        t._emitVaryingFromString(this._mainUVName, "vec2"),
        t.compilationString += this._mainUVName + " = " + r.associatedVariableName + `.xy;\r
`,
        !!this._outputs.some(function(l) {
            return l.isConnectedInVertexShader
        })) {
            this._writeTextureRead(t, !0);
            for (var o = 0, a = this._outputs; o < a.length; o++) {
                var s = a[o];
                s.hasEndpoints && this._writeOutput(t, s, s.name, !0)
            }
        }
    }
    ,
    e.prototype._writeTextureRead = function(t, r) {
        r === void 0 && (r = !1);
        var n = this.uv;
        if (r) {
            if (t.target === NodeMaterialBlockTargets.Fragment)
                return;
            t.compilationString += "vec4 " + this._tempTextureRead + " = texture2D(" + this._samplerName + ", " + n.associatedVariableName + `);\r
`;
            return
        }
        if (this.uv.ownerBlock.target === NodeMaterialBlockTargets.Fragment) {
            t.compilationString += "vec4 " + this._tempTextureRead + " = texture2D(" + this._samplerName + ", " + n.associatedVariableName + `);\r
`;
            return
        }
        t.compilationString += "vec4 " + this._tempTextureRead + " = texture2D(" + this._samplerName + ", " + this._mainUVName + `);\r
`
    }
    ,
    e.prototype._writeOutput = function(t, r, n, o) {
        if (o === void 0 && (o = !1),
        o) {
            if (t.target === NodeMaterialBlockTargets.Fragment)
                return;
            t.compilationString += this._declareOutput(r, t) + " = " + this._tempTextureRead + "." + n + `;\r
`;
            return
        }
        if (this.uv.ownerBlock.target === NodeMaterialBlockTargets.Fragment) {
            t.compilationString += this._declareOutput(r, t) + " = " + this._tempTextureRead + "." + n + `;\r
`;
            return
        }
        t.compilationString += this._declareOutput(r, t) + " = " + this._tempTextureRead + "." + n + `;\r
`,
        t.compilationString += "#ifdef " + this._linearDefineName + `\r
`,
        t.compilationString += r.associatedVariableName + " = toGammaSpace(" + r.associatedVariableName + `);\r
`,
        t.compilationString += `#endif\r
`,
        t.compilationString += "#ifdef " + this._gammaDefineName + `\r
`,
        t.compilationString += r.associatedVariableName + " = toLinearSpace(" + r.associatedVariableName + `);\r
`,
        t.compilationString += `#endif\r
`
    }
    ,
    e.prototype._buildBlock = function(t) {
        if (i.prototype._buildBlock.call(this, t),
        this._tempTextureRead = t._getFreeVariableName("tempTextureRead"),
        t.sharedData.blockingBlocks.indexOf(this) < 0 && t.sharedData.blockingBlocks.push(this),
        t.sharedData.textureBlocks.indexOf(this) < 0 && t.sharedData.textureBlocks.push(this),
        t.sharedData.blocksWithDefines.indexOf(this) < 0 && t.sharedData.blocksWithDefines.push(this),
        t.target !== NodeMaterialBlockTargets.Fragment) {
            t._emit2DSampler(this._samplerName),
            this._injectVertexCode(t);
            return
        }
        if (!!this._outputs.some(function(s) {
            return s.isConnectedInFragmentShader
        })) {
            t._emit2DSampler(this._samplerName),
            this._linearDefineName = t._getFreeDefineName("ISLINEAR"),
            this._gammaDefineName = t._getFreeDefineName("ISGAMMA");
            var r = "//" + this.name;
            t._emitFunctionFromInclude("helperFunctions", r),
            this._writeTextureRead(t);
            for (var n = 0, o = this._outputs; n < o.length; n++) {
                var a = o[n];
                a.hasEndpoints && this._writeOutput(t, a, a.name)
            }
            return this
        }
    }
    ,
    e.prototype.serialize = function() {
        var t = i.prototype.serialize.call(this);
        return t.convertToGammaSpace = this.convertToGammaSpace,
        t.convertToLinearSpace = this.convertToLinearSpace,
        this.texture && !this.texture.isRenderTarget && (t.texture = this.texture.serialize()),
        t
    }
    ,
    e.prototype._deserialize = function(t, r, n) {
        i.prototype._deserialize.call(this, t, r, n),
        this.convertToGammaSpace = t.convertToGammaSpace,
        this.convertToLinearSpace = !!t.convertToLinearSpace,
        t.texture && (n = t.texture.url.indexOf("data:") === 0 ? "" : n,
        this.texture = Texture.Parse(t.texture, r, n))
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.CurrentScreenBlock", CurrentScreenBlock);
var ParticleTextureBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Fragment) || this;
        return r._samplerName = "diffuseSampler",
        r.convertToGammaSpace = !1,
        r.convertToLinearSpace = !1,
        r._isUnique = !1,
        r.registerInput("uv", NodeMaterialBlockConnectionPointTypes.Vector2, !1, NodeMaterialBlockTargets.VertexAndFragment),
        r.registerOutput("rgba", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Neutral),
        r.registerOutput("rgb", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Neutral),
        r.registerOutput("r", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral),
        r.registerOutput("g", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral),
        r.registerOutput("b", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral),
        r.registerOutput("a", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral),
        r._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector3),
        r._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector4),
        r
    }
    return e.prototype.getClassName = function() {
        return "ParticleTextureBlock"
    }
    ,
    Object.defineProperty(e.prototype, "uv", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "rgba", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "rgb", {
        get: function() {
            return this._outputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "r", {
        get: function() {
            return this._outputs[2]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "g", {
        get: function() {
            return this._outputs[3]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "b", {
        get: function() {
            return this._outputs[4]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "a", {
        get: function() {
            return this._outputs[5]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.initialize = function(t) {
        t._excludeVariableName("diffuseSampler")
    }
    ,
    e.prototype.autoConfigure = function(t) {
        if (!this.uv.isConnected) {
            var r = t.getInputBlockByPredicate(function(n) {
                return n.isAttribute && n.name === "particle_uv"
            });
            r || (r = new InputBlock("uv"),
            r.setAsAttribute("particle_uv")),
            r.output.connectTo(this.uv)
        }
    }
    ,
    e.prototype.prepareDefines = function(t, r, n) {
        n.setValue(this._linearDefineName, this.convertToGammaSpace, !0),
        n.setValue(this._gammaDefineName, this.convertToLinearSpace, !0)
    }
    ,
    e.prototype.isReady = function() {
        return !(this.texture && !this.texture.isReadyOrNotBlocking())
    }
    ,
    e.prototype._writeOutput = function(t, r, n) {
        t.compilationString += this._declareOutput(r, t) + " = " + this._tempTextureRead + "." + n + `;\r
`,
        t.compilationString += "#ifdef " + this._linearDefineName + `\r
`,
        t.compilationString += r.associatedVariableName + " = toGammaSpace(" + r.associatedVariableName + `);\r
`,
        t.compilationString += `#endif\r
`,
        t.compilationString += "#ifdef " + this._gammaDefineName + `\r
`,
        t.compilationString += r.associatedVariableName + " = toLinearSpace(" + r.associatedVariableName + `);\r
`,
        t.compilationString += `#endif\r
`
    }
    ,
    e.prototype._buildBlock = function(t) {
        if (i.prototype._buildBlock.call(this, t),
        t.target !== NodeMaterialBlockTargets.Vertex) {
            this._tempTextureRead = t._getFreeVariableName("tempTextureRead"),
            t._emit2DSampler(this._samplerName),
            t.sharedData.blockingBlocks.push(this),
            t.sharedData.textureBlocks.push(this),
            t.sharedData.blocksWithDefines.push(this),
            this._linearDefineName = t._getFreeDefineName("ISLINEAR"),
            this._gammaDefineName = t._getFreeDefineName("ISGAMMA");
            var r = "//" + this.name;
            t._emitFunctionFromInclude("helperFunctions", r),
            t.compilationString += "vec4 " + this._tempTextureRead + " = texture2D(" + this._samplerName + ", " + this.uv.associatedVariableName + `);\r
`;
            for (var n = 0, o = this._outputs; n < o.length; n++) {
                var a = o[n];
                a.hasEndpoints && this._writeOutput(t, a, a.name)
            }
            return this
        }
    }
    ,
    e.prototype.serialize = function() {
        var t = i.prototype.serialize.call(this);
        return t.convertToGammaSpace = this.convertToGammaSpace,
        t.convertToLinearSpace = this.convertToLinearSpace,
        this.texture && !this.texture.isRenderTarget && (t.texture = this.texture.serialize()),
        t
    }
    ,
    e.prototype._deserialize = function(t, r, n) {
        i.prototype._deserialize.call(this, t, r, n),
        this.convertToGammaSpace = t.convertToGammaSpace,
        this.convertToLinearSpace = !!t.convertToLinearSpace,
        t.texture && (n = t.texture.url.indexOf("data:") === 0 ? "" : n,
        this.texture = Texture.Parse(t.texture, r, n))
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.ParticleTextureBlock", ParticleTextureBlock);
var ParticleRampGradientBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Fragment) || this;
        return r._isUnique = !0,
        r.registerInput("color", NodeMaterialBlockConnectionPointTypes.Color4, !1, NodeMaterialBlockTargets.Fragment),
        r.registerOutput("rampColor", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Fragment),
        r
    }
    return e.prototype.getClassName = function() {
        return "ParticleRampGradientBlock"
    }
    ,
    Object.defineProperty(e.prototype, "color", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "rampColor", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.initialize = function(t) {
        t._excludeVariableName("remapRanges"),
        t._excludeVariableName("rampSampler"),
        t._excludeVariableName("baseColor"),
        t._excludeVariableName("alpha"),
        t._excludeVariableName("remappedColorIndex"),
        t._excludeVariableName("rampColor"),
        t._excludeVariableName("finalAlpha")
    }
    ,
    e.prototype._buildBlock = function(t) {
        if (i.prototype._buildBlock.call(this, t),
        t.target !== NodeMaterialBlockTargets.Vertex)
            return t._emit2DSampler("rampSampler"),
            t._emitVaryingFromString("remapRanges", "vec4", "RAMPGRADIENT"),
            t.compilationString += `
            #ifdef RAMPGRADIENT
                vec4 baseColor = ` + this.color.associatedVariableName + `;
                float alpha = ` + this.color.associatedVariableName + `.a;

                float remappedColorIndex = clamp((alpha - remapRanges.x) / remapRanges.y, 0.0, 1.0);

                vec4 rampColor = texture2D(rampSampler, vec2(1.0 - remappedColorIndex, 0.));
                baseColor.rgb *= rampColor.rgb;

                // Remapped alpha
                float finalAlpha = baseColor.a;
                baseColor.a = clamp((alpha * rampColor.a - remapRanges.z) / remapRanges.w, 0.0, 1.0);

                ` + this._declareOutput(this.rampColor, t) + ` = baseColor;
            #else
                ` + this._declareOutput(this.rampColor, t) + " = " + this.color.associatedVariableName + `;
            #endif
        `,
            this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.ParticleRampGradientBlock", ParticleRampGradientBlock);
var ParticleBlendMultiplyBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Fragment) || this;
        return r._isUnique = !0,
        r.registerInput("color", NodeMaterialBlockConnectionPointTypes.Color4, !1, NodeMaterialBlockTargets.Fragment),
        r.registerInput("alphaTexture", NodeMaterialBlockConnectionPointTypes.Float, !1, NodeMaterialBlockTargets.Fragment),
        r.registerInput("alphaColor", NodeMaterialBlockConnectionPointTypes.Float, !1, NodeMaterialBlockTargets.Fragment),
        r.registerOutput("blendColor", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Fragment),
        r
    }
    return e.prototype.getClassName = function() {
        return "ParticleBlendMultiplyBlock"
    }
    ,
    Object.defineProperty(e.prototype, "color", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "alphaTexture", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "alphaColor", {
        get: function() {
            return this._inputs[2]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "blendColor", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.initialize = function(t) {
        t._excludeVariableName("sourceAlpha")
    }
    ,
    e.prototype._buildBlock = function(t) {
        if (i.prototype._buildBlock.call(this, t),
        t.target !== NodeMaterialBlockTargets.Vertex)
            return t.compilationString += `
            #ifdef BLENDMULTIPLYMODE
                ` + this._declareOutput(this.blendColor, t) + `;
                float sourceAlpha = ` + this.alphaColor.associatedVariableName + " * " + this.alphaTexture.associatedVariableName + `;
                ` + this.blendColor.associatedVariableName + ".rgb = " + this.color.associatedVariableName + `.rgb * sourceAlpha + vec3(1.0) * (1.0 - sourceAlpha);
                ` + this.blendColor.associatedVariableName + ".a = " + this.color.associatedVariableName + `.a;
            #else
                ` + this._declareOutput(this.blendColor, t) + " = " + this.color.associatedVariableName + `;
            #endif
        `,
            this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.ParticleBlendMultiplyBlock", ParticleBlendMultiplyBlock);
var VectorMergerBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Neutral) || this;
        return r.xSwizzle = "x",
        r.ySwizzle = "y",
        r.zSwizzle = "z",
        r.wSwizzle = "w",
        r.registerInput("xyzw ", NodeMaterialBlockConnectionPointTypes.Vector4, !0),
        r.registerInput("xyz ", NodeMaterialBlockConnectionPointTypes.Vector3, !0),
        r.registerInput("xy ", NodeMaterialBlockConnectionPointTypes.Vector2, !0),
        r.registerInput("zw ", NodeMaterialBlockConnectionPointTypes.Vector2, !0),
        r.registerInput("x", NodeMaterialBlockConnectionPointTypes.Float, !0),
        r.registerInput("y", NodeMaterialBlockConnectionPointTypes.Float, !0),
        r.registerInput("z", NodeMaterialBlockConnectionPointTypes.Float, !0),
        r.registerInput("w", NodeMaterialBlockConnectionPointTypes.Float, !0),
        r.registerOutput("xyzw", NodeMaterialBlockConnectionPointTypes.Vector4),
        r.registerOutput("xyz", NodeMaterialBlockConnectionPointTypes.Vector3),
        r.registerOutput("xy", NodeMaterialBlockConnectionPointTypes.Vector2),
        r.registerOutput("zw", NodeMaterialBlockConnectionPointTypes.Vector2),
        r
    }
    return e.prototype.getClassName = function() {
        return "VectorMergerBlock"
    }
    ,
    Object.defineProperty(e.prototype, "xyzwIn", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "xyzIn", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "xyIn", {
        get: function() {
            return this._inputs[2]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "zwIn", {
        get: function() {
            return this._inputs[3]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "x", {
        get: function() {
            return this._inputs[4]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "y", {
        get: function() {
            return this._inputs[5]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "z", {
        get: function() {
            return this._inputs[6]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "w", {
        get: function() {
            return this._inputs[7]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "xyzw", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "xyzOut", {
        get: function() {
            return this._outputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "xyOut", {
        get: function() {
            return this._outputs[2]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "zwOut", {
        get: function() {
            return this._outputs[3]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "xy", {
        get: function() {
            return this.xyOut
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "xyz", {
        get: function() {
            return this.xyzOut
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._inputRename = function(t) {
        return t === "xyzw " ? "xyzwIn" : t === "xyz " ? "xyzIn" : t === "xy " ? "xyIn" : t === "zw " ? "zwIn" : t
    }
    ,
    e.prototype._buildSwizzle = function(t) {
        var r = this.xSwizzle + this.ySwizzle + this.zSwizzle + this.wSwizzle;
        return "." + r.substr(0, t)
    }
    ,
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = this.x
          , n = this.y
          , o = this.z
          , a = this.w
          , s = this.xyIn
          , l = this.zwIn
          , u = this.xyzIn
          , c = this.xyzwIn
          , h = this._outputs[0]
          , f = this._outputs[1]
          , d = this._outputs[2]
          , _ = this._outputs[3];
        return c.isConnected ? (h.hasEndpoints && (t.compilationString += this._declareOutput(h, t) + (" = " + c.associatedVariableName + this._buildSwizzle(4) + `;\r
`)),
        f.hasEndpoints && (t.compilationString += this._declareOutput(f, t) + (" = " + c.associatedVariableName + this._buildSwizzle(3) + `;\r
`)),
        d.hasEndpoints && (t.compilationString += this._declareOutput(d, t) + (" = " + c.associatedVariableName + this._buildSwizzle(2) + `;\r
`))) : u.isConnected ? (h.hasEndpoints && (t.compilationString += this._declareOutput(h, t) + (" = vec4(" + u.associatedVariableName + ", " + (a.isConnected ? this._writeVariable(a) : "0.0") + ")" + this._buildSwizzle(4) + `;\r
`)),
        f.hasEndpoints && (t.compilationString += this._declareOutput(f, t) + (" = " + u.associatedVariableName + this._buildSwizzle(3) + `;\r
`)),
        d.hasEndpoints && (t.compilationString += this._declareOutput(d, t) + (" = " + u.associatedVariableName + this._buildSwizzle(2) + `;\r
`))) : s.isConnected ? (h.hasEndpoints && (l.isConnected ? t.compilationString += this._declareOutput(h, t) + (" = vec4(" + s.associatedVariableName + ", " + l.associatedVariableName + ")" + this._buildSwizzle(4) + `;\r
`) : t.compilationString += this._declareOutput(h, t) + (" = vec4(" + s.associatedVariableName + ", " + (o.isConnected ? this._writeVariable(o) : "0.0") + ", " + (a.isConnected ? this._writeVariable(a) : "0.0") + ")" + this._buildSwizzle(4) + `;\r
`)),
        f.hasEndpoints && (t.compilationString += this._declareOutput(f, t) + (" = vec3(" + s.associatedVariableName + ", " + (o.isConnected ? this._writeVariable(o) : "0.0") + ")" + this._buildSwizzle(3) + `;\r
`)),
        d.hasEndpoints && (t.compilationString += this._declareOutput(d, t) + (" = " + s.associatedVariableName + this._buildSwizzle(2) + `;\r
`)),
        _.hasEndpoints && (l.isConnected ? t.compilationString += this._declareOutput(_, t) + (" = " + l.associatedVariableName + this._buildSwizzle(2) + `;\r
`) : t.compilationString += this._declareOutput(_, t) + (" = vec2(" + (o.isConnected ? this._writeVariable(o) : "0.0") + ", " + (a.isConnected ? this._writeVariable(a) : "0.0") + ")" + this._buildSwizzle(2) + `;\r
`))) : (h.hasEndpoints && (l.isConnected ? t.compilationString += this._declareOutput(h, t) + (" = vec4(" + (r.isConnected ? this._writeVariable(r) : "0.0") + ", " + (n.isConnected ? this._writeVariable(n) : "0.0") + ", " + l.associatedVariableName + ")" + this._buildSwizzle(4) + `;\r
`) : t.compilationString += this._declareOutput(h, t) + (" = vec4(" + (r.isConnected ? this._writeVariable(r) : "0.0") + ", " + (n.isConnected ? this._writeVariable(n) : "0.0") + ", " + (o.isConnected ? this._writeVariable(o) : "0.0") + ", " + (a.isConnected ? this._writeVariable(a) : "0.0") + ")" + this._buildSwizzle(4) + `;\r
`)),
        f.hasEndpoints && (t.compilationString += this._declareOutput(f, t) + (" = vec3(" + (r.isConnected ? this._writeVariable(r) : "0.0") + ", " + (n.isConnected ? this._writeVariable(n) : "0.0") + ", " + (o.isConnected ? this._writeVariable(o) : "0.0") + ")" + this._buildSwizzle(3) + `;\r
`)),
        d.hasEndpoints && (t.compilationString += this._declareOutput(d, t) + (" = vec2(" + (r.isConnected ? this._writeVariable(r) : "0.0") + ", " + (n.isConnected ? this._writeVariable(n) : "0.0") + ")" + this._buildSwizzle(2) + `;\r
`)),
        _.hasEndpoints && (l.isConnected ? t.compilationString += this._declareOutput(_, t) + (" = " + l.associatedVariableName + this._buildSwizzle(2) + `;\r
`) : t.compilationString += this._declareOutput(_, t) + (" = vec2(" + (o.isConnected ? this._writeVariable(o) : "0.0") + ", " + (a.isConnected ? this._writeVariable(a) : "0.0") + ")" + this._buildSwizzle(2) + `;\r
`))),
        this
    }
    ,
    e.prototype.serialize = function() {
        var t = i.prototype.serialize.call(this);
        return t.xSwizzle = this.xSwizzle,
        t.ySwizzle = this.ySwizzle,
        t.zSwizzle = this.zSwizzle,
        t.wSwizzle = this.wSwizzle,
        t
    }
    ,
    e.prototype._deserialize = function(t, r, n) {
        var o, a, s, l;
        i.prototype._deserialize.call(this, t, r, n),
        this.xSwizzle = (o = t.xSwizzle) !== null && o !== void 0 ? o : "x",
        this.ySwizzle = (a = t.ySwizzle) !== null && a !== void 0 ? a : "y",
        this.zSwizzle = (s = t.zSwizzle) !== null && s !== void 0 ? s : "z",
        this.wSwizzle = (l = t.wSwizzle) !== null && l !== void 0 ? l : "w"
    }
    ,
    e.prototype._dumpPropertiesCode = function() {
        var t = i.prototype._dumpPropertiesCode.call(this);
        return t += this._codeVariableName + '.xSwizzle = "' + this.xSwizzle + `";\r
`,
        t += this._codeVariableName + '.ySwizzle = "' + this.ySwizzle + `";\r
`,
        t += this._codeVariableName + '.zSwizzle = "' + this.zSwizzle + `";\r
`,
        t += this._codeVariableName + '.wSwizzle = "' + this.wSwizzle + `";\r
`,
        t
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.VectorMergerBlock", VectorMergerBlock);
var RemapBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Neutral) || this;
        return r.sourceRange = new Vector2(-1,1),
        r.targetRange = new Vector2(0,1),
        r.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        r.registerInput("sourceMin", NodeMaterialBlockConnectionPointTypes.Float, !0),
        r.registerInput("sourceMax", NodeMaterialBlockConnectionPointTypes.Float, !0),
        r.registerInput("targetMin", NodeMaterialBlockConnectionPointTypes.Float, !0),
        r.registerInput("targetMax", NodeMaterialBlockConnectionPointTypes.Float, !0),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        r._outputs[0]._typeConnectionSource = r._inputs[0],
        r
    }
    return e.prototype.getClassName = function() {
        return "RemapBlock"
    }
    ,
    Object.defineProperty(e.prototype, "input", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "sourceMin", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "sourceMax", {
        get: function() {
            return this._inputs[2]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "targetMin", {
        get: function() {
            return this._inputs[3]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "targetMax", {
        get: function() {
            return this._inputs[4]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = this._outputs[0]
          , n = this.sourceMin.isConnected ? this.sourceMin.associatedVariableName : this._writeFloat(this.sourceRange.x)
          , o = this.sourceMax.isConnected ? this.sourceMax.associatedVariableName : this._writeFloat(this.sourceRange.y)
          , a = this.targetMin.isConnected ? this.targetMin.associatedVariableName : this._writeFloat(this.targetRange.x)
          , s = this.targetMax.isConnected ? this.targetMax.associatedVariableName : this._writeFloat(this.targetRange.y);
        return t.compilationString += this._declareOutput(r, t) + (" = " + a + " + (" + this._inputs[0].associatedVariableName + " - " + n + ") * (" + s + " - " + a + ") / (" + o + " - " + n + `);\r
`),
        this
    }
    ,
    e.prototype._dumpPropertiesCode = function() {
        var t = i.prototype._dumpPropertiesCode.call(this) + (this._codeVariableName + ".sourceRange = new BABYLON.Vector2(" + this.sourceRange.x + ", " + this.sourceRange.y + `);\r
`);
        return t += this._codeVariableName + ".targetRange = new BABYLON.Vector2(" + this.targetRange.x + ", " + this.targetRange.y + `);\r
`,
        t
    }
    ,
    e.prototype.serialize = function() {
        var t = i.prototype.serialize.call(this);
        return t.sourceRange = this.sourceRange.asArray(),
        t.targetRange = this.targetRange.asArray(),
        t
    }
    ,
    e.prototype._deserialize = function(t, r, n) {
        i.prototype._deserialize.call(this, t, r, n),
        this.sourceRange = Vector2.FromArray(t.sourceRange),
        this.targetRange = Vector2.FromArray(t.targetRange)
    }
    ,
    __decorate([editableInPropertyPage("From", PropertyTypeForEdition.Vector2)], e.prototype, "sourceRange", void 0),
    __decorate([editableInPropertyPage("To", PropertyTypeForEdition.Vector2)], e.prototype, "targetRange", void 0),
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.RemapBlock", RemapBlock);
var MultiplyBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Neutral) || this;
        return r.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        r.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        r._outputs[0]._typeConnectionSource = r._inputs[0],
        r._linkConnectionTypes(0, 1),
        r
    }
    return e.prototype.getClassName = function() {
        return "MultiplyBlock"
    }
    ,
    Object.defineProperty(e.prototype, "left", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "right", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = this._outputs[0];
        return t.compilationString += this._declareOutput(r, t) + (" = " + this.left.associatedVariableName + " * " + this.right.associatedVariableName + `;\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.MultiplyBlock", MultiplyBlock);
var ColorSplitterBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Neutral) || this;
        return r.registerInput("rgba", NodeMaterialBlockConnectionPointTypes.Color4, !0),
        r.registerInput("rgb ", NodeMaterialBlockConnectionPointTypes.Color3, !0),
        r.registerOutput("rgb", NodeMaterialBlockConnectionPointTypes.Color3),
        r.registerOutput("r", NodeMaterialBlockConnectionPointTypes.Float),
        r.registerOutput("g", NodeMaterialBlockConnectionPointTypes.Float),
        r.registerOutput("b", NodeMaterialBlockConnectionPointTypes.Float),
        r.registerOutput("a", NodeMaterialBlockConnectionPointTypes.Float),
        r.inputsAreExclusive = !0,
        r
    }
    return e.prototype.getClassName = function() {
        return "ColorSplitterBlock"
    }
    ,
    Object.defineProperty(e.prototype, "rgba", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "rgbIn", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "rgbOut", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "r", {
        get: function() {
            return this._outputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "g", {
        get: function() {
            return this._outputs[2]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "b", {
        get: function() {
            return this._outputs[3]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "a", {
        get: function() {
            return this._outputs[4]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._inputRename = function(t) {
        return t === "rgb " ? "rgbIn" : t
    }
    ,
    e.prototype._outputRename = function(t) {
        return t === "rgb" ? "rgbOut" : t
    }
    ,
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = this.rgba.isConnected ? this.rgba : this.rgbIn;
        if (!!r.isConnected) {
            var n = this._outputs[0]
              , o = this._outputs[1]
              , a = this._outputs[2]
              , s = this._outputs[3]
              , l = this._outputs[4];
            return n.hasEndpoints && (t.compilationString += this._declareOutput(n, t) + (" = " + r.associatedVariableName + `.rgb;\r
`)),
            o.hasEndpoints && (t.compilationString += this._declareOutput(o, t) + (" = " + r.associatedVariableName + `.r;\r
`)),
            a.hasEndpoints && (t.compilationString += this._declareOutput(a, t) + (" = " + r.associatedVariableName + `.g;\r
`)),
            s.hasEndpoints && (t.compilationString += this._declareOutput(s, t) + (" = " + r.associatedVariableName + `.b;\r
`)),
            l.hasEndpoints && (t.compilationString += this._declareOutput(l, t) + (" = " + r.associatedVariableName + `.a;\r
`)),
            this
        }
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.ColorSplitterBlock", ColorSplitterBlock);
var TrigonometryBlockOperations;
(function(i) {
    i[i.Cos = 0] = "Cos",
    i[i.Sin = 1] = "Sin",
    i[i.Abs = 2] = "Abs",
    i[i.Exp = 3] = "Exp",
    i[i.Exp2 = 4] = "Exp2",
    i[i.Round = 5] = "Round",
    i[i.Floor = 6] = "Floor",
    i[i.Ceiling = 7] = "Ceiling",
    i[i.Sqrt = 8] = "Sqrt",
    i[i.Log = 9] = "Log",
    i[i.Tan = 10] = "Tan",
    i[i.ArcTan = 11] = "ArcTan",
    i[i.ArcCos = 12] = "ArcCos",
    i[i.ArcSin = 13] = "ArcSin",
    i[i.Fract = 14] = "Fract",
    i[i.Sign = 15] = "Sign",
    i[i.Radians = 16] = "Radians",
    i[i.Degrees = 17] = "Degrees"
}
)(TrigonometryBlockOperations || (TrigonometryBlockOperations = {}));
var TrigonometryBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Neutral) || this;
        return r.operation = TrigonometryBlockOperations.Cos,
        r.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        r._outputs[0]._typeConnectionSource = r._inputs[0],
        r
    }
    return e.prototype.getClassName = function() {
        return "TrigonometryBlock"
    }
    ,
    Object.defineProperty(e.prototype, "input", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = this._outputs[0]
          , n = "";
        switch (this.operation) {
        case TrigonometryBlockOperations.Cos:
            {
                n = "cos";
                break
            }
        case TrigonometryBlockOperations.Sin:
            {
                n = "sin";
                break
            }
        case TrigonometryBlockOperations.Abs:
            {
                n = "abs";
                break
            }
        case TrigonometryBlockOperations.Exp:
            {
                n = "exp";
                break
            }
        case TrigonometryBlockOperations.Exp2:
            {
                n = "exp2";
                break
            }
        case TrigonometryBlockOperations.Round:
            {
                n = "round";
                break
            }
        case TrigonometryBlockOperations.Floor:
            {
                n = "floor";
                break
            }
        case TrigonometryBlockOperations.Ceiling:
            {
                n = "ceil";
                break
            }
        case TrigonometryBlockOperations.Sqrt:
            {
                n = "sqrt";
                break
            }
        case TrigonometryBlockOperations.Log:
            {
                n = "log";
                break
            }
        case TrigonometryBlockOperations.Tan:
            {
                n = "tan";
                break
            }
        case TrigonometryBlockOperations.ArcTan:
            {
                n = "atan";
                break
            }
        case TrigonometryBlockOperations.ArcCos:
            {
                n = "acos";
                break
            }
        case TrigonometryBlockOperations.ArcSin:
            {
                n = "asin";
                break
            }
        case TrigonometryBlockOperations.Fract:
            {
                n = "fract";
                break
            }
        case TrigonometryBlockOperations.Sign:
            {
                n = "sign";
                break
            }
        case TrigonometryBlockOperations.Radians:
            {
                n = "radians";
                break
            }
        case TrigonometryBlockOperations.Degrees:
            {
                n = "degrees";
                break
            }
        }
        return t.compilationString += this._declareOutput(r, t) + (" = " + n + "(" + this.input.associatedVariableName + `);\r
`),
        this
    }
    ,
    e.prototype.serialize = function() {
        var t = i.prototype.serialize.call(this);
        return t.operation = this.operation,
        t
    }
    ,
    e.prototype._deserialize = function(t, r, n) {
        i.prototype._deserialize.call(this, t, r, n),
        this.operation = t.operation
    }
    ,
    e.prototype._dumpPropertiesCode = function() {
        var t = i.prototype._dumpPropertiesCode.call(this) + (this._codeVariableName + ".operation = BABYLON.TrigonometryBlockOperations." + TrigonometryBlockOperations[this.operation] + `;\r
`);
        return t
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.TrigonometryBlock", TrigonometryBlock);
var onCreatedEffectParameters$1 = {
    effect: null,
    subMesh: null
}
  , NodeMaterialDefines = function(i) {
    __extends(e, i);
    function e() {
        var t = i.call(this) || this;
        return t.NORMAL = !1,
        t.TANGENT = !1,
        t.UV1 = !1,
        t.UV2 = !1,
        t.UV3 = !1,
        t.UV4 = !1,
        t.UV5 = !1,
        t.UV6 = !1,
        t.NUM_BONE_INFLUENCERS = 0,
        t.BonesPerMesh = 0,
        t.BONETEXTURE = !1,
        t.MORPHTARGETS = !1,
        t.MORPHTARGETS_NORMAL = !1,
        t.MORPHTARGETS_TANGENT = !1,
        t.MORPHTARGETS_UV = !1,
        t.NUM_MORPH_INFLUENCERS = 0,
        t.MORPHTARGETS_TEXTURE = !1,
        t.IMAGEPROCESSING = !1,
        t.VIGNETTE = !1,
        t.VIGNETTEBLENDMODEMULTIPLY = !1,
        t.VIGNETTEBLENDMODEOPAQUE = !1,
        t.TONEMAPPING = !1,
        t.TONEMAPPING_ACES = !1,
        t.CONTRAST = !1,
        t.EXPOSURE = !1,
        t.COLORCURVES = !1,
        t.COLORGRADING = !1,
        t.COLORGRADING3D = !1,
        t.SAMPLER3DGREENDEPTH = !1,
        t.SAMPLER3DBGRMAP = !1,
        t.IMAGEPROCESSINGPOSTPROCESS = !1,
        t.SKIPFINALCOLORCLAMP = !1,
        t.BUMPDIRECTUV = 0,
        t.rebuild(),
        t
    }
    return e.prototype.setValue = function(t, r, n) {
        n === void 0 && (n = !1),
        this[t] === void 0 && this._keys.push(t),
        n && this[t] !== r && this.markAsUnprocessed(),
        this[t] = r
    }
    ,
    e
}(MaterialDefines)
  , NodeMaterial = function(i) {
    __extends(e, i);
    function e(t, r, n) {
        n === void 0 && (n = {});
        var o = i.call(this, t, r || Engine.LastCreatedScene) || this;
        return o._buildId = e._BuildIdGenerator++,
        o._buildWasSuccessful = !1,
        o._cachedWorldViewMatrix = new Matrix,
        o._cachedWorldViewProjectionMatrix = new Matrix,
        o._optimizers = new Array,
        o._animationFrame = -1,
        o.BJSNODEMATERIALEDITOR = o._getGlobalNodeMaterialEditor(),
        o.editorData = null,
        o.ignoreAlpha = !1,
        o.maxSimultaneousLights = 4,
        o.onBuildObservable = new Observable,
        o._vertexOutputNodes = new Array,
        o._fragmentOutputNodes = new Array,
        o.attachedBlocks = new Array,
        o._mode = NodeMaterialModes.Material,
        o._options = __assign({
            emitComments: !1
        }, n),
        o._attachImageProcessingConfiguration(null),
        o
    }
    return e.prototype._getGlobalNodeMaterialEditor = function() {
        if (typeof NODEEDITOR != "undefined")
            return NODEEDITOR;
        if (typeof BABYLON != "undefined" && typeof BABYLON.NodeEditor != "undefined")
            return BABYLON
    }
    ,
    Object.defineProperty(e.prototype, "options", {
        get: function() {
            return this._options
        },
        set: function(t) {
            this._options = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "imageProcessingConfiguration", {
        get: function() {
            return this._imageProcessingConfiguration
        },
        set: function(t) {
            this._attachImageProcessingConfiguration(t),
            this._markAllSubMeshesAsTexturesDirty()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "mode", {
        get: function() {
            return this._mode
        },
        set: function(t) {
            this._mode = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "buildId", {
        get: function() {
            return this._buildId
        },
        set: function(t) {
            this._buildId = t
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getClassName = function() {
        return "NodeMaterial"
    }
    ,
    e.prototype._attachImageProcessingConfiguration = function(t) {
        var r = this;
        t !== this._imageProcessingConfiguration && (this._imageProcessingConfiguration && this._imageProcessingObserver && this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),
        t ? this._imageProcessingConfiguration = t : this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration,
        this._imageProcessingConfiguration && (this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function() {
            r._markAllSubMeshesAsImageProcessingDirty()
        })))
    }
    ,
    e.prototype.getBlockByName = function(t) {
        for (var r = null, n = 0, o = this.attachedBlocks; n < o.length; n++) {
            var a = o[n];
            if (a.name === t)
                if (!r)
                    r = a;
                else
                    return Tools.Warn("More than one block was found with the name `" + t + "`"),
                    r
        }
        return r
    }
    ,
    e.prototype.getBlockByPredicate = function(t) {
        for (var r = 0, n = this.attachedBlocks; r < n.length; r++) {
            var o = n[r];
            if (t(o))
                return o
        }
        return null
    }
    ,
    e.prototype.getInputBlockByPredicate = function(t) {
        for (var r = 0, n = this.attachedBlocks; r < n.length; r++) {
            var o = n[r];
            if (o.isInput && t(o))
                return o
        }
        return null
    }
    ,
    e.prototype.getInputBlocks = function() {
        for (var t = [], r = 0, n = this.attachedBlocks; r < n.length; r++) {
            var o = n[r];
            o.isInput && t.push(o)
        }
        return t
    }
    ,
    e.prototype.registerOptimizer = function(t) {
        var r = this._optimizers.indexOf(t);
        if (!(r > -1))
            return this._optimizers.push(t),
            this
    }
    ,
    e.prototype.unregisterOptimizer = function(t) {
        var r = this._optimizers.indexOf(t);
        if (r !== -1)
            return this._optimizers.splice(r, 1),
            this
    }
    ,
    e.prototype.addOutputNode = function(t) {
        if (t.target === null)
            throw "This node is not meant to be an output node. You may want to explicitly set its target value.";
        return (t.target & NodeMaterialBlockTargets.Vertex) !== 0 && this._addVertexOutputNode(t),
        (t.target & NodeMaterialBlockTargets.Fragment) !== 0 && this._addFragmentOutputNode(t),
        this
    }
    ,
    e.prototype.removeOutputNode = function(t) {
        return t.target === null ? this : ((t.target & NodeMaterialBlockTargets.Vertex) !== 0 && this._removeVertexOutputNode(t),
        (t.target & NodeMaterialBlockTargets.Fragment) !== 0 && this._removeFragmentOutputNode(t),
        this)
    }
    ,
    e.prototype._addVertexOutputNode = function(t) {
        if (this._vertexOutputNodes.indexOf(t) === -1)
            return t.target = NodeMaterialBlockTargets.Vertex,
            this._vertexOutputNodes.push(t),
            this
    }
    ,
    e.prototype._removeVertexOutputNode = function(t) {
        var r = this._vertexOutputNodes.indexOf(t);
        if (r !== -1)
            return this._vertexOutputNodes.splice(r, 1),
            this
    }
    ,
    e.prototype._addFragmentOutputNode = function(t) {
        if (this._fragmentOutputNodes.indexOf(t) === -1)
            return t.target = NodeMaterialBlockTargets.Fragment,
            this._fragmentOutputNodes.push(t),
            this
    }
    ,
    e.prototype._removeFragmentOutputNode = function(t) {
        var r = this._fragmentOutputNodes.indexOf(t);
        if (r !== -1)
            return this._fragmentOutputNodes.splice(r, 1),
            this
    }
    ,
    e.prototype.needAlphaBlending = function() {
        return this.ignoreAlpha ? !1 : this.alpha < 1 || this._sharedData && this._sharedData.hints.needAlphaBlending
    }
    ,
    e.prototype.needAlphaTesting = function() {
        return this._sharedData && this._sharedData.hints.needAlphaTesting
    }
    ,
    e.prototype._initializeBlock = function(t, r, n, o) {
        if (o === void 0 && (o = !0),
        t.initialize(r),
        o && t.autoConfigure(this),
        t._preparationId = this._buildId,
        this.attachedBlocks.indexOf(t) === -1) {
            if (t.isUnique)
                for (var a = t.getClassName(), s = 0, l = this.attachedBlocks; s < l.length; s++) {
                    var u = l[s];
                    if (u.getClassName() === a)
                        throw "Cannot have multiple blocks of type " + a + " in the same NodeMaterial"
                }
            this.attachedBlocks.push(t)
        }
        for (var c = 0, h = t.inputs; c < h.length; c++) {
            var f = h[c];
            f.associatedVariableName = "";
            var d = f.connectedPoint;
            if (d) {
                var _ = d.ownerBlock;
                _ !== t && ((_.target === NodeMaterialBlockTargets.VertexAndFragment || r.target === NodeMaterialBlockTargets.Fragment && _.target === NodeMaterialBlockTargets.Vertex && _._preparationId !== this._buildId) && n.push(_),
                this._initializeBlock(_, r, n, o))
            }
        }
        for (var g = 0, m = t.outputs; g < m.length; g++) {
            var v = m[g];
            v.associatedVariableName = ""
        }
    }
    ,
    e.prototype._resetDualBlocks = function(t, r) {
        t.target === NodeMaterialBlockTargets.VertexAndFragment && (t.buildId = r);
        for (var n = 0, o = t.inputs; n < o.length; n++) {
            var a = o[n]
              , s = a.connectedPoint;
            if (s) {
                var l = s.ownerBlock;
                l !== t && this._resetDualBlocks(l, r)
            }
        }
    }
    ,
    e.prototype.removeBlock = function(t) {
        var r = this.attachedBlocks.indexOf(t);
        r > -1 && this.attachedBlocks.splice(r, 1),
        t.isFinalMerger && this.removeOutputNode(t)
    }
    ,
    e.prototype.build = function(t, r, n) {
        t === void 0 && (t = !1),
        r === void 0 && (r = !0),
        n === void 0 && (n = !0),
        this._buildWasSuccessful = !1;
        var o = this.getScene().getEngine()
          , a = this._mode === NodeMaterialModes.Particle;
        if (this._vertexOutputNodes.length === 0 && !a)
            throw "You must define at least one vertexOutputNode";
        if (this._fragmentOutputNodes.length === 0)
            throw "You must define at least one fragmentOutputNode";
        this._vertexCompilationState = new NodeMaterialBuildState,
        this._vertexCompilationState.supportUniformBuffers = o.supportsUniformBuffers,
        this._vertexCompilationState.target = NodeMaterialBlockTargets.Vertex,
        this._fragmentCompilationState = new NodeMaterialBuildState,
        this._fragmentCompilationState.supportUniformBuffers = o.supportsUniformBuffers,
        this._fragmentCompilationState.target = NodeMaterialBlockTargets.Fragment,
        this._sharedData = new NodeMaterialBuildStateSharedData,
        this._sharedData.fragmentOutputNodes = this._fragmentOutputNodes,
        this._vertexCompilationState.sharedData = this._sharedData,
        this._fragmentCompilationState.sharedData = this._sharedData,
        this._sharedData.buildId = this._buildId,
        this._sharedData.emitComments = this._options.emitComments,
        this._sharedData.verbose = t,
        this._sharedData.scene = this.getScene(),
        this._sharedData.allowEmptyVertexProgram = a;
        for (var s = [], l = [], u = 0, c = this._vertexOutputNodes; u < c.length; u++) {
            var h = c[u];
            s.push(h),
            this._initializeBlock(h, this._vertexCompilationState, l, n)
        }
        for (var f = 0, d = this._fragmentOutputNodes; f < d.length; f++) {
            var _ = d[f];
            l.push(_),
            this._initializeBlock(_, this._fragmentCompilationState, s, n)
        }
        this.optimize();
        for (var g = 0, m = s; g < m.length; g++) {
            var h = m[g];
            h.build(this._vertexCompilationState, s)
        }
        this._fragmentCompilationState.uniforms = this._vertexCompilationState.uniforms.slice(0),
        this._fragmentCompilationState._uniformDeclaration = this._vertexCompilationState._uniformDeclaration,
        this._fragmentCompilationState._constantDeclaration = this._vertexCompilationState._constantDeclaration,
        this._fragmentCompilationState._vertexState = this._vertexCompilationState;
        for (var v = 0, y = l; v < y.length; v++) {
            var _ = y[v];
            this._resetDualBlocks(_, this._buildId - 1)
        }
        for (var b = 0, T = l; b < T.length; b++) {
            var _ = T[b];
            _.build(this._fragmentCompilationState, l)
        }
        this._vertexCompilationState.finalize(this._vertexCompilationState),
        this._fragmentCompilationState.finalize(this._fragmentCompilationState),
        r && (this._buildId = e._BuildIdGenerator++),
        this._sharedData.emitErrors(),
        t && (console.log("Vertex shader:"),
        console.log(this._vertexCompilationState.compilationString),
        console.log("Fragment shader:"),
        console.log(this._fragmentCompilationState.compilationString)),
        this._buildWasSuccessful = !0,
        this.onBuildObservable.notifyObservers(this);
        for (var C = this.getScene().meshes, A = 0, S = C; A < S.length; A++) {
            var P = S[A];
            if (!!P.subMeshes)
                for (var R = 0, M = P.subMeshes; R < M.length; R++) {
                    var x = M[R];
                    if (x.getMaterial() === this && !!x.materialDefines) {
                        var I = x.materialDefines;
                        I.markAllAsDirty(),
                        I.reset()
                    }
                }
        }
    }
    ,
    e.prototype.optimize = function() {
        for (var t = 0, r = this._optimizers; t < r.length; t++) {
            var n = r[t];
            n.optimize(this._vertexOutputNodes, this._fragmentOutputNodes)
        }
    }
    ,
    e.prototype._prepareDefinesForAttributes = function(t, r) {
        var n = r.NORMAL
          , o = r.TANGENT;
        r.NORMAL = t.isVerticesDataPresent(VertexBuffer.NormalKind),
        r.TANGENT = t.isVerticesDataPresent(VertexBuffer.TangentKind);
        for (var a = !1, s = 1; s <= 6; ++s) {
            var l = r["UV" + s];
            r["UV" + s] = t.isVerticesDataPresent("uv" + (s === 1 ? "" : s)),
            a = a || r["UV" + s] !== l
        }
        (n !== r.NORMAL || o !== r.TANGENT || a) && r.markAsAttributesDirty()
    }
    ,
    e.prototype.createPostProcess = function(t, r, n, o, a, s, l) {
        return r === void 0 && (r = 1),
        n === void 0 && (n = 1),
        s === void 0 && (s = 0),
        l === void 0 && (l = 5),
        this.mode !== NodeMaterialModes.PostProcess ? (console.log("Incompatible material mode"),
        null) : this._createEffectForPostProcess(null, t, r, n, o, a, s, l)
    }
    ,
    e.prototype.createEffectForPostProcess = function(t) {
        this._createEffectForPostProcess(t)
    }
    ,
    e.prototype._createEffectForPostProcess = function(t, r, n, o, a, s, l, u) {
        var c = this;
        n === void 0 && (n = 1),
        o === void 0 && (o = 1),
        l === void 0 && (l = 0),
        u === void 0 && (u = 5);
        var h = this.name + this._buildId
          , f = new NodeMaterialDefines
          , d = new AbstractMesh(h + "PostProcess",this.getScene())
          , _ = this._buildId;
        return this._processDefines(d, f),
        Effect.RegisterShader(h, this._fragmentCompilationState._builtCompilationString, this._vertexCompilationState._builtCompilationString),
        t ? t.updateEffect(f.toString(), this._fragmentCompilationState.uniforms, this._fragmentCompilationState.samplers, {
            maxSimultaneousLights: this.maxSimultaneousLights
        }, void 0, void 0, h, h) : t = new PostProcess(this.name + "PostProcess",h,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n,r,o,a,s,f.toString(),l,h,{
            maxSimultaneousLights: this.maxSimultaneousLights
        },!1,u),
        t.nodeMaterialSource = this,
        t.onApplyObservable.add(function(g) {
            _ !== c._buildId && (delete Effect.ShadersStore[h + "VertexShader"],
            delete Effect.ShadersStore[h + "PixelShader"],
            h = c.name + c._buildId,
            f.markAllAsDirty(),
            _ = c._buildId);
            var m = c._processDefines(d, f);
            m && (Effect.RegisterShader(h, c._fragmentCompilationState._builtCompilationString, c._vertexCompilationState._builtCompilationString),
            TimingTools.SetImmediate(function() {
                return t.updateEffect(f.toString(), c._fragmentCompilationState.uniforms, c._fragmentCompilationState.samplers, {
                    maxSimultaneousLights: c.maxSimultaneousLights
                }, void 0, void 0, h, h)
            })),
            c._checkInternals(g)
        }),
        t
    }
    ,
    e.prototype.createProceduralTexture = function(t, r) {
        var n = this;
        if (this.mode !== NodeMaterialModes.ProceduralTexture)
            return console.log("Incompatible material mode"),
            null;
        var o = this.name + this._buildId
          , a = new ProceduralTexture(o,t,null,r)
          , s = new AbstractMesh(o + "Procedural",this.getScene());
        s.reservedDataStore = {
            hidden: !0
        };
        var l = new NodeMaterialDefines
          , u = this._processDefines(s, l);
        Effect.RegisterShader(o, this._fragmentCompilationState._builtCompilationString, this._vertexCompilationState._builtCompilationString);
        var c = this.getScene().getEngine().createEffect({
            vertexElement: o,
            fragmentElement: o
        }, [VertexBuffer.PositionKind], this._fragmentCompilationState.uniforms, this._fragmentCompilationState.samplers, l.toString(), u == null ? void 0 : u.fallbacks, void 0);
        a.nodeMaterialSource = this,
        a._setEffect(c);
        var h = this._buildId;
        return a.onBeforeGenerationObservable.add(function() {
            h !== n._buildId && (delete Effect.ShadersStore[o + "VertexShader"],
            delete Effect.ShadersStore[o + "PixelShader"],
            o = n.name + n._buildId,
            l.markAllAsDirty(),
            h = n._buildId);
            var f = n._processDefines(s, l);
            f && (Effect.RegisterShader(o, n._fragmentCompilationState._builtCompilationString, n._vertexCompilationState._builtCompilationString),
            TimingTools.SetImmediate(function() {
                c = n.getScene().getEngine().createEffect({
                    vertexElement: o,
                    fragmentElement: o
                }, [VertexBuffer.PositionKind], n._fragmentCompilationState.uniforms, n._fragmentCompilationState.samplers, l.toString(), f == null ? void 0 : f.fallbacks, void 0),
                a._setEffect(c)
            })),
            n._checkInternals(c)
        }),
        a
    }
    ,
    e.prototype._createEffectForParticles = function(t, r, n, o, a, s, l, u) {
        var c = this;
        u === void 0 && (u = "");
        var h = this.name + this._buildId + "_" + r;
        s || (s = new NodeMaterialDefines),
        l || (l = this.getScene().getMeshByName(this.name + "Particle"),
        l || (l = new AbstractMesh(this.name + "Particle",this.getScene()),
        l.reservedDataStore = {
            hidden: !0
        }));
        var f = this._buildId
          , d = []
          , _ = u;
        if (!a) {
            var g = this._processDefines(l, s);
            Effect.RegisterShader(h, this._fragmentCompilationState._builtCompilationString),
            t.fillDefines(d, r),
            _ = d.join(`
`),
            a = this.getScene().getEngine().createEffectForParticles(h, this._fragmentCompilationState.uniforms, this._fragmentCompilationState.samplers, s.toString() + `
` + _, g == null ? void 0 : g.fallbacks, n, o, t),
            t.setCustomEffect(a, r)
        }
        a.onBindObservable.add(function(m) {
            f !== c._buildId && (delete Effect.ShadersStore[h + "PixelShader"],
            h = c.name + c._buildId + "_" + r,
            s.markAllAsDirty(),
            f = c._buildId),
            d.length = 0,
            t.fillDefines(d, r);
            var v = d.join(`
`);
            v !== _ && (s.markAllAsDirty(),
            _ = v);
            var y = c._processDefines(l, s);
            if (y) {
                Effect.RegisterShader(h, c._fragmentCompilationState._builtCompilationString),
                m = c.getScene().getEngine().createEffectForParticles(h, c._fragmentCompilationState.uniforms, c._fragmentCompilationState.samplers, s.toString() + `
` + _, y == null ? void 0 : y.fallbacks, n, o, t),
                t.setCustomEffect(m, r),
                c._createEffectForParticles(t, r, n, o, m, s, l, _);
                return
            }
            c._checkInternals(m)
        })
    }
    ,
    e.prototype._checkInternals = function(t) {
        if (this._sharedData.animatedInputs) {
            var r = this.getScene()
              , n = r.getFrameId();
            if (this._animationFrame !== n) {
                for (var o = 0, a = this._sharedData.animatedInputs; o < a.length; o++) {
                    var s = a[o];
                    s.animate(r)
                }
                this._animationFrame = n
            }
        }
        for (var l = 0, u = this._sharedData.bindableBlocks; l < u.length; l++) {
            var c = u[l];
            c.bind(t, this)
        }
        for (var h = 0, f = this._sharedData.inputBlocks; h < f.length; h++) {
            var d = f[h];
            d._transmit(t, this.getScene())
        }
    }
    ,
    e.prototype.createEffectForParticles = function(t, r, n) {
        if (this.mode !== NodeMaterialModes.Particle) {
            console.log("Incompatible material mode");
            return
        }
        this._createEffectForParticles(t, BaseParticleSystem.BLENDMODE_ONEONE, r, n),
        this._createEffectForParticles(t, BaseParticleSystem.BLENDMODE_MULTIPLY, r, n)
    }
    ,
    e.prototype._processDefines = function(t, r, n, o) {
        var a = this;
        n === void 0 && (n = !1);
        var s = null;
        if (this._sharedData.blocksWithDefines.forEach(function(d) {
            d.initializeDefines(t, a, r, n)
        }),
        this._sharedData.blocksWithDefines.forEach(function(d) {
            d.prepareDefines(t, a, r, n, o)
        }),
        r.isDirty) {
            var l = r._areLightsDisposed;
            r.markAsProcessed(),
            this._vertexCompilationState.compilationString = this._vertexCompilationState._builtCompilationString,
            this._fragmentCompilationState.compilationString = this._fragmentCompilationState._builtCompilationString,
            this._sharedData.repeatableContentBlocks.forEach(function(d) {
                d.replaceRepeatableContent(a._vertexCompilationState, a._fragmentCompilationState, t, r)
            });
            var u = [];
            this._sharedData.dynamicUniformBlocks.forEach(function(d) {
                d.updateUniformsAndSamples(a._vertexCompilationState, a, r, u)
            });
            var c = this._vertexCompilationState.uniforms;
            this._fragmentCompilationState.uniforms.forEach(function(d) {
                var _ = c.indexOf(d);
                _ === -1 && c.push(d)
            });
            var h = this._vertexCompilationState.samplers;
            this._fragmentCompilationState.samplers.forEach(function(d) {
                var _ = h.indexOf(d);
                _ === -1 && h.push(d)
            });
            var f = new EffectFallbacks;
            this._sharedData.blocksWithFallbacks.forEach(function(d) {
                d.provideFallbacks(t, f)
            }),
            s = {
                lightDisposed: l,
                uniformBuffers: u,
                mergedUniforms: c,
                mergedSamplers: h,
                fallbacks: f
            }
        }
        return s
    }
    ,
    e.prototype.isReadyForSubMesh = function(t, r, n) {
        var o = this;
        if (n === void 0 && (n = !1),
        !this._buildWasSuccessful)
            return !1;
        var a = this.getScene();
        if (this._sharedData.animatedInputs) {
            var s = a.getFrameId();
            if (this._animationFrame !== s) {
                for (var l = 0, u = this._sharedData.animatedInputs; l < u.length; l++) {
                    var c = u[l];
                    c.animate(a)
                }
                this._animationFrame = s
            }
        }
        if (r.effect && this.isFrozen && r.effect._wasPreviouslyReady)
            return !0;
        r.materialDefines || (r.materialDefines = new NodeMaterialDefines);
        var h = r.materialDefines;
        if (this._isReadyForSubMesh(r))
            return !0;
        var f = a.getEngine();
        if (this._prepareDefinesForAttributes(t, h),
        this._sharedData.blockingBlocks.some(function(v) {
            return !v.isReady(t, o, h, n)
        }))
            return !1;
        var d = this._processDefines(t, h, n, r);
        if (d) {
            var _ = r.effect
              , g = h.toString()
              , m = f.createEffect({
                vertex: "nodeMaterial" + this._buildId,
                fragment: "nodeMaterial" + this._buildId,
                vertexSource: this._vertexCompilationState.compilationString,
                fragmentSource: this._fragmentCompilationState.compilationString
            }, {
                attributes: this._vertexCompilationState.attributes,
                uniformsNames: d.mergedUniforms,
                uniformBuffersNames: d.uniformBuffers,
                samplers: d.mergedSamplers,
                defines: g,
                fallbacks: d.fallbacks,
                onCompiled: this.onCompiled,
                onError: this.onError,
                indexParameters: {
                    maxSimultaneousLights: this.maxSimultaneousLights,
                    maxSimultaneousMorphTargets: h.NUM_MORPH_INFLUENCERS
                }
            }, f);
            if (m)
                if (this._onEffectCreatedObservable && (onCreatedEffectParameters$1.effect = m,
                onCreatedEffectParameters$1.subMesh = r,
                this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters$1)),
                this.allowShaderHotSwapping && _ && !m.isReady()) {
                    if (m = _,
                    h.markAsUnprocessed(),
                    d.lightDisposed)
                        return h._areLightsDisposed = !0,
                        !1
                } else
                    a.resetCachedMaterial(),
                    r.setEffect(m, h, this._materialContext)
        }
        return !r.effect || !r.effect.isReady() ? !1 : (h._renderId = a.getRenderId(),
        r.effect._wasPreviouslyReady = !0,
        !0)
    }
    ,
    Object.defineProperty(e.prototype, "compiledShaders", {
        get: function() {
            return `// Vertex shader\r
` + this._vertexCompilationState.compilationString + `\r
\r
// Fragment shader\r
` + this._fragmentCompilationState.compilationString
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.bindOnlyWorldMatrix = function(t) {
        var r = this.getScene();
        if (!!this._activeEffect) {
            var n = this._sharedData.hints;
            n.needWorldViewMatrix && t.multiplyToRef(r.getViewMatrix(), this._cachedWorldViewMatrix),
            n.needWorldViewProjectionMatrix && t.multiplyToRef(r.getTransformMatrix(), this._cachedWorldViewProjectionMatrix);
            for (var o = 0, a = this._sharedData.inputBlocks; o < a.length; o++) {
                var s = a[o];
                s._transmitWorld(this._activeEffect, t, this._cachedWorldViewMatrix, this._cachedWorldViewProjectionMatrix)
            }
        }
    }
    ,
    e.prototype.bindForSubMesh = function(t, r, n) {
        var o = this.getScene()
          , a = n.effect;
        if (!!a) {
            this._activeEffect = a,
            this.bindOnlyWorldMatrix(t);
            var s = this._mustRebind(o, a, r.visibility)
              , l = this._sharedData;
            if (s) {
                if (a) {
                    for (var u = 0, c = l.bindableBlocks; u < c.length; u++) {
                        var h = c[u];
                        h.bind(a, this, r, n)
                    }
                    for (var f = 0, d = l.forcedBindableBlocks; f < d.length; f++) {
                        var h = d[f];
                        h.bind(a, this, r, n)
                    }
                    for (var _ = 0, g = l.inputBlocks; _ < g.length; _++) {
                        var m = g[_];
                        m._transmit(a, o)
                    }
                }
            } else if (!this.isFrozen)
                for (var v = 0, y = l.forcedBindableBlocks; v < y.length; v++) {
                    var h = y[v];
                    h.bind(a, this, r, n)
                }
            this._afterBind(r, this._activeEffect)
        }
    }
    ,
    e.prototype.getActiveTextures = function() {
        var t = i.prototype.getActiveTextures.call(this);
        return this._sharedData && t.push.apply(t, this._sharedData.textureBlocks.filter(function(r) {
            return r.texture
        }).map(function(r) {
            return r.texture
        })),
        t
    }
    ,
    e.prototype.getTextureBlocks = function() {
        return this._sharedData ? this._sharedData.textureBlocks : []
    }
    ,
    e.prototype.hasTexture = function(t) {
        if (i.prototype.hasTexture.call(this, t))
            return !0;
        if (!this._sharedData)
            return !1;
        for (var r = 0, n = this._sharedData.textureBlocks; r < n.length; r++) {
            var o = n[r];
            if (o.texture === t)
                return !0
        }
        return !1
    }
    ,
    e.prototype.dispose = function(t, r, n) {
        if (r && this._sharedData)
            for (var o = 0, a = this._sharedData.textureBlocks.filter(function(h) {
                return h.texture
            }).map(function(h) {
                return h.texture
            }); o < a.length; o++) {
                var s = a[o];
                s.dispose()
            }
        for (var l = 0, u = this.attachedBlocks; l < u.length; l++) {
            var c = u[l];
            c.dispose()
        }
        this.attachedBlocks = [],
        this._sharedData = null,
        this._vertexCompilationState = null,
        this._fragmentCompilationState = null,
        this.attachedBlocks = [],
        this._sharedData = null,
        this._vertexCompilationState = null,
        this._fragmentCompilationState = null,
        this.onBuildObservable.clear(),
        this._imageProcessingObserver && (this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),
        this._imageProcessingObserver = null),
        i.prototype.dispose.call(this, t, r, n)
    }
    ,
    e.prototype._createNodeEditor = function() {
        this.BJSNODEMATERIALEDITOR.NodeEditor.Show({
            nodeMaterial: this
        })
    }
    ,
    e.prototype.edit = function(t) {
        var r = this;
        return new Promise(function(n, o) {
            if (r.BJSNODEMATERIALEDITOR = r.BJSNODEMATERIALEDITOR || r._getGlobalNodeMaterialEditor(),
            typeof r.BJSNODEMATERIALEDITOR == "undefined") {
                var a = t && t.editorURL ? t.editorURL : e.EditorURL;
                Tools.LoadScript(a, function() {
                    r.BJSNODEMATERIALEDITOR = r.BJSNODEMATERIALEDITOR || r._getGlobalNodeMaterialEditor(),
                    r._createNodeEditor(),
                    n()
                })
            } else
                r._createNodeEditor(),
                n()
        }
        )
    }
    ,
    e.prototype.clear = function() {
        this._vertexOutputNodes = [],
        this._fragmentOutputNodes = [],
        this.attachedBlocks = []
    }
    ,
    e.prototype.setToDefault = function() {
        this.clear(),
        this.editorData = null;
        var t = new InputBlock("Position");
        t.setAsAttribute("position");
        var r = new InputBlock("World");
        r.setAsSystemValue(NodeMaterialSystemValues.World);
        var n = new TransformBlock("WorldPos");
        t.connectTo(n),
        r.connectTo(n);
        var o = new InputBlock("ViewProjection");
        o.setAsSystemValue(NodeMaterialSystemValues.ViewProjection);
        var a = new TransformBlock("WorldPos * ViewProjectionTransform");
        n.connectTo(a),
        o.connectTo(a);
        var s = new VertexOutputBlock("VertexOutput");
        a.connectTo(s);
        var l = new InputBlock("color");
        l.value = new Color4(.8,.8,.8,1);
        var u = new FragmentOutputBlock("FragmentOutput");
        l.connectTo(u),
        this.addOutputNode(s),
        this.addOutputNode(u),
        this._mode = NodeMaterialModes.Material
    }
    ,
    e.prototype.setToDefaultPostProcess = function() {
        this.clear(),
        this.editorData = null;
        var t = new InputBlock("Position");
        t.setAsAttribute("position2d");
        var r = new InputBlock("Constant1");
        r.isConstant = !0,
        r.value = 1;
        var n = new VectorMergerBlock("Position3D");
        t.connectTo(n),
        r.connectTo(n, {
            input: "w"
        });
        var o = new VertexOutputBlock("VertexOutput");
        n.connectTo(o);
        var a = new InputBlock("Scale");
        a.visibleInInspector = !0,
        a.value = new Vector2(1,1);
        var s = new RemapBlock("uv0");
        t.connectTo(s);
        var l = new MultiplyBlock("UV scale");
        s.connectTo(l),
        a.connectTo(l);
        var u = new CurrentScreenBlock("CurrentScreen");
        l.connectTo(u),
        u.texture = new Texture("https://assets.babylonjs.com/nme/currentScreenPostProcess.png",this.getScene());
        var c = new FragmentOutputBlock("FragmentOutput");
        u.connectTo(c, {
            output: "rgba"
        }),
        this.addOutputNode(o),
        this.addOutputNode(c),
        this._mode = NodeMaterialModes.PostProcess
    }
    ,
    e.prototype.setToDefaultProceduralTexture = function() {
        this.clear(),
        this.editorData = null;
        var t = new InputBlock("Position");
        t.setAsAttribute("position2d");
        var r = new InputBlock("Constant1");
        r.isConstant = !0,
        r.value = 1;
        var n = new VectorMergerBlock("Position3D");
        t.connectTo(n),
        r.connectTo(n, {
            input: "w"
        });
        var o = new VertexOutputBlock("VertexOutput");
        n.connectTo(o);
        var a = new InputBlock("Time");
        a.value = 0,
        a.min = 0,
        a.max = 0,
        a.isBoolean = !1,
        a.matrixMode = 0,
        a.animationType = AnimatedInputBlockTypes.Time,
        a.isConstant = !1;
        var s = new InputBlock("Color3");
        s.value = new Color3(1,1,1),
        s.isConstant = !1;
        var l = new FragmentOutputBlock("FragmentOutput")
          , u = new VectorMergerBlock("VectorMerger");
        u.visibleInInspector = !1;
        var c = new TrigonometryBlock("Cos");
        c.operation = TrigonometryBlockOperations.Cos,
        t.connectTo(u),
        a.output.connectTo(c.input),
        c.output.connectTo(u.z),
        u.xyzOut.connectTo(l.rgb),
        this.addOutputNode(o),
        this.addOutputNode(l),
        this._mode = NodeMaterialModes.ProceduralTexture
    }
    ,
    e.prototype.setToDefaultParticle = function() {
        this.clear(),
        this.editorData = null;
        var t = new InputBlock("uv");
        t.setAsAttribute("particle_uv");
        var r = new ParticleTextureBlock("ParticleTexture");
        t.connectTo(r);
        var n = new InputBlock("Color");
        n.setAsAttribute("particle_color");
        var o = new MultiplyBlock("Texture * Color");
        r.connectTo(o),
        n.connectTo(o);
        var a = new ParticleRampGradientBlock("ParticleRampGradient");
        o.connectTo(a);
        var s = new ColorSplitterBlock("ColorSplitter");
        n.connectTo(s);
        var l = new ParticleBlendMultiplyBlock("ParticleBlendMultiply");
        a.connectTo(l),
        r.connectTo(l, {
            output: "a"
        }),
        s.connectTo(l, {
            output: "a"
        });
        var u = new FragmentOutputBlock("FragmentOutput");
        l.connectTo(u),
        this.addOutputNode(u),
        this._mode = NodeMaterialModes.Particle
    }
    ,
    e.prototype.loadAsync = function(t) {
        var r = this;
        return this.getScene()._loadFileAsync(t).then(function(n) {
            var o = JSON.parse(n);
            r.loadFromSerialization(o, "")
        })
    }
    ,
    e.prototype._gatherBlocks = function(t, r) {
        if (r.indexOf(t) === -1) {
            r.push(t);
            for (var n = 0, o = t.inputs; n < o.length; n++) {
                var a = o[n]
                  , s = a.connectedPoint;
                if (s) {
                    var l = s.ownerBlock;
                    l !== t && this._gatherBlocks(l, r)
                }
            }
        }
    }
    ,
    e.prototype.generateCode = function() {
        for (var t = [], r = [], n = ["const", "var", "let"], o = 0, a = this._vertexOutputNodes; o < a.length; o++) {
            var s = a[o];
            this._gatherBlocks(s, r)
        }
        for (var l = [], u = 0, c = this._fragmentOutputNodes; u < c.length; u++) {
            var s = c[u];
            this._gatherBlocks(s, l)
        }
        for (var h = 'var nodeMaterial = new BABYLON.NodeMaterial("' + (this.name || "node material") + `");\r
`, f = 0, d = r; f < d.length; f++) {
            var _ = d[f];
            _.isInput && t.indexOf(_) === -1 && (h += _._dumpCode(n, t))
        }
        for (var g = 0, m = l; g < m.length; g++) {
            var _ = m[g];
            _.isInput && t.indexOf(_) === -1 && (h += _._dumpCode(n, t))
        }
        t = [],
        h += `\r
// Connections\r
`;
        for (var v = 0, y = this._vertexOutputNodes; v < y.length; v++) {
            var _ = y[v];
            h += _._dumpCodeForOutputConnections(t)
        }
        for (var b = 0, T = this._fragmentOutputNodes; b < T.length; b++) {
            var _ = T[b];
            h += _._dumpCodeForOutputConnections(t)
        }
        h += `\r
// Output nodes\r
`;
        for (var C = 0, A = this._vertexOutputNodes; C < A.length; C++) {
            var _ = A[C];
            h += "nodeMaterial.addOutputNode(" + _._codeVariableName + `);\r
`
        }
        for (var S = 0, P = this._fragmentOutputNodes; S < P.length; S++) {
            var _ = P[S];
            h += "nodeMaterial.addOutputNode(" + _._codeVariableName + `);\r
`
        }
        return h += `nodeMaterial.build();\r
`,
        h
    }
    ,
    e.prototype.serialize = function(t) {
        var r = t ? {} : SerializationHelper.Serialize(this);
        r.editorData = JSON.parse(JSON.stringify(this.editorData));
        var n = [];
        if (t)
            n = t;
        else {
            r.customType = "BABYLON.NodeMaterial",
            r.outputNodes = [];
            for (var o = 0, a = this._vertexOutputNodes; o < a.length; o++) {
                var s = a[o];
                this._gatherBlocks(s, n),
                r.outputNodes.push(s.uniqueId)
            }
            for (var l = 0, u = this._fragmentOutputNodes; l < u.length; l++) {
                var s = u[l];
                this._gatherBlocks(s, n),
                r.outputNodes.indexOf(s.uniqueId) === -1 && r.outputNodes.push(s.uniqueId)
            }
        }
        r.blocks = [];
        for (var c = 0, h = n; c < h.length; c++) {
            var f = h[c];
            r.blocks.push(f.serialize())
        }
        if (!t)
            for (var d = 0, _ = this.attachedBlocks; d < _.length; d++) {
                var f = _[d];
                n.indexOf(f) === -1 && r.blocks.push(f.serialize())
            }
        return r
    }
    ,
    e.prototype._restoreConnections = function(t, r, n) {
        for (var o = 0, a = t.outputs; o < a.length; o++)
            for (var s = a[o], l = 0, u = r.blocks; l < u.length; l++) {
                var c = u[l]
                  , h = n[c.id];
                if (!!h)
                    for (var f = 0, d = c.inputs; f < d.length; f++) {
                        var _ = d[f];
                        if (n[_.targetBlockId] === t && _.targetConnectionName === s.name) {
                            var g = h.getInputByName(_.inputName);
                            if (!g || g.isConnected)
                                continue;
                            s.connectTo(g, !0),
                            this._restoreConnections(h, r, n);
                            continue
                        }
                    }
            }
    }
    ,
    e.prototype.loadFromSerialization = function(t, r, n) {
        var o;
        r === void 0 && (r = ""),
        n === void 0 && (n = !1),
        n || this.clear();
        for (var a = {}, s = 0, l = t.blocks; s < l.length; s++) {
            var u = l[s]
              , c = GetClass(u.customType);
            if (c) {
                var h = new c;
                h._deserialize(u, this.getScene(), r),
                a[u.id] = h,
                this.attachedBlocks.push(h)
            }
        }
        for (var f = 0; f < t.blocks.length; f++) {
            var d = t.blocks[f]
              , h = a[d.id];
            !h || h.inputs.length && !n || this._restoreConnections(h, t, a)
        }
        if (t.outputNodes)
            for (var _ = 0, g = t.outputNodes; _ < g.length; _++) {
                var m = g[_];
                this.addOutputNode(a[m])
            }
        if (t.locations || t.editorData && t.editorData.locations) {
            for (var v = t.locations || t.editorData.locations, y = 0, b = v; y < b.length; y++) {
                var T = b[y];
                a[T.blockId] && (T.blockId = a[T.blockId].uniqueId)
            }
            n && this.editorData && this.editorData.locations && v.concat(this.editorData.locations),
            t.locations ? this.editorData = {
                locations: v
            } : (this.editorData = t.editorData,
            this.editorData.locations = v);
            var C = [];
            for (var A in a)
                C[A] = a[A].uniqueId;
            this.editorData.map = C
        }
        this.comment = t.comment,
        n || (this._mode = (o = t.mode) !== null && o !== void 0 ? o : NodeMaterialModes.Material)
    }
    ,
    e.prototype.clone = function(t, r) {
        var n = this;
        r === void 0 && (r = !1);
        var o = this.serialize()
          , a = SerializationHelper.Clone(function() {
            return new e(t,n.getScene(),n.options)
        }, this);
        return a.id = t,
        a.name = t,
        a.loadFromSerialization(o),
        a._buildId = this._buildId,
        a.build(!1, !r),
        a
    }
    ,
    e.Parse = function(t, r, n) {
        n === void 0 && (n = "");
        var o = SerializationHelper.Parse(function() {
            return new e(t.name,r)
        }, t, r, n);
        return o.loadFromSerialization(t, n),
        o.build(),
        o
    }
    ,
    e.ParseFromFileAsync = function(t, r, n) {
        var o = new e(t,n);
        return new Promise(function(a, s) {
            return o.loadAsync(r).then(function() {
                o.build(),
                a(o)
            }).catch(s)
        }
        )
    }
    ,
    e.ParseFromSnippetAsync = function(t, r, n, o) {
        var a = this;
        return n === void 0 && (n = ""),
        t === "_BLANK" ? Promise.resolve(this.CreateDefault("blank", r)) : new Promise(function(s, l) {
            var u = new WebRequest;
            u.addEventListener("readystatechange", function() {
                if (u.readyState == 4)
                    if (u.status == 200) {
                        var c = JSON.parse(JSON.parse(u.responseText).jsonPayload)
                          , h = JSON.parse(c.nodeMaterial);
                        o || (o = SerializationHelper.Parse(function() {
                            return new e(t,r)
                        }, h, r, n),
                        o.uniqueId = r.getUniqueId()),
                        o.loadFromSerialization(h),
                        o.snippetId = t;
                        try {
                            o.build(),
                            s(o)
                        } catch (f) {
                            l(f)
                        }
                    } else
                        l("Unable to load the snippet " + t)
            }),
            u.open("GET", a.SnippetUrl + "/" + t.replace(/#/g, "/")),
            u.send()
        }
        )
    }
    ,
    e.CreateDefault = function(t, r) {
        var n = new e(t,r);
        return n.setToDefault(),
        n.build(),
        n
    }
    ,
    e._BuildIdGenerator = 0,
    e.EditorURL = "https://unpkg.com/babylonjs-node-editor@" + Engine.Version + "/babylon.nodeEditor.js",
    e.SnippetUrl = "https://snippet.babylonjs.com",
    e.IgnoreTexturesAtLoadTime = !1,
    __decorate([serialize()], e.prototype, "ignoreAlpha", void 0),
    __decorate([serialize()], e.prototype, "maxSimultaneousLights", void 0),
    __decorate([serialize("mode")], e.prototype, "_mode", void 0),
    __decorate([serialize("comment")], e.prototype, "comment", void 0),
    e
}(PushMaterial);
RegisterClass("BABYLON.NodeMaterial", NodeMaterial);
var BonesBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Vertex) || this;
        return r.registerInput("matricesIndices", NodeMaterialBlockConnectionPointTypes.Vector4),
        r.registerInput("matricesWeights", NodeMaterialBlockConnectionPointTypes.Vector4),
        r.registerInput("matricesIndicesExtra", NodeMaterialBlockConnectionPointTypes.Vector4, !0),
        r.registerInput("matricesWeightsExtra", NodeMaterialBlockConnectionPointTypes.Vector4, !0),
        r.registerInput("world", NodeMaterialBlockConnectionPointTypes.Matrix),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Matrix),
        r
    }
    return e.prototype.initialize = function(t) {
        t._excludeVariableName("boneSampler"),
        t._excludeVariableName("boneTextureWidth"),
        t._excludeVariableName("mBones"),
        t._excludeVariableName("BonesPerMesh")
    }
    ,
    e.prototype.getClassName = function() {
        return "BonesBlock"
    }
    ,
    Object.defineProperty(e.prototype, "matricesIndices", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "matricesWeights", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "matricesIndicesExtra", {
        get: function() {
            return this._inputs[2]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "matricesWeightsExtra", {
        get: function() {
            return this._inputs[3]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "world", {
        get: function() {
            return this._inputs[4]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.autoConfigure = function(t) {
        if (!this.matricesIndices.isConnected) {
            var r = t.getInputBlockByPredicate(function(a) {
                return a.isAttribute && a.name === "matricesIndices"
            });
            r || (r = new InputBlock("matricesIndices"),
            r.setAsAttribute("matricesIndices")),
            r.output.connectTo(this.matricesIndices)
        }
        if (!this.matricesWeights.isConnected) {
            var n = t.getInputBlockByPredicate(function(a) {
                return a.isAttribute && a.name === "matricesWeights"
            });
            n || (n = new InputBlock("matricesWeights"),
            n.setAsAttribute("matricesWeights")),
            n.output.connectTo(this.matricesWeights)
        }
        if (!this.world.isConnected) {
            var o = t.getInputBlockByPredicate(function(a) {
                return a.systemValue === NodeMaterialSystemValues.World
            });
            o || (o = new InputBlock("world"),
            o.setAsSystemValue(NodeMaterialSystemValues.World)),
            o.output.connectTo(this.world)
        }
    }
    ,
    e.prototype.provideFallbacks = function(t, r) {
        t && t.useBones && t.computeBonesUsingShaders && t.skeleton && r.addCPUSkinningFallback(0, t)
    }
    ,
    e.prototype.bind = function(t, r, n) {
        MaterialHelper.BindBonesParameters(n, t)
    }
    ,
    e.prototype.prepareDefines = function(t, r, n) {
        !n._areAttributesDirty || MaterialHelper.PrepareDefinesForBones(t, n)
    }
    ,
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t),
        t.sharedData.blocksWithFallbacks.push(this),
        t.sharedData.bindableBlocks.push(this),
        t.sharedData.blocksWithDefines.push(this),
        t.uniforms.push("boneTextureWidth"),
        t.uniforms.push("mBones"),
        t.samplers.push("boneSampler");
        var r = "//" + this.name;
        t._emitFunctionFromInclude("bonesDeclaration", r, {
            removeAttributes: !0,
            removeUniforms: !1,
            removeVaryings: !0,
            removeIfDef: !1
        });
        var n = t._getFreeVariableName("influence");
        t.compilationString += t._emitCodeFromInclude("bonesVertex", r, {
            replaceStrings: [{
                search: /finalWorld=finalWorld\*influence;/,
                replace: ""
            }, {
                search: /influence/gm,
                replace: n
            }]
        });
        var o = this._outputs[0]
          , a = this.world;
        return t.compilationString += `#if NUM_BONE_INFLUENCERS>0\r
`,
        t.compilationString += this._declareOutput(o, t) + (" = " + a.associatedVariableName + " * " + n + `;\r
`),
        t.compilationString += `#else\r
`,
        t.compilationString += this._declareOutput(o, t) + (" = " + a.associatedVariableName + `;\r
`),
        t.compilationString += `#endif\r
`,
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.BonesBlock", BonesBlock);
var InstancesBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Vertex) || this;
        return r.registerInput("world0", NodeMaterialBlockConnectionPointTypes.Vector4),
        r.registerInput("world1", NodeMaterialBlockConnectionPointTypes.Vector4),
        r.registerInput("world2", NodeMaterialBlockConnectionPointTypes.Vector4),
        r.registerInput("world3", NodeMaterialBlockConnectionPointTypes.Vector4),
        r.registerInput("world", NodeMaterialBlockConnectionPointTypes.Matrix, !0),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Matrix),
        r.registerOutput("instanceID", NodeMaterialBlockConnectionPointTypes.Float),
        r
    }
    return e.prototype.getClassName = function() {
        return "InstancesBlock"
    }
    ,
    Object.defineProperty(e.prototype, "world0", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "world1", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "world2", {
        get: function() {
            return this._inputs[2]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "world3", {
        get: function() {
            return this._inputs[3]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "world", {
        get: function() {
            return this._inputs[4]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "instanceID", {
        get: function() {
            return this._outputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.autoConfigure = function(t) {
        if (!this.world0.connectedPoint) {
            var r = t.getInputBlockByPredicate(function(l) {
                return l.isAttribute && l.name === "world0"
            });
            r || (r = new InputBlock("world0"),
            r.setAsAttribute("world0")),
            r.output.connectTo(this.world0)
        }
        if (!this.world1.connectedPoint) {
            var n = t.getInputBlockByPredicate(function(l) {
                return l.isAttribute && l.name === "world1"
            });
            n || (n = new InputBlock("world1"),
            n.setAsAttribute("world1")),
            n.output.connectTo(this.world1)
        }
        if (!this.world2.connectedPoint) {
            var o = t.getInputBlockByPredicate(function(l) {
                return l.isAttribute && l.name === "world2"
            });
            o || (o = new InputBlock("world2"),
            o.setAsAttribute("world2")),
            o.output.connectTo(this.world2)
        }
        if (!this.world3.connectedPoint) {
            var a = t.getInputBlockByPredicate(function(l) {
                return l.isAttribute && l.name === "world3"
            });
            a || (a = new InputBlock("world3"),
            a.setAsAttribute("world3")),
            a.output.connectTo(this.world3)
        }
        if (!this.world.connectedPoint) {
            var s = t.getInputBlockByPredicate(function(l) {
                return l.isAttribute && l.name === "world"
            });
            s || (s = new InputBlock("world"),
            s.setAsSystemValue(NodeMaterialSystemValues.World)),
            s.output.connectTo(this.world)
        }
        this.world.define = "!INSTANCES || THIN_INSTANCES"
    }
    ,
    e.prototype.prepareDefines = function(t, r, n, o, a) {
        o === void 0 && (o = !1);
        var s = !1;
        n.INSTANCES !== o && (n.setValue("INSTANCES", o),
        s = !0),
        a && n.THIN_INSTANCES !== !!(a != null && a.getRenderingMesh().hasThinInstances) && (n.setValue("THIN_INSTANCES", !!(a != null && a.getRenderingMesh().hasThinInstances)),
        s = !0),
        s && n.markAsUnprocessed()
    }
    ,
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = t.sharedData.scene.getEngine();
        t.sharedData.blocksWithDefines.push(this);
        var n = this._outputs[0]
          , o = this._outputs[1]
          , a = this.world0
          , s = this.world1
          , l = this.world2
          , u = this.world3;
        return t.compilationString += `#ifdef INSTANCES\r
`,
        t.compilationString += this._declareOutput(n, t) + (" = mat4(" + a.associatedVariableName + ", " + s.associatedVariableName + ", " + l.associatedVariableName + ", " + u.associatedVariableName + `);\r
`),
        t.compilationString += `#ifdef THIN_INSTANCES\r
`,
        t.compilationString += n.associatedVariableName + " = " + this.world.associatedVariableName + " * " + n.associatedVariableName + `;\r
`,
        t.compilationString += `#endif\r
`,
        r._caps.canUseGLInstanceID ? t.compilationString += this._declareOutput(o, t) + ` = float(gl_InstanceID);\r
` : t.compilationString += this._declareOutput(o, t) + ` = 0.0;\r
`,
        t.compilationString += `#else\r
`,
        t.compilationString += this._declareOutput(n, t) + (" = " + this.world.associatedVariableName + `;\r
`),
        t.compilationString += this._declareOutput(o, t) + ` = 0.0;\r
`,
        t.compilationString += `#endif\r
`,
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.InstancesBlock", InstancesBlock);
var MorphTargetsBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Vertex) || this;
        return r.registerInput("position", NodeMaterialBlockConnectionPointTypes.Vector3),
        r.registerInput("normal", NodeMaterialBlockConnectionPointTypes.Vector3),
        r.registerInput("tangent", NodeMaterialBlockConnectionPointTypes.Vector3),
        r.registerInput("uv", NodeMaterialBlockConnectionPointTypes.Vector2),
        r.registerOutput("positionOutput", NodeMaterialBlockConnectionPointTypes.Vector3),
        r.registerOutput("normalOutput", NodeMaterialBlockConnectionPointTypes.Vector3),
        r.registerOutput("tangentOutput", NodeMaterialBlockConnectionPointTypes.Vector3),
        r.registerOutput("uvOutput", NodeMaterialBlockConnectionPointTypes.Vector2),
        r
    }
    return e.prototype.getClassName = function() {
        return "MorphTargetsBlock"
    }
    ,
    Object.defineProperty(e.prototype, "position", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "normal", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "tangent", {
        get: function() {
            return this._inputs[2]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "uv", {
        get: function() {
            return this._inputs[3]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "positionOutput", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "normalOutput", {
        get: function() {
            return this._outputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "tangentOutput", {
        get: function() {
            return this._outputs[2]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "uvOutput", {
        get: function() {
            return this._outputs[3]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.initialize = function(t) {
        t._excludeVariableName("morphTargetInfluences")
    }
    ,
    e.prototype.autoConfigure = function(t) {
        if (!this.position.isConnected) {
            var r = t.getInputBlockByPredicate(function(s) {
                return s.isAttribute && s.name === "position"
            });
            r || (r = new InputBlock("position"),
            r.setAsAttribute()),
            r.output.connectTo(this.position)
        }
        if (!this.normal.isConnected) {
            var n = t.getInputBlockByPredicate(function(s) {
                return s.isAttribute && s.name === "normal"
            });
            n || (n = new InputBlock("normal"),
            n.setAsAttribute("normal")),
            n.output.connectTo(this.normal)
        }
        if (!this.tangent.isConnected) {
            var o = t.getInputBlockByPredicate(function(s) {
                return s.isAttribute && s.name === "tangent"
            });
            o || (o = new InputBlock("tangent"),
            o.setAsAttribute("tangent")),
            o.output.connectTo(this.tangent)
        }
        if (!this.uv.isConnected) {
            var a = t.getInputBlockByPredicate(function(s) {
                return s.isAttribute && s.name === "uv"
            });
            a || (a = new InputBlock("uv"),
            a.setAsAttribute("uv")),
            a.output.connectTo(this.uv)
        }
    }
    ,
    e.prototype.prepareDefines = function(t, r, n) {
        if (t.morphTargetManager) {
            var o = t.morphTargetManager;
            (o == null ? void 0 : o.isUsingTextureForTargets) && o.numInfluencers !== n.NUM_MORPH_INFLUENCERS && n.markAsAttributesDirty()
        }
        !n._areAttributesDirty || MaterialHelper.PrepareDefinesForMorphTargets(t, n)
    }
    ,
    e.prototype.bind = function(t, r, n) {
        n && n.morphTargetManager && n.morphTargetManager.numInfluencers > 0 && (MaterialHelper.BindMorphTargetParameters(n, t),
        n.morphTargetManager.isUsingTextureForTargets && n.morphTargetManager._bind(t))
    }
    ,
    e.prototype.replaceRepeatableContent = function(t, r, n, o) {
        var a = this.position
          , s = this.normal
          , l = this.tangent
          , u = this.uv
          , c = this.positionOutput
          , h = this.normalOutput
          , f = this.tangentOutput
          , d = this.uvOutput
          , _ = t
          , g = o.NUM_MORPH_INFLUENCERS
          , m = n.morphTargetManager
          , v = m && m.supportsNormals && o.NORMAL
          , y = m && m.supportsTangents && o.TANGENT
          , b = m && m.supportsUVs && o.UV1
          , T = "";
        (m == null ? void 0 : m.isUsingTextureForTargets) && g > 0 && (T += `float vertexID;\r
`);
        for (var C = 0; C < g; C++)
            T += `#ifdef MORPHTARGETS\r
`,
            m != null && m.isUsingTextureForTargets ? (T += `vertexID = float(gl_VertexID) * morphTargetTextureInfo.x;\r
`,
            T += c.associatedVariableName + " += (readVector3FromRawSampler(" + C + ", vertexID) - " + a.associatedVariableName + ") * morphTargetInfluences[" + C + `];\r
`,
            T += `vertexID += 1.0;\r
`) : T += c.associatedVariableName + " += (position" + C + " - " + a.associatedVariableName + ") * morphTargetInfluences[" + C + `];\r
`,
            v && (T += `#ifdef MORPHTARGETS_NORMAL\r
`,
            m != null && m.isUsingTextureForTargets ? (T += h.associatedVariableName + " += (readVector3FromRawSampler(" + C + ", vertexID) - " + s.associatedVariableName + ") * morphTargetInfluences[" + C + `];\r
`,
            T += `vertexID += 1.0;\r
`) : T += h.associatedVariableName + " += (normal" + C + " - " + s.associatedVariableName + ") * morphTargetInfluences[" + C + `];\r
`,
            T += `#endif\r
`),
            b && (T += `#ifdef MORPHTARGETS_UV\r
`,
            m != null && m.isUsingTextureForTargets ? (T += d.associatedVariableName + " += (readVector3FromRawSampler(" + C + ", vertexID).xy - " + u.associatedVariableName + ") * morphTargetInfluences[" + C + `];\r
`,
            T += `vertexID += 1.0;\r
`) : T += d.associatedVariableName + ".xy += (uv_" + C + " - " + u.associatedVariableName + ".xy) * morphTargetInfluences[" + C + `];\r
`,
            T += `#endif\r
`),
            y && (T += `#ifdef MORPHTARGETS_TANGENT\r
`,
            m != null && m.isUsingTextureForTargets ? T += f.associatedVariableName + " += (readVector3FromRawSampler(" + C + ", vertexID) - " + l.associatedVariableName + ") * morphTargetInfluences[" + C + `];\r
` : T += f.associatedVariableName + ".xyz += (tangent" + C + " - " + l.associatedVariableName + ".xyz) * morphTargetInfluences[" + C + `];\r
`,
            T += `#endif\r
`),
            T += `#endif\r
`;
        if (_.compilationString = _.compilationString.replace(this._repeatableContentAnchor, T),
        g > 0)
            for (var C = 0; C < g; C++)
                _.attributes.push(VertexBuffer.PositionKind + C),
                v && _.attributes.push(VertexBuffer.NormalKind + C),
                y && _.attributes.push(VertexBuffer.TangentKind + C),
                b && _.attributes.push(VertexBuffer.UVKind + "_" + C)
    }
    ,
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t),
        t.sharedData.blocksWithDefines.push(this),
        t.sharedData.bindableBlocks.push(this),
        t.sharedData.repeatableContentBlocks.push(this);
        var r = this.position
          , n = this.normal
          , o = this.tangent
          , a = this.uv
          , s = this.positionOutput
          , l = this.normalOutput
          , u = this.tangentOutput
          , c = this.uvOutput
          , h = "//" + this.name;
        return t.uniforms.push("morphTargetInfluences"),
        t.uniforms.push("morphTargetTextureInfo"),
        t.uniforms.push("morphTargetTextureIndices"),
        t.samplers.push("morphTargets"),
        t._emitFunctionFromInclude("morphTargetsVertexGlobalDeclaration", h),
        t._emitFunctionFromInclude("morphTargetsVertexDeclaration", h, {
            repeatKey: "maxSimultaneousMorphTargets"
        }),
        t.compilationString += this._declareOutput(s, t) + " = " + r.associatedVariableName + `;\r
`,
        t.compilationString += `#ifdef NORMAL\r
`,
        t.compilationString += this._declareOutput(l, t) + " = " + n.associatedVariableName + `;\r
`,
        t.compilationString += `#else\r
`,
        t.compilationString += this._declareOutput(l, t) + ` = vec3(0., 0., 0.);\r
`,
        t.compilationString += `#endif\r
`,
        t.compilationString += `#ifdef TANGENT\r
`,
        t.compilationString += this._declareOutput(u, t) + " = " + o.associatedVariableName + `;\r
`,
        t.compilationString += `#else\r
`,
        t.compilationString += this._declareOutput(u, t) + ` = vec3(0., 0., 0.);\r
`,
        t.compilationString += `#endif\r
`,
        t.compilationString += `#ifdef UV1\r
`,
        t.compilationString += this._declareOutput(c, t) + " = " + a.associatedVariableName + `;\r
`,
        t.compilationString += `#else\r
`,
        t.compilationString += this._declareOutput(c, t) + ` = vec2(0., 0.);\r
`,
        t.compilationString += `#endif\r
`,
        this._repeatableContentAnchor = t._repeatableContentAnchor,
        t.compilationString += this._repeatableContentAnchor,
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.MorphTargetsBlock", MorphTargetsBlock);
var LightInformationBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Vertex) || this;
        return r.registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes.Vector4, !1, NodeMaterialBlockTargets.Vertex),
        r.registerOutput("direction", NodeMaterialBlockConnectionPointTypes.Vector3),
        r.registerOutput("color", NodeMaterialBlockConnectionPointTypes.Color3),
        r.registerOutput("intensity", NodeMaterialBlockConnectionPointTypes.Float),
        r
    }
    return e.prototype.getClassName = function() {
        return "LightInformationBlock"
    }
    ,
    Object.defineProperty(e.prototype, "worldPosition", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "direction", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "color", {
        get: function() {
            return this._outputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "intensity", {
        get: function() {
            return this._outputs[2]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.bind = function(t, r, n) {
        if (!!n) {
            this.light && this.light.isDisposed && (this.light = null);
            var o = this.light
              , a = r.getScene();
            if (!o && a.lights.length && (o = this.light = a.lights[0],
            this._forcePrepareDefines = !0),
            !o || !o.isEnabled) {
                t.setFloat3(this._lightDataUniformName, 0, 0, 0),
                t.setFloat4(this._lightColorUniformName, 0, 0, 0, 0);
                return
            }
            o.transferToNodeMaterialEffect(t, this._lightDataUniformName),
            t.setColor4(this._lightColorUniformName, o.diffuse, o.intensity)
        }
    }
    ,
    e.prototype.prepareDefines = function(t, r, n) {
        if (!(!n._areLightsDirty && !this._forcePrepareDefines)) {
            this._forcePrepareDefines = !1;
            var o = this.light;
            n.setValue(this._lightTypeDefineName, !!(o && o instanceof PointLight), !0)
        }
    }
    ,
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t),
        t.sharedData.bindableBlocks.push(this),
        t.sharedData.blocksWithDefines.push(this);
        var r = this.direction
          , n = this.color
          , o = this.intensity;
        return this._lightDataUniformName = t._getFreeVariableName("lightData"),
        this._lightColorUniformName = t._getFreeVariableName("lightColor"),
        this._lightTypeDefineName = t._getFreeDefineName("LIGHTPOINTTYPE"),
        t._emitUniformFromString(this._lightDataUniformName, "vec3"),
        t._emitUniformFromString(this._lightColorUniformName, "vec4"),
        t.compilationString += "#ifdef " + this._lightTypeDefineName + `\r
`,
        t.compilationString += this._declareOutput(r, t) + (" = normalize(" + this.worldPosition.associatedVariableName + ".xyz - " + this._lightDataUniformName + `);\r
`),
        t.compilationString += `#else\r
`,
        t.compilationString += this._declareOutput(r, t) + (" = " + this._lightDataUniformName + `;\r
`),
        t.compilationString += `#endif\r
`,
        t.compilationString += this._declareOutput(n, t) + (" = " + this._lightColorUniformName + `.rgb;\r
`),
        t.compilationString += this._declareOutput(o, t) + (" = " + this._lightColorUniformName + `.a;\r
`),
        this
    }
    ,
    e.prototype.serialize = function() {
        var t = i.prototype.serialize.call(this);
        return this.light && (t.lightId = this.light.id),
        t
    }
    ,
    e.prototype._deserialize = function(t, r, n) {
        i.prototype._deserialize.call(this, t, r, n),
        t.lightId && (this.light = r.getLightById(t.lightId))
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.LightInformationBlock", LightInformationBlock);
var ImageProcessingBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Fragment) || this;
        return r.convertInputToLinearSpace = !0,
        r.registerInput("color", NodeMaterialBlockConnectionPointTypes.Color4),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Color4),
        r._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color3),
        r
    }
    return e.prototype.getClassName = function() {
        return "ImageProcessingBlock"
    }
    ,
    Object.defineProperty(e.prototype, "color", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.initialize = function(t) {
        t._excludeVariableName("exposureLinear"),
        t._excludeVariableName("contrast"),
        t._excludeVariableName("vInverseScreenSize"),
        t._excludeVariableName("vignetteSettings1"),
        t._excludeVariableName("vignetteSettings2"),
        t._excludeVariableName("vCameraColorCurveNegative"),
        t._excludeVariableName("vCameraColorCurveNeutral"),
        t._excludeVariableName("vCameraColorCurvePositive"),
        t._excludeVariableName("txColorTransform"),
        t._excludeVariableName("colorTransformSettings")
    }
    ,
    e.prototype.isReady = function(t, r, n) {
        return !(n._areImageProcessingDirty && r.imageProcessingConfiguration && !r.imageProcessingConfiguration.isReady())
    }
    ,
    e.prototype.prepareDefines = function(t, r, n) {
        n._areImageProcessingDirty && r.imageProcessingConfiguration && r.imageProcessingConfiguration.prepareDefines(n)
    }
    ,
    e.prototype.bind = function(t, r, n) {
        !n || !r.imageProcessingConfiguration || r.imageProcessingConfiguration.bind(t)
    }
    ,
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t),
        t.sharedData.blocksWithDefines.push(this),
        t.sharedData.blockingBlocks.push(this),
        t.sharedData.bindableBlocks.push(this),
        t.uniforms.push("exposureLinear"),
        t.uniforms.push("contrast"),
        t.uniforms.push("vInverseScreenSize"),
        t.uniforms.push("vignetteSettings1"),
        t.uniforms.push("vignetteSettings2"),
        t.uniforms.push("vCameraColorCurveNegative"),
        t.uniforms.push("vCameraColorCurveNeutral"),
        t.uniforms.push("vCameraColorCurvePositive"),
        t.uniforms.push("txColorTransform"),
        t.uniforms.push("colorTransformSettings");
        var r = this.color
          , n = this._outputs[0]
          , o = "//" + this.name;
        return t._emitFunctionFromInclude("helperFunctions", o),
        t._emitFunctionFromInclude("imageProcessingDeclaration", o),
        t._emitFunctionFromInclude("imageProcessingFunctions", o),
        r.connectedPoint.type === NodeMaterialBlockConnectionPointTypes.Color4 || r.connectedPoint.type === NodeMaterialBlockConnectionPointTypes.Vector4 ? t.compilationString += this._declareOutput(n, t) + " = " + r.associatedVariableName + `;\r
` : t.compilationString += this._declareOutput(n, t) + " = vec4(" + r.associatedVariableName + `, 1.0);\r
`,
        t.compilationString += `#ifdef IMAGEPROCESSINGPOSTPROCESS\r
`,
        this.convertInputToLinearSpace && (t.compilationString += n.associatedVariableName + ".rgb = toLinearSpace(" + r.associatedVariableName + `.rgb);\r
`),
        t.compilationString += `#else\r
`,
        t.compilationString += `#ifdef IMAGEPROCESSING\r
`,
        this.convertInputToLinearSpace && (t.compilationString += n.associatedVariableName + ".rgb = toLinearSpace(" + r.associatedVariableName + `.rgb);\r
`),
        t.compilationString += n.associatedVariableName + " = applyImageProcessing(" + n.associatedVariableName + `);\r
`,
        t.compilationString += `#endif\r
`,
        t.compilationString += `#endif\r
`,
        this
    }
    ,
    e.prototype._dumpPropertiesCode = function() {
        var t = i.prototype._dumpPropertiesCode.call(this);
        return t += this._codeVariableName + ".convertInputToLinearSpace = " + this.convertInputToLinearSpace + `;\r
`,
        t
    }
    ,
    e.prototype.serialize = function() {
        var t = i.prototype.serialize.call(this);
        return t.convertInputToLinearSpace = this.convertInputToLinearSpace,
        t
    }
    ,
    e.prototype._deserialize = function(t, r, n) {
        var o;
        i.prototype._deserialize.call(this, t, r, n),
        this.convertInputToLinearSpace = (o = t.convertInputToLinearSpace) !== null && o !== void 0 ? o : !0
    }
    ,
    __decorate([editableInPropertyPage("Convert input to linear space", PropertyTypeForEdition.Boolean, "ADVANCED")], e.prototype, "convertInputToLinearSpace", void 0),
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.ImageProcessingBlock", ImageProcessingBlock);
var PerturbNormalBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Fragment) || this;
        return r._tangentSpaceParameterName = "",
        r.invertX = !1,
        r.invertY = !1,
        r.useParallaxOcclusion = !1,
        r._isUnique = !0,
        r.registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes.Vector4, !1),
        r.registerInput("worldNormal", NodeMaterialBlockConnectionPointTypes.Vector4, !1),
        r.registerInput("worldTangent", NodeMaterialBlockConnectionPointTypes.Vector4, !0),
        r.registerInput("uv", NodeMaterialBlockConnectionPointTypes.Vector2, !1),
        r.registerInput("normalMapColor", NodeMaterialBlockConnectionPointTypes.Color3, !1),
        r.registerInput("strength", NodeMaterialBlockConnectionPointTypes.Float, !1),
        r.registerInput("viewDirection", NodeMaterialBlockConnectionPointTypes.Vector3, !0),
        r.registerInput("parallaxScale", NodeMaterialBlockConnectionPointTypes.Float, !0),
        r.registerInput("parallaxHeight", NodeMaterialBlockConnectionPointTypes.Float, !0),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector4),
        r.registerOutput("uvOffset", NodeMaterialBlockConnectionPointTypes.Vector2),
        r
    }
    return e.prototype.getClassName = function() {
        return "PerturbNormalBlock"
    }
    ,
    Object.defineProperty(e.prototype, "worldPosition", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "worldNormal", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "worldTangent", {
        get: function() {
            return this._inputs[2]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "uv", {
        get: function() {
            return this._inputs[3]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "normalMapColor", {
        get: function() {
            return this._inputs[4]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "strength", {
        get: function() {
            return this._inputs[5]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "viewDirection", {
        get: function() {
            return this._inputs[6]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "parallaxScale", {
        get: function() {
            return this._inputs[7]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "parallaxHeight", {
        get: function() {
            return this._inputs[8]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "uvOffset", {
        get: function() {
            return this._outputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.prepareDefines = function(t, r, n) {
        var o = this.normalMapColor.connectedPoint._ownerBlock.samplerName
          , a = this.viewDirection.isConnected && (this.useParallaxOcclusion && o || !this.useParallaxOcclusion && this.parallaxHeight.isConnected);
        n.setValue("BUMP", !0),
        n.setValue("PARALLAX", a, !0),
        n.setValue("PARALLAXOCCLUSION", this.useParallaxOcclusion, !0)
    }
    ,
    e.prototype.bind = function(t, r, n) {
        r.getScene()._mirroredCameraPosition ? t.setFloat2(this._tangentSpaceParameterName, this.invertX ? 1 : -1, this.invertY ? 1 : -1) : t.setFloat2(this._tangentSpaceParameterName, this.invertX ? -1 : 1, this.invertY ? -1 : 1)
    }
    ,
    e.prototype.autoConfigure = function(t) {
        if (!this.uv.isConnected) {
            var r = t.getInputBlockByPredicate(function(o) {
                return o.isAttribute && o.name === "uv"
            });
            r || (r = new InputBlock("uv"),
            r.setAsAttribute()),
            r.output.connectTo(this.uv)
        }
        if (!this.strength.isConnected) {
            var n = new InputBlock("strength");
            n.value = 1,
            n.output.connectTo(this.strength)
        }
    }
    ,
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = "//" + this.name
          , n = this.uv
          , o = this.worldPosition
          , a = this.worldNormal
          , s = this.worldTangent;
        t.sharedData.blocksWithDefines.push(this),
        t.sharedData.bindableBlocks.push(this),
        this._tangentSpaceParameterName = t._getFreeDefineName("tangentSpaceParameter"),
        t._emitUniformFromString(this._tangentSpaceParameterName, "vec2");
        var l = this.normalMapColor.connectedPoint._ownerBlock.samplerName
          , u = this.viewDirection.isConnected && (this.useParallaxOcclusion && l || !this.useParallaxOcclusion && this.parallaxHeight.isConnected)
          , c = this.parallaxScale.isConnectedToInputBlock ? this.parallaxScale.connectInputBlock.isConstant ? t._emitFloat(this.parallaxScale.connectInputBlock.value) : this.parallaxScale.associatedVariableName : "0.05"
          , h = this.strength.isConnectedToInputBlock && this.strength.connectInputBlock.isConstant ? `\r
#if !defined(NORMALXYSCALE)\r
1.0/\r
#endif\r
` + t._emitFloat(this.strength.connectInputBlock.value) : `\r
#if !defined(NORMALXYSCALE)\r
1.0/\r
#endif\r
` + this.strength.associatedVariableName;
        t._emitExtension("derivatives", "#extension GL_OES_standard_derivatives : enable");
        var f = {
            search: /defined\(TANGENT\)/g,
            replace: s.isConnected ? "defined(TANGENT)" : "defined(IGNORE)"
        };
        s.isConnected && (t.compilationString += "vec3 tbnNormal = normalize(" + a.associatedVariableName + `.xyz);\r
`,
        t.compilationString += "vec3 tbnTangent = normalize(" + s.associatedVariableName + `.xyz);\r
`,
        t.compilationString += `vec3 tbnBitangent = cross(tbnNormal, tbnTangent);\r
`,
        t.compilationString += `mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal);\r
`),
        t._emitFunctionFromInclude("bumpFragmentMainFunctions", r, {
            replaceStrings: [f]
        }),
        t._emitFunctionFromInclude("bumpFragmentFunctions", r, {
            replaceStrings: [{
                search: /#include<samplerFragmentDeclaration>\(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump\)/g,
                replace: ""
            }, {
                search: /uniform sampler2D bumpSampler;/g,
                replace: ""
            }, {
                search: /vec2 parallaxOcclusion\(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale\)/g,
                replace: `#define inline\r
vec2 parallaxOcclusion(vec3 vViewDirCoT, vec3 vNormalCoT, vec2 texCoord, float parallaxScale, sampler2D bumpSampler)`
            }, {
                search: /vec2 parallaxOffset\(vec3 viewDir,float heightScale\)/g,
                replace: "vec2 parallaxOffset(vec3 viewDir, float heightScale, float height_)"
            }, {
                search: /texture2D\(bumpSampler,vBumpUV\)\.w/g,
                replace: "height_"
            }]
        });
        var d = !u || !l ? this.normalMapColor.associatedVariableName : "texture2D(" + l + ", " + n.associatedVariableName + " + uvOffset).xyz";
        return t.compilationString += this._declareOutput(this.output, t) + ` = vec4(0.);\r
`,
        t.compilationString += t._emitCodeFromInclude("bumpFragment", r, {
            replaceStrings: [{
                search: /perturbNormal\(TBN,texture2D\(bumpSampler,vBumpUV\+uvOffset\).xyz,vBumpInfos.y\)/g,
                replace: "perturbNormal(TBN, " + d + ", vBumpInfos.y)"
            }, {
                search: /parallaxOcclusion\(invTBN\*-viewDirectionW,invTBN\*normalW,vBumpUV,vBumpInfos.z\)/g,
                replace: "parallaxOcclusion((invTBN * -viewDirectionW), (invTBN * normalW), vBumpUV, vBumpInfos.z, " + (u && this.useParallaxOcclusion ? l : "bumpSampler") + ")"
            }, {
                search: /parallaxOffset\(invTBN\*viewDirectionW,vBumpInfos\.z\)/g,
                replace: "parallaxOffset(invTBN * viewDirectionW, vBumpInfos.z, " + (u ? this.parallaxHeight.associatedVariableName : "0.") + ")"
            }, {
                search: /vTangentSpaceParams/g,
                replace: this._tangentSpaceParameterName
            }, {
                search: /vBumpInfos.y/g,
                replace: h
            }, {
                search: /vBumpInfos.z/g,
                replace: c
            }, {
                search: /vBumpUV/g,
                replace: n.associatedVariableName
            }, {
                search: /vPositionW/g,
                replace: o.associatedVariableName + ".xyz"
            }, {
                search: /normalW=/g,
                replace: this.output.associatedVariableName + ".xyz = "
            }, {
                search: /mat3\(normalMatrix\)\*normalW/g,
                replace: "mat3(normalMatrix) * " + this.output.associatedVariableName + ".xyz"
            }, {
                search: /normalW/g,
                replace: a.associatedVariableName + ".xyz"
            }, {
                search: /viewDirectionW/g,
                replace: u ? this.viewDirection.associatedVariableName : "vec3(0.)"
            }, f]
        }),
        this
    }
    ,
    e.prototype._dumpPropertiesCode = function() {
        var t = i.prototype._dumpPropertiesCode.call(this) + (this._codeVariableName + ".invertX = " + this.invertX + `;\r
`);
        return t += this._codeVariableName + ".invertY = " + this.invertY + `;\r
`,
        t += this._codeVariableName + ".useParallaxOcclusion = " + this.useParallaxOcclusion + `;\r
`,
        t
    }
    ,
    e.prototype.serialize = function() {
        var t = i.prototype.serialize.call(this);
        return t.invertX = this.invertX,
        t.invertY = this.invertY,
        t.useParallaxOcclusion = this.useParallaxOcclusion,
        t
    }
    ,
    e.prototype._deserialize = function(t, r, n) {
        i.prototype._deserialize.call(this, t, r, n),
        this.invertX = t.invertX,
        this.invertY = t.invertY,
        this.useParallaxOcclusion = !!t.useParallaxOcclusion
    }
    ,
    __decorate([editableInPropertyPage("Invert X axis", PropertyTypeForEdition.Boolean, "PROPERTIES", {
        notifiers: {
            update: !1
        }
    })], e.prototype, "invertX", void 0),
    __decorate([editableInPropertyPage("Invert Y axis", PropertyTypeForEdition.Boolean, "PROPERTIES", {
        notifiers: {
            update: !1
        }
    })], e.prototype, "invertY", void 0),
    __decorate([editableInPropertyPage("Use parallax occlusion", PropertyTypeForEdition.Boolean)], e.prototype, "useParallaxOcclusion", void 0),
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.PerturbNormalBlock", PerturbNormalBlock);
var DiscardBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Fragment, !0) || this;
        return r.registerInput("value", NodeMaterialBlockConnectionPointTypes.Float, !0),
        r.registerInput("cutoff", NodeMaterialBlockConnectionPointTypes.Float, !0),
        r
    }
    return e.prototype.getClassName = function() {
        return "DiscardBlock"
    }
    ,
    Object.defineProperty(e.prototype, "value", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cutoff", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._buildBlock = function(t) {
        if (i.prototype._buildBlock.call(this, t),
        t.sharedData.hints.needAlphaTesting = !0,
        !(!this.cutoff.isConnected || !this.value.isConnected))
            return t.compilationString += "if (" + this.value.associatedVariableName + " < " + this.cutoff.associatedVariableName + `) discard;\r
`,
            this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.DiscardBlock", DiscardBlock);
var FrontFacingBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Fragment) || this;
        return r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment),
        r
    }
    return e.prototype.getClassName = function() {
        return "FrontFacingBlock"
    }
    ,
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._buildBlock = function(t) {
        if (i.prototype._buildBlock.call(this, t),
        t.target === NodeMaterialBlockTargets.Vertex)
            throw "FrontFacingBlock must only be used in a fragment shader";
        var r = this._outputs[0];
        return t.compilationString += this._declareOutput(r, t) + ` = gl_FrontFacing ? 1.0 : 0.0;\r
`,
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.FrontFacingBlock", FrontFacingBlock);
var DerivativeBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Fragment) || this;
        return r.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect, !1),
        r.registerOutput("dx", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        r.registerOutput("dy", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        r._outputs[0]._typeConnectionSource = r._inputs[0],
        r._outputs[1]._typeConnectionSource = r._inputs[0],
        r
    }
    return e.prototype.getClassName = function() {
        return "DerivativeBlock"
    }
    ,
    Object.defineProperty(e.prototype, "input", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "dx", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "dy", {
        get: function() {
            return this._outputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = this._outputs[0]
          , n = this._outputs[1];
        return t._emitExtension("derivatives", "#extension GL_OES_standard_derivatives : enable"),
        r.hasEndpoints && (t.compilationString += this._declareOutput(r, t) + (" = dFdx(" + this.input.associatedVariableName + `);\r
`)),
        n.hasEndpoints && (t.compilationString += this._declareOutput(n, t) + (" = dFdy(" + this.input.associatedVariableName + `);\r
`)),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.DerivativeBlock", DerivativeBlock);
var FragCoordBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Fragment) || this;
        return r.registerOutput("xy", NodeMaterialBlockConnectionPointTypes.Vector2, NodeMaterialBlockTargets.Fragment),
        r.registerOutput("xyz", NodeMaterialBlockConnectionPointTypes.Vector3, NodeMaterialBlockTargets.Fragment),
        r.registerOutput("xyzw", NodeMaterialBlockConnectionPointTypes.Vector4, NodeMaterialBlockTargets.Fragment),
        r.registerOutput("x", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment),
        r.registerOutput("y", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment),
        r.registerOutput("z", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment),
        r.registerOutput("w", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment),
        r
    }
    return e.prototype.getClassName = function() {
        return "FragCoordBlock"
    }
    ,
    Object.defineProperty(e.prototype, "xy", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "xyz", {
        get: function() {
            return this._outputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "xyzw", {
        get: function() {
            return this._outputs[2]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "x", {
        get: function() {
            return this._outputs[3]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "y", {
        get: function() {
            return this._outputs[4]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "z", {
        get: function() {
            return this._outputs[5]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[6]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.writeOutputs = function(t) {
        for (var r = "", n = 0, o = this._outputs; n < o.length; n++) {
            var a = o[n];
            a.hasEndpoints && (r += this._declareOutput(a, t) + " = gl_FragCoord." + a.name + `;\r
`)
        }
        return r
    }
    ,
    e.prototype._buildBlock = function(t) {
        if (i.prototype._buildBlock.call(this, t),
        t.target === NodeMaterialBlockTargets.Vertex)
            throw "FragCoordBlock must only be used in a fragment shader";
        return t.compilationString += this.writeOutputs(t),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.FragCoordBlock", FragCoordBlock);
var ScreenSizeBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Fragment) || this;
        return r.registerOutput("xy", NodeMaterialBlockConnectionPointTypes.Vector2, NodeMaterialBlockTargets.Fragment),
        r.registerOutput("x", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment),
        r.registerOutput("y", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment),
        r
    }
    return e.prototype.getClassName = function() {
        return "ScreenSizeBlock"
    }
    ,
    Object.defineProperty(e.prototype, "xy", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "x", {
        get: function() {
            return this._outputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "y", {
        get: function() {
            return this._outputs[2]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.bind = function(t, r, n) {
        var o = this._scene.getEngine();
        t.setFloat2(this._varName, o.getRenderWidth(), o.getRenderHeight())
    }
    ,
    e.prototype.writeOutputs = function(t, r) {
        for (var n = "", o = 0, a = this._outputs; o < a.length; o++) {
            var s = a[o];
            s.hasEndpoints && (n += this._declareOutput(s, t) + " = " + r + "." + s.name + `;\r
`)
        }
        return n
    }
    ,
    e.prototype._buildBlock = function(t) {
        if (i.prototype._buildBlock.call(this, t),
        this._scene = t.sharedData.scene,
        t.target === NodeMaterialBlockTargets.Vertex)
            throw "ScreenSizeBlock must only be used in a fragment shader";
        return t.sharedData.bindableBlocks.push(this),
        this._varName = t._getFreeVariableName("screenSize"),
        t._emitUniformFromString(this._varName, "vec2"),
        t.compilationString += this.writeOutputs(t, this._varName),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.ScreenSizeBlock", ScreenSizeBlock);
var ScreenSpaceBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Fragment) || this;
        return r.registerInput("vector", NodeMaterialBlockConnectionPointTypes.Vector3),
        r.registerInput("worldViewProjection", NodeMaterialBlockConnectionPointTypes.Matrix),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector2),
        r.registerOutput("x", NodeMaterialBlockConnectionPointTypes.Float),
        r.registerOutput("y", NodeMaterialBlockConnectionPointTypes.Float),
        r.inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector4),
        r
    }
    return e.prototype.getClassName = function() {
        return "ScreenSpaceBlock"
    }
    ,
    Object.defineProperty(e.prototype, "vector", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "worldViewProjection", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "x", {
        get: function() {
            return this._outputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "y", {
        get: function() {
            return this._outputs[2]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.autoConfigure = function(t) {
        if (!this.worldViewProjection.isConnected) {
            var r = t.getInputBlockByPredicate(function(n) {
                return n.systemValue === NodeMaterialSystemValues.WorldViewProjection
            });
            r || (r = new InputBlock("worldViewProjection"),
            r.setAsSystemValue(NodeMaterialSystemValues.WorldViewProjection)),
            r.output.connectTo(this.worldViewProjection)
        }
    }
    ,
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = this.vector
          , n = this.worldViewProjection;
        if (!!r.connectedPoint) {
            var o = n.associatedVariableName
              , a = t._getFreeVariableName("screenSpaceTemp");
            switch (r.connectedPoint.type) {
            case NodeMaterialBlockConnectionPointTypes.Vector3:
                t.compilationString += "vec4 " + a + " = " + o + " * vec4(" + r.associatedVariableName + `, 1.0);\r
`;
                break;
            case NodeMaterialBlockConnectionPointTypes.Vector4:
                t.compilationString += "vec4 " + a + " = " + o + " * " + r.associatedVariableName + `;\r
`;
                break
            }
            return t.compilationString += a + ".xy /= " + a + ".w;",
            t.compilationString += a + ".xy = " + a + ".xy * 0.5 + vec2(0.5, 0.5);",
            this.output.hasEndpoints && (t.compilationString += this._declareOutput(this.output, t) + (" = " + a + `.xy;\r
`)),
            this.x.hasEndpoints && (t.compilationString += this._declareOutput(this.x, t) + (" = " + a + `.x;\r
`)),
            this.y.hasEndpoints && (t.compilationString += this._declareOutput(this.y, t) + (" = " + a + `.y;\r
`)),
            this
        }
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.ScreenSpaceBlock", ScreenSpaceBlock);
var TwirlBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Fragment) || this;
        return r.registerInput("input", NodeMaterialBlockConnectionPointTypes.Vector2),
        r.registerInput("strength", NodeMaterialBlockConnectionPointTypes.Float),
        r.registerInput("center", NodeMaterialBlockConnectionPointTypes.Vector2),
        r.registerInput("offset", NodeMaterialBlockConnectionPointTypes.Vector2),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector2),
        r.registerOutput("x", NodeMaterialBlockConnectionPointTypes.Float),
        r.registerOutput("y", NodeMaterialBlockConnectionPointTypes.Float),
        r
    }
    return e.prototype.getClassName = function() {
        return "TwirlBlock"
    }
    ,
    Object.defineProperty(e.prototype, "input", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "strength", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "center", {
        get: function() {
            return this._inputs[2]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "offset", {
        get: function() {
            return this._inputs[3]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "x", {
        get: function() {
            return this._outputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "y", {
        get: function() {
            return this._outputs[2]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.autoConfigure = function(t) {
        if (!this.center.isConnected) {
            var r = new InputBlock("center");
            r.value = new Vector2(.5,.5),
            r.output.connectTo(this.center)
        }
        if (!this.strength.isConnected) {
            var n = new InputBlock("strength");
            n.value = 1,
            n.output.connectTo(this.strength)
        }
        if (!this.offset.isConnected) {
            var o = new InputBlock("offset");
            o.value = new Vector2(0,0),
            o.output.connectTo(this.offset)
        }
    }
    ,
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = t._getFreeVariableName("delta")
          , n = t._getFreeVariableName("angle")
          , o = t._getFreeVariableName("x")
          , a = t._getFreeVariableName("y")
          , s = t._getFreeVariableName("result");
        return t.compilationString += `
            vec2 ` + r + " = " + this.input.associatedVariableName + " - " + this.center.associatedVariableName + `;
            float ` + n + " = " + this.strength.associatedVariableName + " * length(" + r + `);
            float ` + o + " = cos(" + n + ") * " + r + ".x - sin(" + n + ") * " + r + `.y;
            float ` + a + " = sin(" + n + ") * " + r + ".x + cos(" + n + ") * " + r + `.y;
            vec2 ` + s + " = vec2(" + o + " + " + this.center.associatedVariableName + ".x + " + this.offset.associatedVariableName + ".x, " + a + " + " + this.center.associatedVariableName + ".y + " + this.offset.associatedVariableName + `.y);
        `,
        this.output.hasEndpoints && (t.compilationString += this._declareOutput(this.output, t) + (" = " + s + `;\r
`)),
        this.x.hasEndpoints && (t.compilationString += this._declareOutput(this.x, t) + (" = " + s + `.x;\r
`)),
        this.y.hasEndpoints && (t.compilationString += this._declareOutput(this.y, t) + (" = " + s + `.y;\r
`)),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.TwirlBlock", TwirlBlock);
var FogBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.VertexAndFragment, !1) || this;
        return r.registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes.Vector4, !1, NodeMaterialBlockTargets.Vertex),
        r.registerInput("view", NodeMaterialBlockConnectionPointTypes.Matrix, !1, NodeMaterialBlockTargets.Vertex),
        r.registerInput("input", NodeMaterialBlockConnectionPointTypes.Color3, !1, NodeMaterialBlockTargets.Fragment),
        r.registerInput("fogColor", NodeMaterialBlockConnectionPointTypes.Color3, !1, NodeMaterialBlockTargets.Fragment),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment),
        r.input.acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color4),
        r.fogColor.acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color4),
        r
    }
    return e.prototype.getClassName = function() {
        return "FogBlock"
    }
    ,
    Object.defineProperty(e.prototype, "worldPosition", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "view", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "input", {
        get: function() {
            return this._inputs[2]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "fogColor", {
        get: function() {
            return this._inputs[3]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.autoConfigure = function(t) {
        if (!this.view.isConnected) {
            var r = t.getInputBlockByPredicate(function(o) {
                return o.systemValue === NodeMaterialSystemValues.View
            });
            r || (r = new InputBlock("view"),
            r.setAsSystemValue(NodeMaterialSystemValues.View)),
            r.output.connectTo(this.view)
        }
        if (!this.fogColor.isConnected) {
            var n = t.getInputBlockByPredicate(function(o) {
                return o.systemValue === NodeMaterialSystemValues.FogColor
            });
            n || (n = new InputBlock("fogColor",void 0,NodeMaterialBlockConnectionPointTypes.Color3),
            n.setAsSystemValue(NodeMaterialSystemValues.FogColor)),
            n.output.connectTo(this.fogColor)
        }
    }
    ,
    e.prototype.prepareDefines = function(t, r, n) {
        var o = t.getScene();
        n.setValue("FOG", r.fogEnabled && MaterialHelper.GetFogState(t, o))
    }
    ,
    e.prototype.bind = function(t, r, n) {
        if (!!n) {
            var o = n.getScene();
            t.setFloat4(this._fogParameters, o.fogMode, o.fogStart, o.fogEnd, o.fogDensity)
        }
    }
    ,
    e.prototype._buildBlock = function(t) {
        if (i.prototype._buildBlock.call(this, t),
        t.target === NodeMaterialBlockTargets.Fragment) {
            t.sharedData.blocksWithDefines.push(this),
            t.sharedData.bindableBlocks.push(this),
            t._emitFunctionFromInclude("fogFragmentDeclaration", "//" + this.name, {
                removeUniforms: !0,
                removeVaryings: !0,
                removeIfDef: !1,
                replaceStrings: [{
                    search: /float CalcFogFactor\(\)/,
                    replace: "float CalcFogFactor(vec3 vFogDistance, vec4 vFogInfos)"
                }]
            });
            var r = t._getFreeVariableName("fog")
              , n = this.input
              , o = this.fogColor;
            this._fogParameters = t._getFreeVariableName("fogParameters");
            var a = this._outputs[0];
            t._emitUniformFromString(this._fogParameters, "vec4"),
            t.compilationString += `#ifdef FOG\r
`,
            t.compilationString += "float " + r + " = CalcFogFactor(" + this._fogDistanceName + ", " + this._fogParameters + `);\r
`,
            t.compilationString += this._declareOutput(a, t) + (" = " + r + " * " + n.associatedVariableName + ".rgb + (1.0 - " + r + ") * " + o.associatedVariableName + `.rgb;\r
`),
            t.compilationString += `#else\r
` + this._declareOutput(a, t) + " =  " + n.associatedVariableName + `.rgb;\r
`,
            t.compilationString += `#endif\r
`
        } else {
            var s = this.worldPosition
              , l = this.view;
            this._fogDistanceName = t._getFreeVariableName("vFogDistance"),
            t._emitVaryingFromString(this._fogDistanceName, "vec3"),
            t.compilationString += this._fogDistanceName + " = (" + l.associatedVariableName + " * " + s.associatedVariableName + `).xyz;\r
`
        }
        return this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.FogBlock", FogBlock);
var LightBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.VertexAndFragment) || this;
        return r._isUnique = !0,
        r.registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes.Vector4, !1, NodeMaterialBlockTargets.Vertex),
        r.registerInput("worldNormal", NodeMaterialBlockConnectionPointTypes.Vector4, !1, NodeMaterialBlockTargets.Fragment),
        r.registerInput("cameraPosition", NodeMaterialBlockConnectionPointTypes.Vector3, !1, NodeMaterialBlockTargets.Fragment),
        r.registerInput("glossiness", NodeMaterialBlockConnectionPointTypes.Float, !0, NodeMaterialBlockTargets.Fragment),
        r.registerInput("glossPower", NodeMaterialBlockConnectionPointTypes.Float, !0, NodeMaterialBlockTargets.Fragment),
        r.registerInput("diffuseColor", NodeMaterialBlockConnectionPointTypes.Color3, !0, NodeMaterialBlockTargets.Fragment),
        r.registerInput("specularColor", NodeMaterialBlockConnectionPointTypes.Color3, !0, NodeMaterialBlockTargets.Fragment),
        r.registerInput("view", NodeMaterialBlockConnectionPointTypes.Matrix, !0),
        r.registerOutput("diffuseOutput", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment),
        r.registerOutput("specularOutput", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment),
        r.registerOutput("shadow", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment),
        r
    }
    return e.prototype.getClassName = function() {
        return "LightBlock"
    }
    ,
    Object.defineProperty(e.prototype, "worldPosition", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "worldNormal", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cameraPosition", {
        get: function() {
            return this._inputs[2]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "glossiness", {
        get: function() {
            return this._inputs[3]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "glossPower", {
        get: function() {
            return this._inputs[4]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "diffuseColor", {
        get: function() {
            return this._inputs[5]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "specularColor", {
        get: function() {
            return this._inputs[6]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "view", {
        get: function() {
            return this._inputs[7]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "diffuseOutput", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "specularOutput", {
        get: function() {
            return this._outputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "shadow", {
        get: function() {
            return this._outputs[2]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.autoConfigure = function(t) {
        if (!this.cameraPosition.isConnected) {
            var r = t.getInputBlockByPredicate(function(n) {
                return n.systemValue === NodeMaterialSystemValues.CameraPosition
            });
            r || (r = new InputBlock("cameraPosition"),
            r.setAsSystemValue(NodeMaterialSystemValues.CameraPosition)),
            r.output.connectTo(this.cameraPosition)
        }
    }
    ,
    e.prototype.prepareDefines = function(t, r, n) {
        if (!!n._areLightsDirty) {
            var o = t.getScene();
            if (!this.light)
                MaterialHelper.PrepareDefinesForLights(o, t, n, !0, r.maxSimultaneousLights);
            else {
                var a = {
                    needNormals: !1,
                    needRebuild: !1,
                    lightmapMode: !1,
                    shadowEnabled: !1,
                    specularEnabled: !1
                };
                MaterialHelper.PrepareDefinesForLight(o, t, this.light, this._lightId, n, !0, a),
                a.needRebuild && n.rebuild()
            }
        }
    }
    ,
    e.prototype.updateUniformsAndSamples = function(t, r, n, o) {
        for (var a = 0; a < r.maxSimultaneousLights && n["LIGHT" + a]; a++) {
            var s = t.uniforms.indexOf("vLightData" + a) >= 0;
            MaterialHelper.PrepareUniformsAndSamplersForLight(a, t.uniforms, t.samplers, n["PROJECTEDLIGHTTEXTURE" + a], o, s)
        }
    }
    ,
    e.prototype.bind = function(t, r, n) {
        if (!!n) {
            var o = n.getScene();
            this.light ? MaterialHelper.BindLight(this.light, this._lightId, o, t, !0) : MaterialHelper.BindLights(o, n, t, !0, r.maxSimultaneousLights)
        }
    }
    ,
    e.prototype._injectVertexCode = function(t) {
        var r = this.worldPosition
          , n = "//" + this.name;
        this.light ? (this._lightId = (t.counters.lightCounter !== void 0 ? t.counters.lightCounter : -1) + 1,
        t.counters.lightCounter = this._lightId,
        t._emitFunctionFromInclude(t.supportUniformBuffers ? "lightVxUboDeclaration" : "lightVxFragmentDeclaration", n, {
            replaceStrings: [{
                search: /{X}/g,
                replace: this._lightId.toString()
            }]
        }, this._lightId.toString())) : (t._emitFunctionFromInclude(t.supportUniformBuffers ? "lightVxUboDeclaration" : "lightVxFragmentDeclaration", n, {
            repeatKey: "maxSimultaneousLights"
        }),
        this._lightId = 0,
        t.sharedData.dynamicUniformBlocks.push(this));
        var o = "v_" + r.associatedVariableName;
        t._emitVaryingFromString(o, "vec4") && (t.compilationString += o + " = " + r.associatedVariableName + `;\r
`),
        this.light ? t.compilationString += t._emitCodeFromInclude("shadowsVertex", n, {
            replaceStrings: [{
                search: /{X}/g,
                replace: this._lightId.toString()
            }, {
                search: /worldPos/g,
                replace: r.associatedVariableName
            }]
        }) : (t.compilationString += "vec4 worldPos = " + r.associatedVariableName + `;\r
`,
        this.view.isConnected && (t.compilationString += "mat4 view = " + this.view.associatedVariableName + `;\r
`),
        t.compilationString += t._emitCodeFromInclude("shadowsVertex", n, {
            repeatKey: "maxSimultaneousLights"
        }))
    }
    ,
    e.prototype._buildBlock = function(t) {
        if (i.prototype._buildBlock.call(this, t),
        t.target !== NodeMaterialBlockTargets.Fragment) {
            this._injectVertexCode(t);
            return
        }
        t.sharedData.forcedBindableBlocks.push(this),
        t.sharedData.blocksWithDefines.push(this);
        var r = "//" + this.name
          , n = this.worldPosition;
        t._emitFunctionFromInclude("helperFunctions", r),
        t._emitFunctionFromInclude("lightsFragmentFunctions", r, {
            replaceStrings: [{
                search: /vPositionW/g,
                replace: "v_" + n.associatedVariableName + ".xyz"
            }]
        }),
        t._emitFunctionFromInclude("shadowsFragmentFunctions", r, {
            replaceStrings: [{
                search: /vPositionW/g,
                replace: "v_" + n.associatedVariableName + ".xyz"
            }]
        }),
        this.light ? t._emitFunctionFromInclude(t.supportUniformBuffers ? "lightUboDeclaration" : "lightFragmentDeclaration", r, {
            replaceStrings: [{
                search: /{X}/g,
                replace: this._lightId.toString()
            }]
        }, this._lightId.toString()) : t._emitFunctionFromInclude(t.supportUniformBuffers ? "lightUboDeclaration" : "lightFragmentDeclaration", r, {
            repeatKey: "maxSimultaneousLights"
        }),
        this._lightId === 0 && (t._registerTempVariable("viewDirectionW") && (t.compilationString += "vec3 viewDirectionW = normalize(" + this.cameraPosition.associatedVariableName + " - " + ("v_" + n.associatedVariableName) + `.xyz);\r
`),
        t.compilationString += `lightingInfo info;\r
`,
        t.compilationString += `float shadow = 1.;\r
`,
        t.compilationString += "float glossiness = " + (this.glossiness.isConnected ? this.glossiness.associatedVariableName : "1.0") + " * " + (this.glossPower.isConnected ? this.glossPower.associatedVariableName : "1024.0") + `;\r
`,
        t.compilationString += `vec3 diffuseBase = vec3(0., 0., 0.);\r
`,
        t.compilationString += `vec3 specularBase = vec3(0., 0., 0.);\r
`,
        t.compilationString += "vec3 normalW = " + this.worldNormal.associatedVariableName + `.xyz;\r
`),
        this.light ? t.compilationString += t._emitCodeFromInclude("lightFragment", r, {
            replaceStrings: [{
                search: /{X}/g,
                replace: this._lightId.toString()
            }]
        }) : t.compilationString += t._emitCodeFromInclude("lightFragment", r, {
            repeatKey: "maxSimultaneousLights"
        });
        var o = this.diffuseOutput
          , a = this.specularOutput;
        return t.compilationString += this._declareOutput(o, t) + (" = diffuseBase" + (this.diffuseColor.isConnected ? " * " + this.diffuseColor.associatedVariableName : "") + `;\r
`),
        a.hasEndpoints && (t.compilationString += this._declareOutput(a, t) + (" = specularBase" + (this.specularColor.isConnected ? " * " + this.specularColor.associatedVariableName : "") + `;\r
`)),
        this.shadow.hasEndpoints && (t.compilationString += this._declareOutput(this.shadow, t) + ` = shadow;\r
`),
        this
    }
    ,
    e.prototype.serialize = function() {
        var t = i.prototype.serialize.call(this);
        return this.light && (t.lightId = this.light.id),
        t
    }
    ,
    e.prototype._deserialize = function(t, r, n) {
        i.prototype._deserialize.call(this, t, r, n),
        t.lightId && (this.light = r.getLightById(t.lightId))
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.LightBlock", LightBlock);
var NodeMaterialConnectionPointCustomObject = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a, s) {
        var l = i.call(this, t, r, n) || this;
        return l._blockType = o,
        l._blockName = a,
        l._nameForCheking = s,
        l._nameForCheking || (l._nameForCheking = t),
        l.needDualDirectionValidation = !0,
        l
    }
    return e.prototype.checkCompatibilityState = function(t) {
        return t instanceof e && t.name === this._nameForCheking ? NodeMaterialConnectionPointCompatibilityStates.Compatible : NodeMaterialConnectionPointCompatibilityStates.TypeIncompatible
    }
    ,
    e.prototype.createCustomInputBlock = function() {
        return [new this._blockType(this._blockName), this.name]
    }
    ,
    e
}(NodeMaterialConnectionPoint)
  , ImageSourceBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.VertexAndFragment) || this;
        return r.registerOutput("source", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject("source",r,NodeMaterialConnectionPointDirection.Output,e,"ImageSourceBlock")),
        r
    }
    return Object.defineProperty(e.prototype, "texture", {
        get: function() {
            return this._texture
        },
        set: function(t) {
            var r = this, n;
            if (this._texture !== t) {
                var o = (n = t == null ? void 0 : t.getScene()) !== null && n !== void 0 ? n : Engine.LastCreatedScene;
                !t && o && o.markAllMaterialsAsDirty(1, function(a) {
                    return a.hasTexture(r._texture)
                }),
                this._texture = t,
                t && o && o.markAllMaterialsAsDirty(1, function(a) {
                    return a.hasTexture(t)
                })
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "samplerName", {
        get: function() {
            return this._samplerName
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.bind = function(t, r, n) {
        !this.texture || t.setTexture(this._samplerName, this.texture)
    }
    ,
    e.prototype.isReady = function() {
        return !(this.texture && !this.texture.isReadyOrNotBlocking())
    }
    ,
    e.prototype.getClassName = function() {
        return "ImageSourceBlock"
    }
    ,
    Object.defineProperty(e.prototype, "source", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._buildBlock = function(t) {
        return i.prototype._buildBlock.call(this, t),
        t.target === NodeMaterialBlockTargets.Vertex && (this._samplerName = t._getFreeVariableName(this.name + "Sampler"),
        t.sharedData.blockingBlocks.push(this),
        t.sharedData.textureBlocks.push(this),
        t.sharedData.bindableBlocks.push(this)),
        t._emit2DSampler(this._samplerName),
        this
    }
    ,
    e.prototype._dumpPropertiesCode = function() {
        var t = i.prototype._dumpPropertiesCode.call(this);
        return this.texture && (t += this._codeVariableName + '.texture = new BABYLON.Texture("' + this.texture.name + '", null, ' + this.texture.noMipmap + ", " + this.texture.invertY + ", " + this.texture.samplingMode + `);\r
`,
        t += this._codeVariableName + ".texture.wrapU = " + this.texture.wrapU + `;\r
`,
        t += this._codeVariableName + ".texture.wrapV = " + this.texture.wrapV + `;\r
`,
        t += this._codeVariableName + ".texture.uAng = " + this.texture.uAng + `;\r
`,
        t += this._codeVariableName + ".texture.vAng = " + this.texture.vAng + `;\r
`,
        t += this._codeVariableName + ".texture.wAng = " + this.texture.wAng + `;\r
`,
        t += this._codeVariableName + ".texture.uOffset = " + this.texture.uOffset + `;\r
`,
        t += this._codeVariableName + ".texture.vOffset = " + this.texture.vOffset + `;\r
`,
        t += this._codeVariableName + ".texture.uScale = " + this.texture.uScale + `;\r
`,
        t += this._codeVariableName + ".texture.vScale = " + this.texture.vScale + `;\r
`,
        t += this._codeVariableName + ".texture.coordinatesMode = " + this.texture.coordinatesMode + `;\r
`),
        t
    }
    ,
    e.prototype.serialize = function() {
        var t = i.prototype.serialize.call(this);
        return this.texture && !this.texture.isRenderTarget && this.texture.getClassName() !== "VideoTexture" && (t.texture = this.texture.serialize()),
        t
    }
    ,
    e.prototype._deserialize = function(t, r, n) {
        i.prototype._deserialize.call(this, t, r, n),
        t.texture && !NodeMaterial.IgnoreTexturesAtLoadTime && t.texture.url !== void 0 && (n = t.texture.url.indexOf("data:") === 0 ? "" : n,
        this.texture = Texture.Parse(t.texture, r, n))
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.ImageSourceBlock", ImageSourceBlock);
var TextureBlock = function(i) {
    __extends(e, i);
    function e(t, r) {
        r === void 0 && (r = !1);
        var n = i.call(this, t, r ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.VertexAndFragment) || this;
        return n.convertToGammaSpace = !1,
        n.convertToLinearSpace = !1,
        n.disableLevelMultiplication = !1,
        n._fragmentOnly = r,
        n.registerInput("uv", NodeMaterialBlockConnectionPointTypes.Vector2, !1, NodeMaterialBlockTargets.VertexAndFragment),
        n.registerInput("source", NodeMaterialBlockConnectionPointTypes.Object, !0, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject("source",n,NodeMaterialConnectionPointDirection.Input,ImageSourceBlock,"ImageSourceBlock")),
        n.registerOutput("rgba", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Neutral),
        n.registerOutput("rgb", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Neutral),
        n.registerOutput("r", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral),
        n.registerOutput("g", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral),
        n.registerOutput("b", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral),
        n.registerOutput("a", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral),
        n.registerOutput("level", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral),
        n._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector3),
        n._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector4),
        n._inputs[0]._prioritizeVertex = !r,
        n
    }
    return Object.defineProperty(e.prototype, "texture", {
        get: function() {
            var t;
            return this.source.isConnected ? ((t = this.source.connectedPoint) === null || t === void 0 ? void 0 : t.ownerBlock).texture : this._texture
        },
        set: function(t) {
            var r = this, n;
            if (this._texture !== t) {
                var o = (n = t == null ? void 0 : t.getScene()) !== null && n !== void 0 ? n : Engine.LastCreatedScene;
                !t && o && o.markAllMaterialsAsDirty(1, function(a) {
                    return a.hasTexture(r._texture)
                }),
                this._texture = t,
                t && o && o.markAllMaterialsAsDirty(1, function(a) {
                    return a.hasTexture(t)
                })
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "samplerName", {
        get: function() {
            return this._imageSource ? this._imageSource.samplerName : this._samplerName
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "hasImageSource", {
        get: function() {
            return !!this._imageSource
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getClassName = function() {
        return "TextureBlock"
    }
    ,
    Object.defineProperty(e.prototype, "uv", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "source", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "rgba", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "rgb", {
        get: function() {
            return this._outputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "r", {
        get: function() {
            return this._outputs[2]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "g", {
        get: function() {
            return this._outputs[3]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "b", {
        get: function() {
            return this._outputs[4]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "a", {
        get: function() {
            return this._outputs[5]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "level", {
        get: function() {
            return this._outputs[6]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "target", {
        get: function() {
            if (this._fragmentOnly)
                return NodeMaterialBlockTargets.Fragment;
            if (!this.uv.isConnected || this.uv.sourceBlock.isInput)
                return NodeMaterialBlockTargets.VertexAndFragment;
            for (var t = this.uv.connectedPoint; t; ) {
                if (t.target === NodeMaterialBlockTargets.Fragment)
                    return NodeMaterialBlockTargets.Fragment;
                if (t.target === NodeMaterialBlockTargets.Vertex)
                    return NodeMaterialBlockTargets.VertexAndFragment;
                if (t.target === NodeMaterialBlockTargets.Neutral || t.target === NodeMaterialBlockTargets.VertexAndFragment) {
                    var r = t.ownerBlock;
                    if (r.target === NodeMaterialBlockTargets.Fragment)
                        return NodeMaterialBlockTargets.Fragment;
                    t = null;
                    for (var n = 0, o = r.inputs; n < o.length; n++) {
                        var a = o[n];
                        if (a.connectedPoint) {
                            t = a.connectedPoint;
                            break
                        }
                    }
                }
            }
            return NodeMaterialBlockTargets.VertexAndFragment
        },
        set: function(t) {},
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.autoConfigure = function(t) {
        if (!this.uv.isConnected)
            if (t.mode === NodeMaterialModes.PostProcess) {
                var r = t.getBlockByPredicate(function(o) {
                    return o.name === "uv"
                });
                r && r.connectTo(this)
            } else {
                var n = t.mode === NodeMaterialModes.Particle ? "particle_uv" : "uv"
                  , r = t.getInputBlockByPredicate(function(a) {
                    return a.isAttribute && a.name === n
                });
                r || (r = new InputBlock("uv"),
                r.setAsAttribute(n)),
                r.output.connectTo(this.uv)
            }
    }
    ,
    e.prototype.initializeDefines = function(t, r, n, o) {
        !n._areTexturesDirty || this._mainUVDefineName !== void 0 && n.setValue(this._mainUVDefineName, !1, !0)
    }
    ,
    e.prototype.prepareDefines = function(t, r, n) {
        if (!!n._areTexturesDirty) {
            if (!this.texture || !this.texture.getTextureMatrix) {
                this._isMixed && (n.setValue(this._defineName, !1, !0),
                n.setValue(this._mainUVDefineName, !0, !0));
                return
            }
            n.setValue(this._linearDefineName, this.convertToGammaSpace, !0),
            n.setValue(this._gammaDefineName, this.convertToLinearSpace, !0),
            this._isMixed && (this.texture.getTextureMatrix().isIdentityAs3x2() ? (n.setValue(this._defineName, !1, !0),
            n.setValue(this._mainUVDefineName, !0, !0)) : (n.setValue(this._defineName, !0),
            n[this._mainUVDefineName] == null && n.setValue(this._mainUVDefineName, !1, !0)))
        }
    }
    ,
    e.prototype.isReady = function() {
        return !(this.texture && !this.texture.isReadyOrNotBlocking())
    }
    ,
    e.prototype.bind = function(t, r, n) {
        !this.texture || (this._isMixed && (t.setFloat(this._textureInfoName, this.texture.level),
        t.setMatrix(this._textureTransformName, this.texture.getTextureMatrix())),
        this._imageSource || t.setTexture(this._samplerName, this.texture))
    }
    ,
    Object.defineProperty(e.prototype, "_isMixed", {
        get: function() {
            return this.target !== NodeMaterialBlockTargets.Fragment
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._injectVertexCode = function(t) {
        var r = this.uv;
        if (this._defineName = t._getFreeDefineName("UVTRANSFORM"),
        this._mainUVDefineName = "VMAIN" + r.associatedVariableName.toUpperCase(),
        this._mainUVName = "vMain" + r.associatedVariableName,
        this._transformedUVName = t._getFreeVariableName("transformedUV"),
        this._textureTransformName = t._getFreeVariableName("textureTransform"),
        this._textureInfoName = t._getFreeVariableName("textureInfoName"),
        this.level.associatedVariableName = this._textureInfoName,
        t._emitVaryingFromString(this._transformedUVName, "vec2", this._defineName),
        t._emitVaryingFromString(this._mainUVName, "vec2", this._mainUVDefineName),
        t._emitUniformFromString(this._textureTransformName, "mat4", this._defineName),
        t.compilationString += "#ifdef " + this._defineName + `\r
`,
        t.compilationString += this._transformedUVName + " = vec2(" + this._textureTransformName + " * vec4(" + r.associatedVariableName + `.xy, 1.0, 0.0));\r
`,
        t.compilationString += "#elif defined(" + this._mainUVDefineName + `)\r
`,
        t.compilationString += this._mainUVName + " = " + r.associatedVariableName + `.xy;\r
`,
        t.compilationString += `#endif\r
`,
        !!this._outputs.some(function(s) {
            return s.isConnectedInVertexShader
        })) {
            this._writeTextureRead(t, !0);
            for (var n = 0, o = this._outputs; n < o.length; n++) {
                var a = o[n];
                a.hasEndpoints && a.name !== "level" && this._writeOutput(t, a, a.name, !0)
            }
        }
    }
    ,
    e.prototype._generateTextureLookup = function(t) {
        var r = this.samplerName;
        t.compilationString += "#ifdef " + this._defineName + `\r
`,
        t.compilationString += "vec4 " + this._tempTextureRead + " = texture2D(" + r + ", " + this._transformedUVName + `);\r
`,
        t.compilationString += "#elif defined(" + this._mainUVDefineName + `)\r
`,
        t.compilationString += "vec4 " + this._tempTextureRead + " = texture2D(" + r + ", " + (this._mainUVName ? this._mainUVName : this.uv.associatedVariableName) + `);\r
`,
        t.compilationString += `#endif\r
`
    }
    ,
    e.prototype._writeTextureRead = function(t, r) {
        r === void 0 && (r = !1);
        var n = this.uv;
        if (r) {
            if (t.target === NodeMaterialBlockTargets.Fragment)
                return;
            this._generateTextureLookup(t);
            return
        }
        if (this.uv.ownerBlock.target === NodeMaterialBlockTargets.Fragment) {
            t.compilationString += "vec4 " + this._tempTextureRead + " = texture2D(" + this.samplerName + ", " + n.associatedVariableName + `);\r
`;
            return
        }
        this._generateTextureLookup(t)
    }
    ,
    e.prototype._generateConversionCode = function(t, r, n) {
        n !== "a" && ((!this.texture || !this.texture.gammaSpace) && (t.compilationString += "#ifdef " + this._linearDefineName + `
                    ` + r.associatedVariableName + " = toGammaSpace(" + r.associatedVariableName + `);
                    #endif
                `),
        (!this.texture || this.texture.gammaSpace) && (t.compilationString += "#ifdef " + this._gammaDefineName + `
                    ` + r.associatedVariableName + " = toLinearSpace(" + r.associatedVariableName + `);
                    #endif
                `))
    }
    ,
    e.prototype._writeOutput = function(t, r, n, o) {
        if (o === void 0 && (o = !1),
        o) {
            if (t.target === NodeMaterialBlockTargets.Fragment)
                return;
            t.compilationString += this._declareOutput(r, t) + " = " + this._tempTextureRead + "." + n + `;\r
`,
            this._generateConversionCode(t, r, n);
            return
        }
        if (this.uv.ownerBlock.target === NodeMaterialBlockTargets.Fragment) {
            t.compilationString += this._declareOutput(r, t) + " = " + this._tempTextureRead + "." + n + `;\r
`,
            this._generateConversionCode(t, r, n);
            return
        }
        var a = "";
        this.disableLevelMultiplication || (a = " * " + this._textureInfoName),
        t.compilationString += this._declareOutput(r, t) + " = " + this._tempTextureRead + "." + n + a + `;\r
`,
        this._generateConversionCode(t, r, n)
    }
    ,
    e.prototype._buildBlock = function(t) {
        if (i.prototype._buildBlock.call(this, t),
        this.source.isConnected ? this._imageSource = this.source.connectedPoint.ownerBlock : this._imageSource = null,
        (t.target === NodeMaterialBlockTargets.Vertex || this._fragmentOnly || t.target === NodeMaterialBlockTargets.Fragment && this._tempTextureRead === void 0) && (this._tempTextureRead = t._getFreeVariableName("tempTextureRead"),
        this._linearDefineName = t._getFreeDefineName("ISLINEAR"),
        this._gammaDefineName = t._getFreeDefineName("ISGAMMA")),
        (!this._isMixed && t.target === NodeMaterialBlockTargets.Fragment || this._isMixed && t.target === NodeMaterialBlockTargets.Vertex) && (this._imageSource || (this._samplerName = t._getFreeVariableName(this.name + "Sampler"),
        t._emit2DSampler(this._samplerName)),
        t.sharedData.blockingBlocks.push(this),
        t.sharedData.textureBlocks.push(this),
        t.sharedData.blocksWithDefines.push(this),
        t.sharedData.bindableBlocks.push(this)),
        t.target !== NodeMaterialBlockTargets.Fragment) {
            this._injectVertexCode(t);
            return
        }
        if (!!this._outputs.some(function(s) {
            return s.isConnectedInFragmentShader
        })) {
            this._isMixed && !this._imageSource && t._emit2DSampler(this._samplerName);
            var r = "//" + this.name;
            t._emitFunctionFromInclude("helperFunctions", r),
            this._isMixed && t._emitUniformFromString(this._textureInfoName, "float"),
            this._writeTextureRead(t);
            for (var n = 0, o = this._outputs; n < o.length; n++) {
                var a = o[n];
                a.hasEndpoints && a.name !== "level" && this._writeOutput(t, a, a.name)
            }
            return this
        }
    }
    ,
    e.prototype._dumpPropertiesCode = function() {
        var t = i.prototype._dumpPropertiesCode.call(this);
        return t += this._codeVariableName + ".convertToGammaSpace = " + this.convertToGammaSpace + `;\r
`,
        t += this._codeVariableName + ".convertToLinearSpace = " + this.convertToLinearSpace + `;\r
`,
        t += this._codeVariableName + ".disableLevelMultiplication = " + this.disableLevelMultiplication + `;\r
`,
        this.texture && (t += this._codeVariableName + '.texture = new BABYLON.Texture("' + this.texture.name + '", null, ' + this.texture.noMipmap + ", " + this.texture.invertY + ", " + this.texture.samplingMode + `);\r
`,
        t += this._codeVariableName + ".texture.wrapU = " + this.texture.wrapU + `;\r
`,
        t += this._codeVariableName + ".texture.wrapV = " + this.texture.wrapV + `;\r
`,
        t += this._codeVariableName + ".texture.uAng = " + this.texture.uAng + `;\r
`,
        t += this._codeVariableName + ".texture.vAng = " + this.texture.vAng + `;\r
`,
        t += this._codeVariableName + ".texture.wAng = " + this.texture.wAng + `;\r
`,
        t += this._codeVariableName + ".texture.uOffset = " + this.texture.uOffset + `;\r
`,
        t += this._codeVariableName + ".texture.vOffset = " + this.texture.vOffset + `;\r
`,
        t += this._codeVariableName + ".texture.uScale = " + this.texture.uScale + `;\r
`,
        t += this._codeVariableName + ".texture.vScale = " + this.texture.vScale + `;\r
`,
        t += this._codeVariableName + ".texture.coordinatesMode = " + this.texture.coordinatesMode + `;\r
`),
        t
    }
    ,
    e.prototype.serialize = function() {
        var t = i.prototype.serialize.call(this);
        return t.convertToGammaSpace = this.convertToGammaSpace,
        t.convertToLinearSpace = this.convertToLinearSpace,
        t.fragmentOnly = this._fragmentOnly,
        t.disableLevelMultiplication = this.disableLevelMultiplication,
        !this.hasImageSource && this.texture && !this.texture.isRenderTarget && this.texture.getClassName() !== "VideoTexture" && (t.texture = this.texture.serialize()),
        t
    }
    ,
    e.prototype._deserialize = function(t, r, n) {
        i.prototype._deserialize.call(this, t, r, n),
        this.convertToGammaSpace = t.convertToGammaSpace,
        this.convertToLinearSpace = !!t.convertToLinearSpace,
        this._fragmentOnly = !!t.fragmentOnly,
        this.disableLevelMultiplication = !!t.disableLevelMultiplication,
        t.texture && !NodeMaterial.IgnoreTexturesAtLoadTime && t.texture.url !== void 0 && (n = t.texture.url.indexOf("data:") === 0 ? "" : n,
        this.texture = Texture.Parse(t.texture, r, n))
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.TextureBlock", TextureBlock);
var ReflectionTextureBaseBlock = function(i) {
    __extends(e, i);
    function e(t) {
        return i.call(this, t, NodeMaterialBlockTargets.VertexAndFragment) || this
    }
    return Object.defineProperty(e.prototype, "texture", {
        get: function() {
            return this._texture
        },
        set: function(t) {
            var r = this, n;
            if (this._texture !== t) {
                var o = (n = t == null ? void 0 : t.getScene()) !== null && n !== void 0 ? n : Engine.LastCreatedScene;
                !t && o && o.markAllMaterialsAsDirty(1, function(a) {
                    return a.hasTexture(r._texture)
                }),
                this._texture = t,
                t && o && o.markAllMaterialsAsDirty(1, function(a) {
                    return a.hasTexture(t)
                })
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getClassName = function() {
        return "ReflectionTextureBaseBlock"
    }
    ,
    e.prototype._getTexture = function() {
        return this.texture
    }
    ,
    e.prototype.autoConfigure = function(t) {
        if (!this.position.isConnected) {
            var r = t.getInputBlockByPredicate(function(a) {
                return a.isAttribute && a.name === "position"
            });
            r || (r = new InputBlock("position"),
            r.setAsAttribute()),
            r.output.connectTo(this.position)
        }
        if (!this.world.isConnected) {
            var n = t.getInputBlockByPredicate(function(a) {
                return a.systemValue === NodeMaterialSystemValues.World
            });
            n || (n = new InputBlock("world"),
            n.setAsSystemValue(NodeMaterialSystemValues.World)),
            n.output.connectTo(this.world)
        }
        if (this.view && !this.view.isConnected) {
            var o = t.getInputBlockByPredicate(function(a) {
                return a.systemValue === NodeMaterialSystemValues.View
            });
            o || (o = new InputBlock("view"),
            o.setAsSystemValue(NodeMaterialSystemValues.View)),
            o.output.connectTo(this.view)
        }
    }
    ,
    e.prototype.prepareDefines = function(t, r, n) {
        if (!!n._areTexturesDirty) {
            var o = this._getTexture();
            !o || !o.getTextureMatrix || (n.setValue(this._define3DName, o.isCube, !0),
            n.setValue(this._defineLocalCubicName, !!o.boundingBoxSize, !0),
            n.setValue(this._defineExplicitName, o.coordinatesMode === 0, !0),
            n.setValue(this._defineSkyboxName, o.coordinatesMode === 5, !0),
            n.setValue(this._defineCubicName, o.coordinatesMode === 3 || o.coordinatesMode === 6, !0),
            n.setValue("INVERTCUBICMAP", o.coordinatesMode === 6, !0),
            n.setValue(this._defineSphericalName, o.coordinatesMode === 1, !0),
            n.setValue(this._definePlanarName, o.coordinatesMode === 2, !0),
            n.setValue(this._defineProjectionName, o.coordinatesMode === 4, !0),
            n.setValue(this._defineEquirectangularName, o.coordinatesMode === 7, !0),
            n.setValue(this._defineEquirectangularFixedName, o.coordinatesMode === 8, !0),
            n.setValue(this._defineMirroredEquirectangularFixedName, o.coordinatesMode === 9, !0))
        }
    }
    ,
    e.prototype.isReady = function() {
        var t = this._getTexture();
        return !(t && !t.isReadyOrNotBlocking())
    }
    ,
    e.prototype.bind = function(t, r, n) {
        var o = this._getTexture();
        if (!(!n || !o) && (t.setMatrix(this._reflectionMatrixName, o.getReflectionTextureMatrix()),
        o.isCube ? t.setTexture(this._cubeSamplerName, o) : t.setTexture(this._2DSamplerName, o),
        o.boundingBoxSize)) {
            var a = o;
            t.setVector3(this._reflectionPositionName, a.boundingBoxPosition),
            t.setVector3(this._reflectionSizeName, a.boundingBoxSize)
        }
    }
    ,
    e.prototype.handleVertexSide = function(t) {
        this._define3DName = t._getFreeDefineName("REFLECTIONMAP_3D"),
        this._defineCubicName = t._getFreeDefineName("REFLECTIONMAP_CUBIC"),
        this._defineSphericalName = t._getFreeDefineName("REFLECTIONMAP_SPHERICAL"),
        this._definePlanarName = t._getFreeDefineName("REFLECTIONMAP_PLANAR"),
        this._defineProjectionName = t._getFreeDefineName("REFLECTIONMAP_PROJECTION"),
        this._defineExplicitName = t._getFreeDefineName("REFLECTIONMAP_EXPLICIT"),
        this._defineEquirectangularName = t._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR"),
        this._defineLocalCubicName = t._getFreeDefineName("USE_LOCAL_REFLECTIONMAP_CUBIC"),
        this._defineMirroredEquirectangularFixedName = t._getFreeDefineName("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"),
        this._defineEquirectangularFixedName = t._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR_FIXED"),
        this._defineSkyboxName = t._getFreeDefineName("REFLECTIONMAP_SKYBOX"),
        this._defineOppositeZ = t._getFreeDefineName("REFLECTIONMAP_OPPOSITEZ"),
        this._reflectionMatrixName = t._getFreeVariableName("reflectionMatrix"),
        t._emitUniformFromString(this._reflectionMatrixName, "mat4");
        var r = ""
          , n = "v_" + this.worldPosition.associatedVariableName;
        return t._emitVaryingFromString(n, "vec4") && (r += n + " = " + this.worldPosition.associatedVariableName + `;\r
`),
        this._positionUVWName = t._getFreeVariableName("positionUVW"),
        this._directionWName = t._getFreeVariableName("directionW"),
        t._emitVaryingFromString(this._positionUVWName, "vec3", this._defineSkyboxName) && (r += "#ifdef " + this._defineSkyboxName + `\r
`,
        r += this._positionUVWName + " = " + this.position.associatedVariableName + `.xyz;\r
`,
        r += `#endif\r
`),
        t._emitVaryingFromString(this._directionWName, "vec3", "defined(" + this._defineEquirectangularFixedName + ") || defined(" + this._defineMirroredEquirectangularFixedName + ")") && (r += "#if defined(" + this._defineEquirectangularFixedName + ") || defined(" + this._defineMirroredEquirectangularFixedName + `)\r
`,
        r += this._directionWName + " = normalize(vec3(" + this.world.associatedVariableName + " * vec4(" + this.position.associatedVariableName + `.xyz, 0.0)));\r
`,
        r += `#endif\r
`),
        r
    }
    ,
    e.prototype.handleFragmentSideInits = function(t) {
        t.sharedData.blockingBlocks.push(this),
        t.sharedData.textureBlocks.push(this),
        this._cubeSamplerName = t._getFreeVariableName(this.name + "CubeSampler"),
        t.samplers.push(this._cubeSamplerName),
        this._2DSamplerName = t._getFreeVariableName(this.name + "2DSampler"),
        t.samplers.push(this._2DSamplerName),
        t._samplerDeclaration += "#ifdef " + this._define3DName + `\r
`,
        t._samplerDeclaration += "uniform samplerCube " + this._cubeSamplerName + `;\r
`,
        t._samplerDeclaration += `#else\r
`,
        t._samplerDeclaration += "uniform sampler2D " + this._2DSamplerName + `;\r
`,
        t._samplerDeclaration += `#endif\r
`,
        t.sharedData.blocksWithDefines.push(this),
        t.sharedData.bindableBlocks.push(this);
        var r = "//" + this.name;
        t._emitFunction("ReciprocalPI", "#define RECIPROCAL_PI2 0.15915494", ""),
        t._emitFunctionFromInclude("helperFunctions", r),
        t._emitFunctionFromInclude("reflectionFunction", r, {
            replaceStrings: [{
                search: /vec3 computeReflectionCoords/g,
                replace: "void DUMMYFUNC"
            }]
        }),
        this._reflectionColorName = t._getFreeVariableName("reflectionColor"),
        this._reflectionVectorName = t._getFreeVariableName("reflectionUVW"),
        this._reflectionCoordsName = t._getFreeVariableName("reflectionCoords"),
        this._reflectionPositionName = t._getFreeVariableName("vReflectionPosition"),
        t._emitUniformFromString(this._reflectionPositionName, "vec3"),
        this._reflectionSizeName = t._getFreeVariableName("vReflectionPosition"),
        t._emitUniformFromString(this._reflectionSizeName, "vec3")
    }
    ,
    e.prototype.handleFragmentSideCodeReflectionCoords = function(t, r, n) {
        n === void 0 && (n = !1),
        r || (r = "v_" + this.worldPosition.associatedVariableName);
        var o = this._reflectionMatrixName
          , a = "normalize(" + this._directionWName + ")"
          , s = "" + this._positionUVWName
          , l = "" + this.cameraPosition.associatedVariableName
          , u = "" + this.view.associatedVariableName;
        t += ".xyz";
        var c = `
            #ifdef ` + this._defineMirroredEquirectangularFixedName + `
                vec3 ` + this._reflectionVectorName + " = computeMirroredFixedEquirectangularCoords(" + r + ", " + t + ", " + a + `);
            #endif

            #ifdef ` + this._defineEquirectangularFixedName + `
                vec3 ` + this._reflectionVectorName + " = computeFixedEquirectangularCoords(" + r + ", " + t + ", " + a + `);
            #endif

            #ifdef ` + this._defineEquirectangularName + `
                vec3 ` + this._reflectionVectorName + " = computeEquirectangularCoords(" + r + ", " + t + ", " + l + ".xyz, " + o + `);
            #endif

            #ifdef ` + this._defineSphericalName + `
                vec3 ` + this._reflectionVectorName + " = computeSphericalCoords(" + r + ", " + t + ", " + u + ", " + o + `);
            #endif

            #ifdef ` + this._definePlanarName + `
                vec3 ` + this._reflectionVectorName + " = computePlanarCoords(" + r + ", " + t + ", " + l + ".xyz, " + o + `);
            #endif

            #ifdef ` + this._defineCubicName + `
                #ifdef ` + this._defineLocalCubicName + `
                    vec3 ` + this._reflectionVectorName + " = computeCubicLocalCoords(" + r + ", " + t + ", " + l + ".xyz, " + o + ", " + this._reflectionSizeName + ", " + this._reflectionPositionName + `);
                #else
                vec3 ` + this._reflectionVectorName + " = computeCubicCoords(" + r + ", " + t + ", " + l + ".xyz, " + o + `);
                #endif
            #endif

            #ifdef ` + this._defineProjectionName + `
                vec3 ` + this._reflectionVectorName + " = computeProjectionCoords(" + r + ", " + u + ", " + o + `);
            #endif

            #ifdef ` + this._defineSkyboxName + `
                vec3 ` + this._reflectionVectorName + " = computeSkyBoxCoords(" + s + ", " + o + `);
            #endif

            #ifdef ` + this._defineExplicitName + `
                vec3 ` + this._reflectionVectorName + ` = vec3(0, 0, 0);
            #endif

            #ifdef ` + this._defineOppositeZ + `
                ` + this._reflectionVectorName + `.z *= -1.0;
            #endif\r
`;
        return n || (c += `
                #ifdef ` + this._define3DName + `
                    vec3 ` + this._reflectionCoordsName + " = " + this._reflectionVectorName + `;
                #else
                    vec2 ` + this._reflectionCoordsName + " = " + this._reflectionVectorName + `.xy;
                    #ifdef ` + this._defineProjectionName + `
                        ` + this._reflectionCoordsName + " /= " + this._reflectionVectorName + `.z;
                    #endif
                    ` + this._reflectionCoordsName + ".y = 1.0 - " + this._reflectionCoordsName + `.y;
                #endif\r
`),
        c
    }
    ,
    e.prototype.handleFragmentSideCodeReflectionColor = function(t, r) {
        r === void 0 && (r = ".rgb");
        var n = "vec" + (r.length === 0 ? "4" : r.length - 1)
          , o = n + " " + this._reflectionColorName + `;
            #ifdef ` + this._define3DName + `\r
`;
        return t ? o += this._reflectionColorName + " = textureCubeLodEXT(" + this._cubeSamplerName + ", " + this._reflectionVectorName + ", " + t + ")" + r + `;\r
` : o += this._reflectionColorName + " = textureCube(" + this._cubeSamplerName + ", " + this._reflectionVectorName + ")" + r + `;\r
`,
        o += `
            #else\r
`,
        t ? o += this._reflectionColorName + " = texture2DLodEXT(" + this._2DSamplerName + ", " + this._reflectionCoordsName + ", " + t + ")" + r + `;\r
` : o += this._reflectionColorName + " = texture2D(" + this._2DSamplerName + ", " + this._reflectionCoordsName + ")" + r + `;\r
`,
        o += `#endif\r
`,
        o
    }
    ,
    e.prototype.writeOutputs = function(t, r) {
        var n = "";
        if (t.target === NodeMaterialBlockTargets.Fragment)
            for (var o = 0, a = this._outputs; o < a.length; o++) {
                var s = a[o];
                s.hasEndpoints && (n += this._declareOutput(s, t) + " = " + r + "." + s.name + `;\r
`)
            }
        return n
    }
    ,
    e.prototype._buildBlock = function(t) {
        return i.prototype._buildBlock.call(this, t),
        this
    }
    ,
    e.prototype._dumpPropertiesCode = function() {
        var t = i.prototype._dumpPropertiesCode.call(this);
        if (!this.texture)
            return t;
        if (this.texture.isCube) {
            var r = this.texture.forcedExtension;
            t += this._codeVariableName + '.texture = new BABYLON.CubeTexture("' + this.texture.name + '", undefined, undefined, ' + this.texture.noMipmap + ", null, undefined, undefined, undefined, " + this.texture._prefiltered + ", " + (r ? '"' + r + '"' : "null") + `);\r
`
        } else
            t += this._codeVariableName + '.texture = new BABYLON.Texture("' + this.texture.name + `", null);\r
`;
        return t += this._codeVariableName + ".texture.coordinatesMode = " + this.texture.coordinatesMode + `;\r
`,
        t
    }
    ,
    e.prototype.serialize = function() {
        var t = i.prototype.serialize.call(this);
        return this.texture && !this.texture.isRenderTarget && (t.texture = this.texture.serialize()),
        t
    }
    ,
    e.prototype._deserialize = function(t, r, n) {
        i.prototype._deserialize.call(this, t, r, n),
        t.texture && (n = t.texture.url.indexOf("data:") === 0 ? "" : n,
        t.texture.isCube ? this.texture = CubeTexture.Parse(t.texture, r, n) : this.texture = Texture.Parse(t.texture, r, n))
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.ReflectionTextureBaseBlock", ReflectionTextureBaseBlock);
var ReflectionTextureBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t) || this;
        return r.registerInput("position", NodeMaterialBlockConnectionPointTypes.Vector3, !1, NodeMaterialBlockTargets.Vertex),
        r.registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes.Vector4, !1, NodeMaterialBlockTargets.Vertex),
        r.registerInput("worldNormal", NodeMaterialBlockConnectionPointTypes.Vector4, !1, NodeMaterialBlockTargets.Fragment),
        r.registerInput("world", NodeMaterialBlockConnectionPointTypes.Matrix, !1, NodeMaterialBlockTargets.Vertex),
        r.registerInput("cameraPosition", NodeMaterialBlockConnectionPointTypes.Vector3, !1, NodeMaterialBlockTargets.Fragment),
        r.registerInput("view", NodeMaterialBlockConnectionPointTypes.Matrix, !1, NodeMaterialBlockTargets.Fragment),
        r.registerOutput("rgb", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment),
        r.registerOutput("rgba", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Fragment),
        r.registerOutput("r", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment),
        r.registerOutput("g", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment),
        r.registerOutput("b", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment),
        r.registerOutput("a", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment),
        r._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector4),
        r
    }
    return e.prototype.getClassName = function() {
        return "ReflectionTextureBlock"
    }
    ,
    Object.defineProperty(e.prototype, "position", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "worldPosition", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "worldNormal", {
        get: function() {
            return this._inputs[2]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "world", {
        get: function() {
            return this._inputs[3]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cameraPosition", {
        get: function() {
            return this._inputs[4]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "view", {
        get: function() {
            return this._inputs[5]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "rgb", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "rgba", {
        get: function() {
            return this._outputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "r", {
        get: function() {
            return this._outputs[2]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "g", {
        get: function() {
            return this._outputs[3]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "b", {
        get: function() {
            return this._outputs[4]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "a", {
        get: function() {
            return this._outputs[5]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.autoConfigure = function(t) {
        if (i.prototype.autoConfigure.call(this, t),
        !this.cameraPosition.isConnected) {
            var r = t.getInputBlockByPredicate(function(n) {
                return n.systemValue === NodeMaterialSystemValues.CameraPosition
            });
            r || (r = new InputBlock("cameraPosition"),
            r.setAsSystemValue(NodeMaterialSystemValues.CameraPosition)),
            r.output.connectTo(this.cameraPosition)
        }
    }
    ,
    e.prototype._buildBlock = function(t) {
        if (i.prototype._buildBlock.call(this, t),
        !this.texture)
            return t.compilationString += this.writeOutputs(t, "vec3(0.)"),
            this;
        if (t.target !== NodeMaterialBlockTargets.Fragment)
            return t.compilationString += this.handleVertexSide(t),
            this;
        this.handleFragmentSideInits(t);
        var r = t._getFreeVariableName("normalWUnit");
        return t.compilationString += "vec4 " + r + " = normalize(" + this.worldNormal.associatedVariableName + `);\r
`,
        t.compilationString += this.handleFragmentSideCodeReflectionCoords(r),
        t.compilationString += this.handleFragmentSideCodeReflectionColor(void 0, ""),
        t.compilationString += this.writeOutputs(t, this._reflectionColorName),
        this
    }
    ,
    e
}(ReflectionTextureBaseBlock);
RegisterClass("BABYLON.ReflectionTextureBlock", ReflectionTextureBlock);
var SceneDepthBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.VertexAndFragment) || this;
        return r._samplerName = "textureSampler",
        r.useNonLinearDepth = !1,
        r.force32itsFloat = !1,
        r._isUnique = !0,
        r.registerInput("uv", NodeMaterialBlockConnectionPointTypes.Vector2, !1, NodeMaterialBlockTargets.VertexAndFragment),
        r.registerOutput("depth", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral),
        r._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector3),
        r._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector4),
        r._inputs[0]._prioritizeVertex = !1,
        r
    }
    return e.prototype.getClassName = function() {
        return "SceneDepthBlock"
    }
    ,
    Object.defineProperty(e.prototype, "uv", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "depth", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.initialize = function(t) {
        t._excludeVariableName("textureSampler")
    }
    ,
    Object.defineProperty(e.prototype, "target", {
        get: function() {
            return !this.uv.isConnected || this.uv.sourceBlock.isInput ? NodeMaterialBlockTargets.VertexAndFragment : NodeMaterialBlockTargets.Fragment
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._getTexture = function(t) {
        var r = t.enableDepthRenderer(void 0, this.useNonLinearDepth, this.force32itsFloat);
        return r.getDepthMap()
    }
    ,
    e.prototype.bind = function(t, r, n) {
        var o = this._getTexture(r.getScene());
        t.setTexture(this._samplerName, o)
    }
    ,
    e.prototype._injectVertexCode = function(t) {
        var r = this.uv;
        if (r.connectedPoint.ownerBlock.isInput) {
            var n = r.connectedPoint.ownerBlock;
            n.isAttribute || t._emitUniformFromString(r.associatedVariableName, "vec" + (r.type === NodeMaterialBlockConnectionPointTypes.Vector3 ? "3" : r.type === NodeMaterialBlockConnectionPointTypes.Vector4 ? "4" : "2"))
        }
        if (this._mainUVName = "vMain" + r.associatedVariableName,
        t._emitVaryingFromString(this._mainUVName, "vec2"),
        t.compilationString += this._mainUVName + " = " + r.associatedVariableName + `.xy;\r
`,
        !!this._outputs.some(function(l) {
            return l.isConnectedInVertexShader
        })) {
            this._writeTextureRead(t, !0);
            for (var o = 0, a = this._outputs; o < a.length; o++) {
                var s = a[o];
                s.hasEndpoints && this._writeOutput(t, s, "r", !0)
            }
        }
    }
    ,
    e.prototype._writeTextureRead = function(t, r) {
        r === void 0 && (r = !1);
        var n = this.uv;
        if (r) {
            if (t.target === NodeMaterialBlockTargets.Fragment)
                return;
            t.compilationString += "vec4 " + this._tempTextureRead + " = texture2D(" + this._samplerName + ", " + n.associatedVariableName + `.xy);\r
`;
            return
        }
        if (this.uv.ownerBlock.target === NodeMaterialBlockTargets.Fragment) {
            t.compilationString += "vec4 " + this._tempTextureRead + " = texture2D(" + this._samplerName + ", " + n.associatedVariableName + `.xy);\r
`;
            return
        }
        t.compilationString += "vec4 " + this._tempTextureRead + " = texture2D(" + this._samplerName + ", " + this._mainUVName + `);\r
`
    }
    ,
    e.prototype._writeOutput = function(t, r, n, o) {
        if (o === void 0 && (o = !1),
        o) {
            if (t.target === NodeMaterialBlockTargets.Fragment)
                return;
            t.compilationString += this._declareOutput(r, t) + " = " + this._tempTextureRead + "." + n + `;\r
`;
            return
        }
        if (this.uv.ownerBlock.target === NodeMaterialBlockTargets.Fragment) {
            t.compilationString += this._declareOutput(r, t) + " = " + this._tempTextureRead + "." + n + `;\r
`;
            return
        }
        t.compilationString += this._declareOutput(r, t) + " = " + this._tempTextureRead + "." + n + `;\r
`
    }
    ,
    e.prototype._buildBlock = function(t) {
        if (i.prototype._buildBlock.call(this, t),
        this._tempTextureRead = t._getFreeVariableName("tempTextureRead"),
        t.sharedData.bindableBlocks.indexOf(this) < 0 && t.sharedData.bindableBlocks.push(this),
        t.target !== NodeMaterialBlockTargets.Fragment) {
            t._emit2DSampler(this._samplerName),
            this._injectVertexCode(t);
            return
        }
        if (!!this._outputs.some(function(a) {
            return a.isConnectedInFragmentShader
        })) {
            t._emit2DSampler(this._samplerName),
            this._writeTextureRead(t);
            for (var r = 0, n = this._outputs; r < n.length; r++) {
                var o = n[r];
                o.hasEndpoints && this._writeOutput(t, o, "r")
            }
            return this
        }
    }
    ,
    e.prototype.serialize = function() {
        var t = i.prototype.serialize.call(this);
        return t.useNonLinearDepth = this.useNonLinearDepth,
        t.force32itsFloat = this.force32itsFloat,
        t
    }
    ,
    e.prototype._deserialize = function(t, r, n) {
        i.prototype._deserialize.call(this, t, r, n),
        this.useNonLinearDepth = t.useNonLinearDepth,
        this.force32itsFloat = t.force32itsFloat
    }
    ,
    __decorate([editableInPropertyPage("Use non linear depth", PropertyTypeForEdition.Boolean, "ADVANCED", {
        notifiers: {
            activatePreviewCommand: !0,
            callback: function(t) {
                return t.disableDepthRenderer()
            }
        }
    })], e.prototype, "useNonLinearDepth", void 0),
    __decorate([editableInPropertyPage("Force 32 bits float", PropertyTypeForEdition.Boolean, "ADVANCED", {
        notifiers: {
            activatePreviewCommand: !0,
            callback: function(t) {
                return t.disableDepthRenderer()
            }
        }
    })], e.prototype, "force32itsFloat", void 0),
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.SceneDepthBlock", SceneDepthBlock);
var AddBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Neutral) || this;
        return r.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        r.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        r._outputs[0]._typeConnectionSource = r._inputs[0],
        r._linkConnectionTypes(0, 1),
        r
    }
    return e.prototype.getClassName = function() {
        return "AddBlock"
    }
    ,
    Object.defineProperty(e.prototype, "left", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "right", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = this._outputs[0];
        return t.compilationString += this._declareOutput(r, t) + (" = " + this.left.associatedVariableName + " + " + this.right.associatedVariableName + `;\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.AddBlock", AddBlock);
var ScaleBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Neutral) || this;
        return r.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        r.registerInput("factor", NodeMaterialBlockConnectionPointTypes.Float),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        r._outputs[0]._typeConnectionSource = r._inputs[0],
        r
    }
    return e.prototype.getClassName = function() {
        return "ScaleBlock"
    }
    ,
    Object.defineProperty(e.prototype, "input", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "factor", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = this._outputs[0];
        return t.compilationString += this._declareOutput(r, t) + (" = " + this.input.associatedVariableName + " * " + this.factor.associatedVariableName + `;\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.ScaleBlock", ScaleBlock);
var ClampBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Neutral) || this;
        return r.minimum = 0,
        r.maximum = 1,
        r.registerInput("value", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        r._outputs[0]._typeConnectionSource = r._inputs[0],
        r
    }
    return e.prototype.getClassName = function() {
        return "ClampBlock"
    }
    ,
    Object.defineProperty(e.prototype, "value", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = this._outputs[0];
        return t.compilationString += this._declareOutput(r, t) + (" = clamp(" + this.value.associatedVariableName + ", " + this._writeFloat(this.minimum) + ", " + this._writeFloat(this.maximum) + `);\r
`),
        this
    }
    ,
    e.prototype._dumpPropertiesCode = function() {
        var t = i.prototype._dumpPropertiesCode.call(this) + (this._codeVariableName + ".minimum = " + this.minimum + `;\r
`);
        return t += this._codeVariableName + ".maximum = " + this.maximum + `;\r
`,
        t
    }
    ,
    e.prototype.serialize = function() {
        var t = i.prototype.serialize.call(this);
        return t.minimum = this.minimum,
        t.maximum = this.maximum,
        t
    }
    ,
    e.prototype._deserialize = function(t, r, n) {
        i.prototype._deserialize.call(this, t, r, n),
        this.minimum = t.minimum,
        this.maximum = t.maximum
    }
    ,
    __decorate([editableInPropertyPage("Minimum", PropertyTypeForEdition.Float)], e.prototype, "minimum", void 0),
    __decorate([editableInPropertyPage("Maximum", PropertyTypeForEdition.Float)], e.prototype, "maximum", void 0),
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.ClampBlock", ClampBlock);
var CrossBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Neutral) || this;
        return r.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        r.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector3),
        r._linkConnectionTypes(0, 1),
        r._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float),
        r._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix),
        r._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector2),
        r._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float),
        r._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix),
        r._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector2),
        r
    }
    return e.prototype.getClassName = function() {
        return "CrossBlock"
    }
    ,
    Object.defineProperty(e.prototype, "left", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "right", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = this._outputs[0];
        return t.compilationString += this._declareOutput(r, t) + (" = cross(" + this.left.associatedVariableName + ".xyz, " + this.right.associatedVariableName + `.xyz);\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.CrossBlock", CrossBlock);
var CustomBlock = function(i) {
    __extends(e, i);
    function e(t) {
        return i.call(this, t) || this
    }
    return Object.defineProperty(e.prototype, "options", {
        get: function() {
            return this._options
        },
        set: function(t) {
            this._deserializeOptions(t)
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getClassName = function() {
        return "CustomBlock"
    }
    ,
    e.prototype._buildBlock = function(t) {
        var r = this;
        i.prototype._buildBlock.call(this, t);
        var n = this._code
          , o = this._options.functionName;
        this._inputs.forEach(function(s) {
            var l = new RegExp("\\{TYPE_" + s.name + "\\}","gm")
              , u = t._getGLType(s.type);
            n = n.replace(l, u),
            o = o.replace(l, u)
        }),
        this._outputs.forEach(function(s) {
            var l = new RegExp("\\{TYPE_" + s.name + "\\}","gm")
              , u = t._getGLType(s.type);
            n = n.replace(l, u),
            o = o.replace(l, u)
        }),
        t._emitFunction(o, n, ""),
        this._outputs.forEach(function(s) {
            t.compilationString += r._declareOutput(s, t) + `;\r
`
        }),
        t.compilationString += o + "(";
        var a = !1;
        return this._inputs.forEach(function(s, l) {
            l > 0 && (t.compilationString += ", "),
            t.compilationString += s.associatedVariableName,
            a = !0
        }),
        this._outputs.forEach(function(s, l) {
            (l > 0 || a) && (t.compilationString += ", "),
            t.compilationString += s.associatedVariableName
        }),
        t.compilationString += `);\r
`,
        this
    }
    ,
    e.prototype._dumpPropertiesCode = function() {
        var t = i.prototype._dumpPropertiesCode.call(this);
        return t += this._codeVariableName + ".options = " + JSON.stringify(this._options) + `;\r
`,
        t
    }
    ,
    e.prototype.serialize = function() {
        var t = i.prototype.serialize.call(this);
        return t.options = this._options,
        t
    }
    ,
    e.prototype._deserialize = function(t, r, n) {
        this._deserializeOptions(t.options),
        i.prototype._deserialize.call(this, t, r, n)
    }
    ,
    e.prototype._deserializeOptions = function(t) {
        var r = this, n, o, a;
        this._options = t,
        this._code = t.code.join(`\r
`) + `\r
`,
        this.name = this.name || t.name,
        this.target = NodeMaterialBlockTargets[t.target],
        (n = t.inParameters) === null || n === void 0 || n.forEach(function(s, l) {
            var u = NodeMaterialBlockConnectionPointTypes[s.type];
            r.registerInput(s.name, u),
            Object.defineProperty(r, s.name, {
                get: function() {
                    return this._inputs[l]
                },
                enumerable: !0,
                configurable: !0
            })
        }),
        (o = t.outParameters) === null || o === void 0 || o.forEach(function(s, l) {
            r.registerOutput(s.name, NodeMaterialBlockConnectionPointTypes[s.type]),
            Object.defineProperty(r, s.name, {
                get: function() {
                    return this._outputs[l]
                },
                enumerable: !0,
                configurable: !0
            }),
            s.type === "BasedOnInput" && (r._outputs[l]._typeConnectionSource = r._findInputByName(s.typeFromInput)[0])
        }),
        (a = t.inLinkedConnectionTypes) === null || a === void 0 || a.forEach(function(s) {
            r._linkConnectionTypes(r._findInputByName(s.input1)[1], r._findInputByName(s.input2)[1])
        })
    }
    ,
    e.prototype._findInputByName = function(t) {
        if (!t)
            return null;
        for (var r = 0; r < this._inputs.length; r++)
            if (this._inputs[r].name === t)
                return [this._inputs[r], r];
        return null
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.CustomBlock", CustomBlock);
var DotBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Neutral) || this;
        return r.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        r.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float),
        r._linkConnectionTypes(0, 1),
        r._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float),
        r._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix),
        r._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float),
        r._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix),
        r
    }
    return e.prototype.getClassName = function() {
        return "DotBlock"
    }
    ,
    Object.defineProperty(e.prototype, "left", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "right", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = this._outputs[0];
        return t.compilationString += this._declareOutput(r, t) + (" = dot(" + this.left.associatedVariableName + ", " + this.right.associatedVariableName + `);\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.DotBlock", DotBlock);
var NormalizeBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Neutral) || this;
        return r.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        r._outputs[0]._typeConnectionSource = r._inputs[0],
        r._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float),
        r._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix),
        r
    }
    return e.prototype.getClassName = function() {
        return "NormalizeBlock"
    }
    ,
    Object.defineProperty(e.prototype, "input", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = this._outputs[0]
          , n = this._inputs[0];
        return t.compilationString += this._declareOutput(r, t) + (" = normalize(" + n.associatedVariableName + `);\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.NormalizeBlock", NormalizeBlock);
var ColorMergerBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Neutral) || this;
        return r.rSwizzle = "r",
        r.gSwizzle = "g",
        r.bSwizzle = "b",
        r.aSwizzle = "a",
        r.registerInput("rgb ", NodeMaterialBlockConnectionPointTypes.Color3, !0),
        r.registerInput("r", NodeMaterialBlockConnectionPointTypes.Float, !0),
        r.registerInput("g", NodeMaterialBlockConnectionPointTypes.Float, !0),
        r.registerInput("b", NodeMaterialBlockConnectionPointTypes.Float, !0),
        r.registerInput("a", NodeMaterialBlockConnectionPointTypes.Float, !0),
        r.registerOutput("rgba", NodeMaterialBlockConnectionPointTypes.Color4),
        r.registerOutput("rgb", NodeMaterialBlockConnectionPointTypes.Color3),
        r
    }
    return e.prototype.getClassName = function() {
        return "ColorMergerBlock"
    }
    ,
    Object.defineProperty(e.prototype, "rgbIn", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "r", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "g", {
        get: function() {
            return this._inputs[2]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "b", {
        get: function() {
            return this._inputs[3]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "a", {
        get: function() {
            return this._inputs[4]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "rgba", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "rgbOut", {
        get: function() {
            return this._outputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "rgb", {
        get: function() {
            return this.rgbOut
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._inputRename = function(t) {
        return t === "rgb " ? "rgbIn" : t
    }
    ,
    e.prototype._buildSwizzle = function(t) {
        var r = this.rSwizzle + this.gSwizzle + this.bSwizzle + this.aSwizzle;
        return "." + r.substr(0, t)
    }
    ,
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = this.r
          , n = this.g
          , o = this.b
          , a = this.a
          , s = this.rgbIn
          , l = this._outputs[0]
          , u = this._outputs[1];
        return s.isConnected ? (l.hasEndpoints && (t.compilationString += this._declareOutput(l, t) + (" = vec4(" + s.associatedVariableName + ", " + (a.isConnected ? this._writeVariable(a) : "0.0") + ")" + this._buildSwizzle(4) + `;\r
`)),
        u.hasEndpoints && (t.compilationString += this._declareOutput(u, t) + (" = " + s.associatedVariableName + this._buildSwizzle(3) + `;\r
`))) : (l.hasEndpoints && (t.compilationString += this._declareOutput(l, t) + (" = vec4(" + (r.isConnected ? this._writeVariable(r) : "0.0") + ", " + (n.isConnected ? this._writeVariable(n) : "0.0") + ", " + (o.isConnected ? this._writeVariable(o) : "0.0") + ", " + (a.isConnected ? this._writeVariable(a) : "0.0") + ")" + this._buildSwizzle(4) + `;\r
`)),
        u.hasEndpoints && (t.compilationString += this._declareOutput(u, t) + (" = vec3(" + (r.isConnected ? this._writeVariable(r) : "0.0") + ", " + (n.isConnected ? this._writeVariable(n) : "0.0") + ", " + (o.isConnected ? this._writeVariable(o) : "0.0") + ")" + this._buildSwizzle(3) + `;\r
`))),
        this
    }
    ,
    e.prototype.serialize = function() {
        var t = i.prototype.serialize.call(this);
        return t.rSwizzle = this.rSwizzle,
        t.gSwizzle = this.gSwizzle,
        t.bSwizzle = this.bSwizzle,
        t.aSwizzle = this.aSwizzle,
        t
    }
    ,
    e.prototype._deserialize = function(t, r, n) {
        var o, a, s, l;
        i.prototype._deserialize.call(this, t, r, n),
        this.rSwizzle = (o = t.rSwizzle) !== null && o !== void 0 ? o : "r",
        this.gSwizzle = (a = t.gSwizzle) !== null && a !== void 0 ? a : "g",
        this.bSwizzle = (s = t.bSwizzle) !== null && s !== void 0 ? s : "b",
        this.aSwizzle = (l = t.aSwizzle) !== null && l !== void 0 ? l : "a"
    }
    ,
    e.prototype._dumpPropertiesCode = function() {
        var t = i.prototype._dumpPropertiesCode.call(this);
        return t += this._codeVariableName + ".rSwizzle = " + this.rSwizzle + `};\r
`,
        t += this._codeVariableName + ".gSwizzle = " + this.gSwizzle + `};\r
`,
        t += this._codeVariableName + ".bSwizzle = " + this.bSwizzle + `};\r
`,
        t += this._codeVariableName + ".aSwizzle = " + this.aSwizzle + `};\r
`,
        t
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.ColorMergerBlock", ColorMergerBlock);
var VectorSplitterBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Neutral) || this;
        return r.registerInput("xyzw", NodeMaterialBlockConnectionPointTypes.Vector4, !0),
        r.registerInput("xyz ", NodeMaterialBlockConnectionPointTypes.Vector3, !0),
        r.registerInput("xy ", NodeMaterialBlockConnectionPointTypes.Vector2, !0),
        r.registerOutput("xyz", NodeMaterialBlockConnectionPointTypes.Vector3),
        r.registerOutput("xy", NodeMaterialBlockConnectionPointTypes.Vector2),
        r.registerOutput("zw", NodeMaterialBlockConnectionPointTypes.Vector2),
        r.registerOutput("x", NodeMaterialBlockConnectionPointTypes.Float),
        r.registerOutput("y", NodeMaterialBlockConnectionPointTypes.Float),
        r.registerOutput("z", NodeMaterialBlockConnectionPointTypes.Float),
        r.registerOutput("w", NodeMaterialBlockConnectionPointTypes.Float),
        r.inputsAreExclusive = !0,
        r
    }
    return e.prototype.getClassName = function() {
        return "VectorSplitterBlock"
    }
    ,
    Object.defineProperty(e.prototype, "xyzw", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "xyzIn", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "xyIn", {
        get: function() {
            return this._inputs[2]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "xyzOut", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "xyOut", {
        get: function() {
            return this._outputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "zw", {
        get: function() {
            return this._outputs[2]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "x", {
        get: function() {
            return this._outputs[3]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "y", {
        get: function() {
            return this._outputs[4]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "z", {
        get: function() {
            return this._outputs[5]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "w", {
        get: function() {
            return this._outputs[6]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._inputRename = function(t) {
        switch (t) {
        case "xy ":
            return "xyIn";
        case "xyz ":
            return "xyzIn";
        default:
            return t
        }
    }
    ,
    e.prototype._outputRename = function(t) {
        switch (t) {
        case "xy":
            return "xyOut";
        case "xyz":
            return "xyzOut";
        default:
            return t
        }
    }
    ,
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = this.xyzw.isConnected ? this.xyzw : this.xyzIn.isConnected ? this.xyzIn : this.xyIn
          , n = this._outputs[0]
          , o = this._outputs[1]
          , a = this._outputs[2]
          , s = this._outputs[3]
          , l = this._outputs[4]
          , u = this._outputs[5]
          , c = this._outputs[6];
        return n.hasEndpoints && (r === this.xyIn ? t.compilationString += this._declareOutput(n, t) + (" = vec3(" + r.associatedVariableName + `, 0.0);\r
`) : t.compilationString += this._declareOutput(n, t) + (" = " + r.associatedVariableName + `.xyz;\r
`)),
        a.hasEndpoints && this.xyzw.isConnected && (t.compilationString += this._declareOutput(a, t) + (" = " + this.xyzw.associatedVariableName + `.zw;\r
`)),
        o.hasEndpoints && (t.compilationString += this._declareOutput(o, t) + (" = " + r.associatedVariableName + `.xy;\r
`)),
        s.hasEndpoints && (t.compilationString += this._declareOutput(s, t) + (" = " + r.associatedVariableName + `.x;\r
`)),
        l.hasEndpoints && (t.compilationString += this._declareOutput(l, t) + (" = " + r.associatedVariableName + `.y;\r
`)),
        u.hasEndpoints && (t.compilationString += this._declareOutput(u, t) + (" = " + r.associatedVariableName + `.z;\r
`)),
        c.hasEndpoints && (t.compilationString += this._declareOutput(c, t) + (" = " + r.associatedVariableName + `.w;\r
`)),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.VectorSplitterBlock", VectorSplitterBlock);
var LerpBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Neutral) || this;
        return r.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        r.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        r.registerInput("gradient", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        r._outputs[0]._typeConnectionSource = r._inputs[0],
        r._linkConnectionTypes(0, 1),
        r._linkConnectionTypes(1, 2, !0),
        r._inputs[2].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float),
        r
    }
    return e.prototype.getClassName = function() {
        return "LerpBlock"
    }
    ,
    Object.defineProperty(e.prototype, "left", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "right", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "gradient", {
        get: function() {
            return this._inputs[2]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = this._outputs[0];
        return t.compilationString += this._declareOutput(r, t) + (" = mix(" + this.left.associatedVariableName + " , " + this.right.associatedVariableName + ", " + this.gradient.associatedVariableName + `);\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.LerpBlock", LerpBlock);
var DivideBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Neutral) || this;
        return r.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        r.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        r._outputs[0]._typeConnectionSource = r._inputs[0],
        r._linkConnectionTypes(0, 1),
        r
    }
    return e.prototype.getClassName = function() {
        return "DivideBlock"
    }
    ,
    Object.defineProperty(e.prototype, "left", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "right", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = this._outputs[0];
        return t.compilationString += this._declareOutput(r, t) + (" = " + this.left.associatedVariableName + " / " + this.right.associatedVariableName + `;\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.DivideBlock", DivideBlock);
var SubtractBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Neutral) || this;
        return r.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        r.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        r._outputs[0]._typeConnectionSource = r._inputs[0],
        r._linkConnectionTypes(0, 1),
        r
    }
    return e.prototype.getClassName = function() {
        return "SubtractBlock"
    }
    ,
    Object.defineProperty(e.prototype, "left", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "right", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = this._outputs[0];
        return t.compilationString += this._declareOutput(r, t) + (" = " + this.left.associatedVariableName + " - " + this.right.associatedVariableName + `;\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.SubtractBlock", SubtractBlock);
var StepBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Neutral) || this;
        return r.registerInput("value", NodeMaterialBlockConnectionPointTypes.Float),
        r.registerInput("edge", NodeMaterialBlockConnectionPointTypes.Float),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float),
        r
    }
    return e.prototype.getClassName = function() {
        return "StepBlock"
    }
    ,
    Object.defineProperty(e.prototype, "value", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "edge", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = this._outputs[0];
        return t.compilationString += this._declareOutput(r, t) + (" = step(" + this.edge.associatedVariableName + ", " + this.value.associatedVariableName + `);\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.StepBlock", StepBlock);
var OneMinusBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Neutral) || this;
        return r.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        r._outputs[0]._typeConnectionSource = r._inputs[0],
        r._outputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix),
        r
    }
    return e.prototype.getClassName = function() {
        return "OneMinusBlock"
    }
    ,
    Object.defineProperty(e.prototype, "input", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = this._outputs[0];
        return t.compilationString += this._declareOutput(r, t) + (" = 1. - " + this.input.associatedVariableName + `;\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.OneMinusBlock", OneMinusBlock);
RegisterClass("BABYLON.OppositeBlock", OneMinusBlock);
var ViewDirectionBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Neutral) || this;
        return r.registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes.Vector4),
        r.registerInput("cameraPosition", NodeMaterialBlockConnectionPointTypes.Vector3),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector3),
        r
    }
    return e.prototype.getClassName = function() {
        return "ViewDirectionBlock"
    }
    ,
    Object.defineProperty(e.prototype, "worldPosition", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cameraPosition", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.autoConfigure = function(t) {
        if (!this.cameraPosition.isConnected) {
            var r = t.getInputBlockByPredicate(function(n) {
                return n.systemValue === NodeMaterialSystemValues.CameraPosition
            });
            r || (r = new InputBlock("cameraPosition"),
            r.setAsSystemValue(NodeMaterialSystemValues.CameraPosition)),
            r.output.connectTo(this.cameraPosition)
        }
    }
    ,
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = this._outputs[0];
        return t.compilationString += this._declareOutput(r, t) + (" = normalize(" + this.cameraPosition.associatedVariableName + " - " + this.worldPosition.associatedVariableName + `.xyz);\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.ViewDirectionBlock", ViewDirectionBlock);
var FresnelBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Neutral) || this;
        return r.registerInput("worldNormal", NodeMaterialBlockConnectionPointTypes.Vector4),
        r.registerInput("viewDirection", NodeMaterialBlockConnectionPointTypes.Vector3),
        r.registerInput("bias", NodeMaterialBlockConnectionPointTypes.Float),
        r.registerInput("power", NodeMaterialBlockConnectionPointTypes.Float),
        r.registerOutput("fresnel", NodeMaterialBlockConnectionPointTypes.Float),
        r
    }
    return e.prototype.getClassName = function() {
        return "FresnelBlock"
    }
    ,
    Object.defineProperty(e.prototype, "worldNormal", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "viewDirection", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "bias", {
        get: function() {
            return this._inputs[2]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "power", {
        get: function() {
            return this._inputs[3]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "fresnel", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.autoConfigure = function(t) {
        if (!this.viewDirection.isConnected) {
            var r = new ViewDirectionBlock("View direction");
            r.output.connectTo(this.viewDirection),
            r.autoConfigure(t)
        }
        if (!this.bias.isConnected) {
            var n = new InputBlock("bias");
            n.value = 0,
            n.output.connectTo(this.bias)
        }
        if (!this.power.isConnected) {
            var o = new InputBlock("power");
            o.value = 1,
            o.output.connectTo(this.power)
        }
    }
    ,
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = "//" + this.name;
        return t._emitFunctionFromInclude("fresnelFunction", r, {
            removeIfDef: !0
        }),
        t.compilationString += this._declareOutput(this.fresnel, t) + (" = computeFresnelTerm(" + this.viewDirection.associatedVariableName + ".xyz, " + this.worldNormal.associatedVariableName + ".xyz, " + this.bias.associatedVariableName + ", " + this.power.associatedVariableName + `);\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.FresnelBlock", FresnelBlock);
var MaxBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Neutral) || this;
        return r.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        r.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        r._outputs[0]._typeConnectionSource = r._inputs[0],
        r._linkConnectionTypes(0, 1),
        r
    }
    return e.prototype.getClassName = function() {
        return "MaxBlock"
    }
    ,
    Object.defineProperty(e.prototype, "left", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "right", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = this._outputs[0];
        return t.compilationString += this._declareOutput(r, t) + (" = max(" + this.left.associatedVariableName + ", " + this.right.associatedVariableName + `);\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.MaxBlock", MaxBlock);
var MinBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Neutral) || this;
        return r.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        r.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        r._outputs[0]._typeConnectionSource = r._inputs[0],
        r._linkConnectionTypes(0, 1),
        r
    }
    return e.prototype.getClassName = function() {
        return "MinBlock"
    }
    ,
    Object.defineProperty(e.prototype, "left", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "right", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = this._outputs[0];
        return t.compilationString += this._declareOutput(r, t) + (" = min(" + this.left.associatedVariableName + ", " + this.right.associatedVariableName + `);\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.MinBlock", MinBlock);
var DistanceBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Neutral) || this;
        return r.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        r.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float),
        r._linkConnectionTypes(0, 1),
        r._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float),
        r._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix),
        r._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float),
        r._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix),
        r
    }
    return e.prototype.getClassName = function() {
        return "DistanceBlock"
    }
    ,
    Object.defineProperty(e.prototype, "left", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "right", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = this._outputs[0];
        return t.compilationString += this._declareOutput(r, t) + (" = length(" + this.left.associatedVariableName + " - " + this.right.associatedVariableName + `);\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.DistanceBlock", DistanceBlock);
var LengthBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Neutral) || this;
        return r.registerInput("value", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float),
        r._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float),
        r._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix),
        r
    }
    return e.prototype.getClassName = function() {
        return "LengthBlock"
    }
    ,
    Object.defineProperty(e.prototype, "value", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = this._outputs[0];
        return t.compilationString += this._declareOutput(r, t) + (" = length(" + this.value.associatedVariableName + `);\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.LengthBlock", LengthBlock);
var NegateBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Neutral) || this;
        return r.registerInput("value", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        r._outputs[0]._typeConnectionSource = r._inputs[0],
        r
    }
    return e.prototype.getClassName = function() {
        return "NegateBlock"
    }
    ,
    Object.defineProperty(e.prototype, "value", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = this._outputs[0];
        return t.compilationString += this._declareOutput(r, t) + (" = -1.0 * " + this.value.associatedVariableName + `;\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.NegateBlock", NegateBlock);
var PowBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Neutral) || this;
        return r.registerInput("value", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        r.registerInput("power", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        r._outputs[0]._typeConnectionSource = r._inputs[0],
        r._linkConnectionTypes(0, 1),
        r
    }
    return e.prototype.getClassName = function() {
        return "PowBlock"
    }
    ,
    Object.defineProperty(e.prototype, "value", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "power", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = this._outputs[0];
        return t.compilationString += this._declareOutput(r, t) + (" = pow(" + this.value.associatedVariableName + ", " + this.power.associatedVariableName + `);\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.PowBlock", PowBlock);
var RandomNumberBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Neutral) || this;
        return r.registerInput("seed", NodeMaterialBlockConnectionPointTypes.Vector2),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float),
        r._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector3),
        r._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector4),
        r._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color3),
        r._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color4),
        r
    }
    return e.prototype.getClassName = function() {
        return "RandomNumberBlock"
    }
    ,
    Object.defineProperty(e.prototype, "seed", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = this._outputs[0]
          , n = "//" + this.name;
        return t._emitFunctionFromInclude("helperFunctions", n),
        t.compilationString += this._declareOutput(r, t) + (" = getRand(" + this.seed.associatedVariableName + `.xy);\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.RandomNumberBlock", RandomNumberBlock);
var ArcTan2Block = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Neutral) || this;
        return r.registerInput("x", NodeMaterialBlockConnectionPointTypes.Float),
        r.registerInput("y", NodeMaterialBlockConnectionPointTypes.Float),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float),
        r
    }
    return e.prototype.getClassName = function() {
        return "ArcTan2Block"
    }
    ,
    Object.defineProperty(e.prototype, "x", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "y", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = this._outputs[0];
        return t.compilationString += this._declareOutput(r, t) + (" = atan(" + this.x.associatedVariableName + ", " + this.y.associatedVariableName + `);\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.ArcTan2Block", ArcTan2Block);
var SmoothStepBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Neutral) || this;
        return r.registerInput("value", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        r.registerInput("edge0", NodeMaterialBlockConnectionPointTypes.Float),
        r.registerInput("edge1", NodeMaterialBlockConnectionPointTypes.Float),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        r._outputs[0]._typeConnectionSource = r._inputs[0],
        r
    }
    return e.prototype.getClassName = function() {
        return "SmoothStepBlock"
    }
    ,
    Object.defineProperty(e.prototype, "value", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "edge0", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "edge1", {
        get: function() {
            return this._inputs[2]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = this._outputs[0];
        return t.compilationString += this._declareOutput(r, t) + (" = smoothstep(" + this.edge0.associatedVariableName + ", " + this.edge1.associatedVariableName + ", " + this.value.associatedVariableName + `);\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.SmoothStepBlock", SmoothStepBlock);
var ReciprocalBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Neutral) || this;
        return r.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        r._outputs[0]._typeConnectionSource = r._inputs[0],
        r._outputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix),
        r
    }
    return e.prototype.getClassName = function() {
        return "ReciprocalBlock"
    }
    ,
    Object.defineProperty(e.prototype, "input", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = this._outputs[0];
        return t.compilationString += this._declareOutput(r, t) + (" = 1. / " + this.input.associatedVariableName + `;\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.ReciprocalBlock", ReciprocalBlock);
var ReplaceColorBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Neutral) || this;
        return r.registerInput("value", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        r.registerInput("reference", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        r.registerInput("distance", NodeMaterialBlockConnectionPointTypes.Float),
        r.registerInput("replacement", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        r._outputs[0]._typeConnectionSource = r._inputs[0],
        r._linkConnectionTypes(0, 1),
        r._linkConnectionTypes(0, 3),
        r._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float),
        r._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix),
        r._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float),
        r._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix),
        r._inputs[3].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float),
        r._inputs[3].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix),
        r
    }
    return e.prototype.getClassName = function() {
        return "ReplaceColorBlock"
    }
    ,
    Object.defineProperty(e.prototype, "value", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "reference", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "distance", {
        get: function() {
            return this._inputs[2]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "replacement", {
        get: function() {
            return this._inputs[3]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = this._outputs[0];
        return t.compilationString += this._declareOutput(r, t) + `;\r
`,
        t.compilationString += "if (length(" + this.value.associatedVariableName + " - " + this.reference.associatedVariableName + ") < " + this.distance.associatedVariableName + `) {\r
`,
        t.compilationString += r.associatedVariableName + " = " + this.replacement.associatedVariableName + `;\r
`,
        t.compilationString += `} else {\r
`,
        t.compilationString += r.associatedVariableName + " = " + this.value.associatedVariableName + `;\r
`,
        t.compilationString += `}\r
`,
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.ReplaceColorBlock", ReplaceColorBlock);
var PosterizeBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Neutral) || this;
        return r.registerInput("value", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        r.registerInput("steps", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        r._outputs[0]._typeConnectionSource = r._inputs[0],
        r._linkConnectionTypes(0, 1),
        r._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix),
        r._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix),
        r
    }
    return e.prototype.getClassName = function() {
        return "PosterizeBlock"
    }
    ,
    Object.defineProperty(e.prototype, "value", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "steps", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = this._outputs[0];
        return t.compilationString += this._declareOutput(r, t) + (" = floor(" + this.value.associatedVariableName + " / (1.0 / " + this.steps.associatedVariableName + ")) * (1.0 / " + this.steps.associatedVariableName + `);\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.PosterizeBlock", PosterizeBlock);
var WaveBlockKind;
(function(i) {
    i[i.SawTooth = 0] = "SawTooth",
    i[i.Square = 1] = "Square",
    i[i.Triangle = 2] = "Triangle"
}
)(WaveBlockKind || (WaveBlockKind = {}));
var WaveBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Neutral) || this;
        return r.kind = WaveBlockKind.SawTooth,
        r.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        r._outputs[0]._typeConnectionSource = r._inputs[0],
        r._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix),
        r
    }
    return e.prototype.getClassName = function() {
        return "WaveBlock"
    }
    ,
    Object.defineProperty(e.prototype, "input", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = this._outputs[0];
        switch (this.kind) {
        case WaveBlockKind.SawTooth:
            {
                t.compilationString += this._declareOutput(r, t) + (" = " + this.input.associatedVariableName + " - floor(0.5 + " + this.input.associatedVariableName + `);\r
`);
                break
            }
        case WaveBlockKind.Square:
            {
                t.compilationString += this._declareOutput(r, t) + (" = 1.0 - 2.0 * round(fract(" + this.input.associatedVariableName + `));\r
`);
                break
            }
        case WaveBlockKind.Triangle:
            {
                t.compilationString += this._declareOutput(r, t) + (" = 2.0 * abs(2.0 * (" + this.input.associatedVariableName + " - floor(0.5 + " + this.input.associatedVariableName + `))) - 1.0;\r
`);
                break
            }
        }
        return this
    }
    ,
    e.prototype.serialize = function() {
        var t = i.prototype.serialize.call(this);
        return t.kind = this.kind,
        t
    }
    ,
    e.prototype._deserialize = function(t, r, n) {
        i.prototype._deserialize.call(this, t, r, n),
        this.kind = t.kind
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.WaveBlock", WaveBlock);
var GradientBlockColorStep = function() {
    function i(e, t) {
        this.step = e,
        this.color = t
    }
    return Object.defineProperty(i.prototype, "step", {
        get: function() {
            return this._step
        },
        set: function(e) {
            this._step = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "color", {
        get: function() {
            return this._color
        },
        set: function(e) {
            this._color = e
        },
        enumerable: !1,
        configurable: !0
    }),
    i
}()
  , GradientBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Neutral) || this;
        return r.colorSteps = [new GradientBlockColorStep(0,Color3.Black()), new GradientBlockColorStep(1,Color3.White())],
        r.onValueChangedObservable = new Observable,
        r.registerInput("gradient", NodeMaterialBlockConnectionPointTypes.Float),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Color3),
        r._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector2),
        r._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector3),
        r._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector4),
        r._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color3),
        r._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color4),
        r
    }
    return e.prototype.colorStepsUpdated = function() {
        this.onValueChangedObservable.notifyObservers(this)
    }
    ,
    e.prototype.getClassName = function() {
        return "GradientBlock"
    }
    ,
    Object.defineProperty(e.prototype, "gradient", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._writeColorConstant = function(t) {
        var r = this.colorSteps[t];
        return "vec3(" + r.color.r + ", " + r.color.g + ", " + r.color.b + ")"
    }
    ,
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = this._outputs[0];
        if (!this.colorSteps.length || !this.gradient.connectedPoint) {
            t.compilationString += this._declareOutput(r, t) + ` = vec3(0., 0., 0.);\r
`;
            return
        }
        var n = t._getFreeVariableName("gradientTempColor")
          , o = t._getFreeVariableName("gradientTempPosition");
        t.compilationString += "vec3 " + n + " = " + this._writeColorConstant(0) + `;\r
`,
        t.compilationString += "float " + o + `;\r
`;
        var a = this.gradient.associatedVariableName;
        this.gradient.connectedPoint.type !== NodeMaterialBlockConnectionPointTypes.Float && (a += ".x");
        for (var s = 1; s < this.colorSteps.length; s++) {
            var l = this.colorSteps[s]
              , u = this.colorSteps[s - 1];
            t.compilationString += o + " = clamp((" + a + " - " + t._emitFloat(u.step) + ") / (" + t._emitFloat(l.step) + " -  " + t._emitFloat(u.step) + "), 0.0, 1.0) * step(" + t._emitFloat(s) + ", " + t._emitFloat(this.colorSteps.length - 1) + `);\r
`,
            t.compilationString += n + " = mix(" + n + ", " + this._writeColorConstant(s) + ", " + o + `);\r
`
        }
        return t.compilationString += this._declareOutput(r, t) + (" = " + n + `;\r
`),
        this
    }
    ,
    e.prototype.serialize = function() {
        var t = i.prototype.serialize.call(this);
        t.colorSteps = [];
        for (var r = 0, n = this.colorSteps; r < n.length; r++) {
            var o = n[r];
            t.colorSteps.push({
                step: o.step,
                color: {
                    r: o.color.r,
                    g: o.color.g,
                    b: o.color.b
                }
            })
        }
        return t
    }
    ,
    e.prototype._deserialize = function(t, r, n) {
        i.prototype._deserialize.call(this, t, r, n),
        this.colorSteps = [];
        for (var o = 0, a = t.colorSteps; o < a.length; o++) {
            var s = a[o];
            this.colorSteps.push(new GradientBlockColorStep(s.step,new Color3(s.color.r,s.color.g,s.color.b)))
        }
    }
    ,
    e.prototype._dumpPropertiesCode = function() {
        var t = i.prototype._dumpPropertiesCode.call(this);
        t += this._codeVariableName + `.colorSteps = [];\r
`;
        for (var r = 0, n = this.colorSteps; r < n.length; r++) {
            var o = n[r];
            t += this._codeVariableName + ".colorSteps.push(new BABYLON.GradientBlockColorStep(" + o.step + ", new BABYLON.Color3(" + o.color.r + ", " + o.color.g + ", " + o.color.b + `)));\r
`
        }
        return t
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.GradientBlock", GradientBlock);
var NLerpBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Neutral) || this;
        return r.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        r.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        r.registerInput("gradient", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        r._outputs[0]._typeConnectionSource = r._inputs[0],
        r._linkConnectionTypes(0, 1),
        r._linkConnectionTypes(1, 2, !0),
        r._inputs[2].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float),
        r
    }
    return e.prototype.getClassName = function() {
        return "NLerpBlock"
    }
    ,
    Object.defineProperty(e.prototype, "left", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "right", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "gradient", {
        get: function() {
            return this._inputs[2]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = this._outputs[0];
        return t.compilationString += this._declareOutput(r, t) + (" = normalize(mix(" + this.left.associatedVariableName + " , " + this.right.associatedVariableName + ", " + this.gradient.associatedVariableName + `));\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.NLerpBlock", NLerpBlock);
var WorleyNoise3DBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Neutral) || this;
        return r.manhattanDistance = !1,
        r.registerInput("seed", NodeMaterialBlockConnectionPointTypes.Vector3),
        r.registerInput("jitter", NodeMaterialBlockConnectionPointTypes.Float),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector2),
        r.registerOutput("x", NodeMaterialBlockConnectionPointTypes.Float),
        r.registerOutput("y", NodeMaterialBlockConnectionPointTypes.Float),
        r
    }
    return e.prototype.getClassName = function() {
        return "WorleyNoise3DBlock"
    }
    ,
    Object.defineProperty(e.prototype, "seed", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "jitter", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "x", {
        get: function() {
            return this._outputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "y", {
        get: function() {
            return this._outputs[2]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._buildBlock = function(t) {
        if (i.prototype._buildBlock.call(this, t),
        !!this.seed.isConnected && !(!this.output.hasEndpoints && !this.x.hasEndpoints && !this.y.hasEndpoints)) {
            var r = `vec3 permute(vec3 x){\r
`;
            r += `    return mod((34.0 * x + 1.0) * x, 289.0);\r
`,
            r += `}\r
\r
`,
            r += `vec3 dist(vec3 x, vec3 y, vec3 z,  bool manhattanDistance){\r
`,
            r += `    return manhattanDistance ?  abs(x) + abs(y) + abs(z) :  (x * x + y * y + z * z);\r
`,
            r += `}\r
\r
`,
            r += `vec2 worley(vec3 P, float jitter, bool manhattanDistance){\r
`,
            r += `    float K = 0.142857142857; // 1/7\r
`,
            r += `    float Ko = 0.428571428571; // 1/2-K/2\r
`,
            r += `    float  K2 = 0.020408163265306; // 1/(7*7)\r
`,
            r += `    float Kz = 0.166666666667; // 1/6\r
`,
            r += `    float Kzo = 0.416666666667; // 1/2-1/6*2\r
`,
            r += `\r
`,
            r += `    vec3 Pi = mod(floor(P), 289.0);\r
`,
            r += `    vec3 Pf = fract(P) - 0.5;\r
`,
            r += `\r
`,
            r += `    vec3 Pfx = Pf.x + vec3(1.0, 0.0, -1.0);\r
`,
            r += `    vec3 Pfy = Pf.y + vec3(1.0, 0.0, -1.0);\r
`,
            r += `    vec3 Pfz = Pf.z + vec3(1.0, 0.0, -1.0);\r
`,
            r += `\r
`,
            r += `    vec3 p = permute(Pi.x + vec3(-1.0, 0.0, 1.0));\r
`,
            r += `    vec3 p1 = permute(p + Pi.y - 1.0);\r
`,
            r += `    vec3 p2 = permute(p + Pi.y);\r
`,
            r += `    vec3 p3 = permute(p + Pi.y + 1.0);\r
`,
            r += `\r
`,
            r += `    vec3 p11 = permute(p1 + Pi.z - 1.0);\r
`,
            r += `    vec3 p12 = permute(p1 + Pi.z);\r
`,
            r += `    vec3 p13 = permute(p1 + Pi.z + 1.0);\r
`,
            r += `\r
`,
            r += `    vec3 p21 = permute(p2 + Pi.z - 1.0);\r
`,
            r += `    vec3 p22 = permute(p2 + Pi.z);\r
`,
            r += `    vec3 p23 = permute(p2 + Pi.z + 1.0);\r
`,
            r += `\r
`,
            r += `    vec3 p31 = permute(p3 + Pi.z - 1.0);\r
`,
            r += `    vec3 p32 = permute(p3 + Pi.z);\r
`,
            r += `    vec3 p33 = permute(p3 + Pi.z + 1.0);\r
`,
            r += `\r
`,
            r += `    vec3 ox11 = fract(p11*K) - Ko;\r
`,
            r += `    vec3 oy11 = mod(floor(p11*K), 7.0)*K - Ko;\r
`,
            r += `    vec3 oz11 = floor(p11*K2)*Kz - Kzo; // p11 < 289 guaranteed\r
`,
            r += `\r
`,
            r += `    vec3 ox12 = fract(p12*K) - Ko;\r
`,
            r += `    vec3 oy12 = mod(floor(p12*K), 7.0)*K - Ko;\r
`,
            r += `    vec3 oz12 = floor(p12*K2)*Kz - Kzo;\r
`,
            r += `\r
`,
            r += `    vec3 ox13 = fract(p13*K) - Ko;\r
`,
            r += `    vec3 oy13 = mod(floor(p13*K), 7.0)*K - Ko;\r
`,
            r += `    vec3 oz13 = floor(p13*K2)*Kz - Kzo;\r
`,
            r += `\r
`,
            r += `    vec3 ox21 = fract(p21*K) - Ko;\r
`,
            r += `    vec3 oy21 = mod(floor(p21*K), 7.0)*K - Ko;\r
`,
            r += `    vec3 oz21 = floor(p21*K2)*Kz - Kzo;\r
`,
            r += `\r
`,
            r += `    vec3 ox22 = fract(p22*K) - Ko;\r
`,
            r += `    vec3 oy22 = mod(floor(p22*K), 7.0)*K - Ko;\r
`,
            r += `    vec3 oz22 = floor(p22*K2)*Kz - Kzo;\r
`,
            r += `\r
`,
            r += `    vec3 ox23 = fract(p23*K) - Ko;\r
`,
            r += `    vec3 oy23 = mod(floor(p23*K), 7.0)*K - Ko;\r
`,
            r += `    vec3 oz23 = floor(p23*K2)*Kz - Kzo;\r
`,
            r += `\r
`,
            r += `    vec3 ox31 = fract(p31*K) - Ko;\r
`,
            r += `    vec3 oy31 = mod(floor(p31*K), 7.0)*K - Ko;\r
`,
            r += `    vec3 oz31 = floor(p31*K2)*Kz - Kzo;\r
`,
            r += `\r
`,
            r += `    vec3 ox32 = fract(p32*K) - Ko;\r
`,
            r += `    vec3 oy32 = mod(floor(p32*K), 7.0)*K - Ko;\r
`,
            r += `    vec3 oz32 = floor(p32*K2)*Kz - Kzo;\r
`,
            r += `\r
`,
            r += `    vec3 ox33 = fract(p33*K) - Ko;\r
`,
            r += `    vec3 oy33 = mod(floor(p33*K), 7.0)*K - Ko;\r
`,
            r += `    vec3 oz33 = floor(p33*K2)*Kz - Kzo;\r
`,
            r += `\r
`,
            r += `    vec3 dx11 = Pfx + jitter*ox11;\r
`,
            r += `    vec3 dy11 = Pfy.x + jitter*oy11;\r
`,
            r += `    vec3 dz11 = Pfz.x + jitter*oz11;\r
`,
            r += `\r
`,
            r += `    vec3 dx12 = Pfx + jitter*ox12;\r
`,
            r += `    vec3 dy12 = Pfy.x + jitter*oy12;\r
`,
            r += `    vec3 dz12 = Pfz.y + jitter*oz12;\r
`,
            r += `\r
`,
            r += `    vec3 dx13 = Pfx + jitter*ox13;\r
`,
            r += `    vec3 dy13 = Pfy.x + jitter*oy13;\r
`,
            r += `    vec3 dz13 = Pfz.z + jitter*oz13;\r
`,
            r += `\r
`,
            r += `    vec3 dx21 = Pfx + jitter*ox21;\r
`,
            r += `    vec3 dy21 = Pfy.y + jitter*oy21;\r
`,
            r += `    vec3 dz21 = Pfz.x + jitter*oz21;\r
`,
            r += `\r
`,
            r += `    vec3 dx22 = Pfx + jitter*ox22;\r
`,
            r += `    vec3 dy22 = Pfy.y + jitter*oy22;\r
`,
            r += `    vec3 dz22 = Pfz.y + jitter*oz22;\r
`,
            r += `\r
`,
            r += `    vec3 dx23 = Pfx + jitter*ox23;\r
`,
            r += `    vec3 dy23 = Pfy.y + jitter*oy23;\r
`,
            r += `    vec3 dz23 = Pfz.z + jitter*oz23;\r
`,
            r += `\r
`,
            r += `    vec3 dx31 = Pfx + jitter*ox31;\r
`,
            r += `    vec3 dy31 = Pfy.z + jitter*oy31;\r
`,
            r += `    vec3 dz31 = Pfz.x + jitter*oz31;\r
`,
            r += `\r
`,
            r += `    vec3 dx32 = Pfx + jitter*ox32;\r
`,
            r += `    vec3 dy32 = Pfy.z + jitter*oy32;\r
`,
            r += `    vec3 dz32 = Pfz.y + jitter*oz32;\r
`,
            r += `\r
`,
            r += `    vec3 dx33 = Pfx + jitter*ox33;\r
`,
            r += `    vec3 dy33 = Pfy.z + jitter*oy33;\r
`,
            r += `    vec3 dz33 = Pfz.z + jitter*oz33;\r
`,
            r += `\r
`,
            r += `    vec3 d11 = dist(dx11, dy11, dz11, manhattanDistance);\r
`,
            r += `    vec3 d12 =dist(dx12, dy12, dz12, manhattanDistance);\r
`,
            r += `    vec3 d13 = dist(dx13, dy13, dz13, manhattanDistance);\r
`,
            r += `    vec3 d21 = dist(dx21, dy21, dz21, manhattanDistance);\r
`,
            r += `    vec3 d22 = dist(dx22, dy22, dz22, manhattanDistance);\r
`,
            r += `    vec3 d23 = dist(dx23, dy23, dz23, manhattanDistance);\r
`,
            r += `    vec3 d31 = dist(dx31, dy31, dz31, manhattanDistance);\r
`,
            r += `    vec3 d32 = dist(dx32, dy32, dz32, manhattanDistance);\r
`,
            r += `    vec3 d33 = dist(dx33, dy33, dz33, manhattanDistance);\r
`,
            r += `\r
`,
            r += `    vec3 d1a = min(d11, d12);\r
`,
            r += `    d12 = max(d11, d12);\r
`,
            r += `    d11 = min(d1a, d13); // Smallest now not in d12 or d13\r
`,
            r += `    d13 = max(d1a, d13);\r
`,
            r += `    d12 = min(d12, d13); // 2nd smallest now not in d13\r
`,
            r += `    vec3 d2a = min(d21, d22);\r
`,
            r += `    d22 = max(d21, d22);\r
`,
            r += `    d21 = min(d2a, d23); // Smallest now not in d22 or d23\r
`,
            r += `    d23 = max(d2a, d23);\r
`,
            r += `    d22 = min(d22, d23); // 2nd smallest now not in d23\r
`,
            r += `    vec3 d3a = min(d31, d32);\r
`,
            r += `    d32 = max(d31, d32);\r
`,
            r += `    d31 = min(d3a, d33); // Smallest now not in d32 or d33\r
`,
            r += `    d33 = max(d3a, d33);\r
`,
            r += `    d32 = min(d32, d33); // 2nd smallest now not in d33\r
`,
            r += `    vec3 da = min(d11, d21);\r
`,
            r += `    d21 = max(d11, d21);\r
`,
            r += `    d11 = min(da, d31); // Smallest now in d11\r
`,
            r += `    d31 = max(da, d31); // 2nd smallest now not in d31\r
`,
            r += `    d11.xy = (d11.x < d11.y) ? d11.xy : d11.yx;\r
`,
            r += `    d11.xz = (d11.x < d11.z) ? d11.xz : d11.zx; // d11.x now smallest\r
`,
            r += `    d12 = min(d12, d21); // 2nd smallest now not in d21\r
`,
            r += `    d12 = min(d12, d22); // nor in d22\r
`,
            r += `    d12 = min(d12, d31); // nor in d31\r
`,
            r += `    d12 = min(d12, d32); // nor in d32\r
`,
            r += `    d11.yz = min(d11.yz,d12.xy); // nor in d12.yz\r
`,
            r += `    d11.y = min(d11.y,d12.z); // Only two more to go\r
`,
            r += `    d11.y = min(d11.y,d11.z); // Done! (Phew!)\r
`,
            r += `    return sqrt(d11.xy); // F1, F2\r
`,
            r += `}\r
\r
`,
            t._emitFunction("worley3D", r, "// Worley3D");
            var n = t._getFreeVariableName("worleyTemp");
            return t.compilationString += "vec2 " + n + " = worley(" + this.seed.associatedVariableName + ", " + this.jitter.associatedVariableName + ", " + this.manhattanDistance + `);\r
`,
            this.output.hasEndpoints && (t.compilationString += this._declareOutput(this.output, t) + (" = " + n + `;\r
`)),
            this.x.hasEndpoints && (t.compilationString += this._declareOutput(this.x, t) + (" = " + n + `.x;\r
`)),
            this.y.hasEndpoints && (t.compilationString += this._declareOutput(this.y, t) + (" = " + n + `.y;\r
`)),
            this
        }
    }
    ,
    e.prototype._dumpPropertiesCode = function() {
        var t = i.prototype._dumpPropertiesCode.call(this) + (this._codeVariableName + ".manhattanDistance = " + this.manhattanDistance + `;\r
`);
        return t
    }
    ,
    e.prototype.serialize = function() {
        var t = i.prototype.serialize.call(this);
        return t.manhattanDistance = this.manhattanDistance,
        t
    }
    ,
    e.prototype._deserialize = function(t, r, n) {
        i.prototype._deserialize.call(this, t, r, n),
        this.manhattanDistance = t.manhattanDistance
    }
    ,
    __decorate([editableInPropertyPage("Use Manhattan Distance", PropertyTypeForEdition.Boolean, "PROPERTIES", {
        notifiers: {
            update: !1
        }
    })], e.prototype, "manhattanDistance", void 0),
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.WorleyNoise3DBlock", WorleyNoise3DBlock);
var SimplexPerlin3DBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Neutral) || this;
        return r.registerInput("seed", NodeMaterialBlockConnectionPointTypes.Vector3),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float),
        r
    }
    return e.prototype.getClassName = function() {
        return "SimplexPerlin3DBlock"
    }
    ,
    Object.defineProperty(e.prototype, "seed", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._buildBlock = function(t) {
        if (i.prototype._buildBlock.call(this, t),
        !!this.seed.isConnected && !!this._outputs[0].hasEndpoints) {
            var r = `const float SKEWFACTOR = 1.0/3.0;\r
`;
            return r += `const float UNSKEWFACTOR = 1.0/6.0;\r
`,
            r += `const float SIMPLEX_CORNER_POS = 0.5;\r
`,
            r += `const float SIMPLEX_TETRAHADRON_HEIGHT = 0.70710678118654752440084436210485;\r
`,
            r += `float SimplexPerlin3D( vec3 P ){\r
`,
            r += `    P *= SIMPLEX_TETRAHADRON_HEIGHT;\r
`,
            r += "    vec3 Pi = floor( P + dot( P, vec3( SKEWFACTOR) ) );",
            r += `    vec3 x0 = P - Pi + dot(Pi, vec3( UNSKEWFACTOR ) );\r
`,
            r += `    vec3 g = step(x0.yzx, x0.xyz);\r
`,
            r += `    vec3 l = 1.0 - g;\r
`,
            r += `    vec3 Pi_1 = min( g.xyz, l.zxy );\r
`,
            r += `    vec3 Pi_2 = max( g.xyz, l.zxy );\r
`,
            r += `    vec3 x1 = x0 - Pi_1 + UNSKEWFACTOR;\r
`,
            r += `    vec3 x2 = x0 - Pi_2 + SKEWFACTOR;\r
`,
            r += `    vec3 x3 = x0 - SIMPLEX_CORNER_POS;\r
`,
            r += `    vec4 v1234_x = vec4( x0.x, x1.x, x2.x, x3.x );\r
`,
            r += `    vec4 v1234_y = vec4( x0.y, x1.y, x2.y, x3.y );\r
`,
            r += `    vec4 v1234_z = vec4( x0.z, x1.z, x2.z, x3.z );\r
`,
            r += `    Pi.xyz = Pi.xyz - floor(Pi.xyz * ( 1.0 / 69.0 )) * 69.0;\r
`,
            r += `    vec3 Pi_inc1 = step( Pi, vec3( 69.0 - 1.5 ) ) * ( Pi + 1.0 );\r
`,
            r += `    vec4 Pt = vec4( Pi.xy, Pi_inc1.xy ) + vec2( 50.0, 161.0 ).xyxy;\r
`,
            r += `    Pt *= Pt;\r
`,
            r += `    vec4 V1xy_V2xy = mix( Pt.xyxy, Pt.zwzw, vec4( Pi_1.xy, Pi_2.xy ) );\r
`,
            r += `    Pt = vec4( Pt.x, V1xy_V2xy.xz, Pt.z ) * vec4( Pt.y, V1xy_V2xy.yw, Pt.w );\r
`,
            r += `    const vec3 SOMELARGEFLOATS = vec3( 635.298681, 682.357502, 668.926525 );\r
`,
            r += `    const vec3 ZINC = vec3( 48.500388, 65.294118, 63.934599 );\r
`,
            r += `    vec3 lowz_mods = vec3( 1.0 / ( SOMELARGEFLOATS.xyz + Pi.zzz * ZINC.xyz ) );\r
`,
            r += `    vec3 highz_mods = vec3( 1.0 / ( SOMELARGEFLOATS.xyz + Pi_inc1.zzz * ZINC.xyz ) );\r
`,
            r += `    Pi_1 = ( Pi_1.z < 0.5 ) ? lowz_mods : highz_mods;\r
`,
            r += `    Pi_2 = ( Pi_2.z < 0.5 ) ? lowz_mods : highz_mods;\r
`,
            r += `    vec4 hash_0 = fract( Pt * vec4( lowz_mods.x, Pi_1.x, Pi_2.x, highz_mods.x ) ) - 0.49999;\r
`,
            r += `    vec4 hash_1 = fract( Pt * vec4( lowz_mods.y, Pi_1.y, Pi_2.y, highz_mods.y ) ) - 0.49999;\r
`,
            r += `    vec4 hash_2 = fract( Pt * vec4( lowz_mods.z, Pi_1.z, Pi_2.z, highz_mods.z ) ) - 0.49999;\r
`,
            r += `    vec4 grad_results = inversesqrt( hash_0 * hash_0 + hash_1 * hash_1 + hash_2 * hash_2 ) * ( hash_0 * v1234_x + hash_1 * v1234_y + hash_2 * v1234_z );\r
`,
            r += `    const float FINAL_NORMALIZATION = 37.837227241611314102871574478976;\r
`,
            r += `    vec4 kernel_weights = v1234_x * v1234_x + v1234_y * v1234_y + v1234_z * v1234_z;\r
`,
            r += `    kernel_weights = max(0.5 - kernel_weights, 0.0);\r
`,
            r += `    kernel_weights = kernel_weights*kernel_weights*kernel_weights;\r
`,
            r += `    return dot( kernel_weights, grad_results ) * FINAL_NORMALIZATION;\r
`,
            r += `}\r
`,
            t._emitFunction("SimplexPerlin3D", r, "// SimplexPerlin3D"),
            t.compilationString += this._declareOutput(this._outputs[0], t) + (" = SimplexPerlin3D(" + this.seed.associatedVariableName + `);\r
`),
            this
        }
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.SimplexPerlin3DBlock", SimplexPerlin3DBlock);
var NormalBlendBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Neutral) || this;
        return r.registerInput("normalMap0", NodeMaterialBlockConnectionPointTypes.Vector3),
        r.registerInput("normalMap1", NodeMaterialBlockConnectionPointTypes.Vector3),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector3),
        r._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color3),
        r._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color4),
        r._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector4),
        r._inputs[1].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color3),
        r._inputs[1].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color4),
        r._inputs[1].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector4),
        r
    }
    return e.prototype.getClassName = function() {
        return "NormalBlendBlock"
    }
    ,
    Object.defineProperty(e.prototype, "normalMap0", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "normalMap1", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = this._outputs[0]
          , n = this._inputs[0]
          , o = this._inputs[1]
          , a = t._getFreeVariableName("stepR")
          , s = t._getFreeVariableName("stepG");
        return t.compilationString += "float " + a + " = step(0.5, " + n.associatedVariableName + `.r);\r
`,
        t.compilationString += "float " + s + " = step(0.5, " + n.associatedVariableName + `.g);\r
`,
        t.compilationString += this._declareOutput(r, t) + `;\r
`,
        t.compilationString += r.associatedVariableName + ".r = (1.0 - " + a + ") * " + n.associatedVariableName + ".r * " + o.associatedVariableName + ".r * 2.0 + " + a + " * (1.0 - (1.0 - " + n.associatedVariableName + ".r) * (1.0 - " + o.associatedVariableName + `.r) * 2.0);\r
`,
        t.compilationString += r.associatedVariableName + ".g = (1.0 - " + s + ") * " + n.associatedVariableName + ".g * " + o.associatedVariableName + ".g * 2.0 + " + s + " * (1.0 - (1.0 - " + n.associatedVariableName + ".g) * (1.0 - " + o.associatedVariableName + `.g) * 2.0);\r
`,
        t.compilationString += r.associatedVariableName + ".b = " + n.associatedVariableName + ".b * " + o.associatedVariableName + `.b;\r
`,
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.NormalBlendBlock", NormalBlendBlock);
var Rotate2dBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Neutral) || this;
        return r.registerInput("input", NodeMaterialBlockConnectionPointTypes.Vector2),
        r.registerInput("angle", NodeMaterialBlockConnectionPointTypes.Float),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector2),
        r
    }
    return e.prototype.getClassName = function() {
        return "Rotate2dBlock"
    }
    ,
    Object.defineProperty(e.prototype, "input", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "angle", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.autoConfigure = function(t) {
        if (!this.angle.isConnected) {
            var r = new InputBlock("angle");
            r.value = 0,
            r.output.connectTo(this.angle)
        }
    }
    ,
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = this._outputs[0]
          , n = this.angle
          , o = this.input;
        return t.compilationString += this._declareOutput(r, t) + (" = vec2(cos(" + n.associatedVariableName + ") * " + o.associatedVariableName + ".x - sin(" + n.associatedVariableName + ") * " + o.associatedVariableName + ".y, sin(" + n.associatedVariableName + ") * " + o.associatedVariableName + ".x + cos(" + n.associatedVariableName + ") * " + o.associatedVariableName + `.y);\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.Rotate2dBlock", Rotate2dBlock);
var ReflectBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Neutral) || this;
        return r.registerInput("incident", NodeMaterialBlockConnectionPointTypes.Vector3),
        r.registerInput("normal", NodeMaterialBlockConnectionPointTypes.Vector3),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector3),
        r._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector4),
        r._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color3),
        r._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color4),
        r._inputs[1].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector4),
        r._inputs[1].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color3),
        r._inputs[1].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color4),
        r
    }
    return e.prototype.getClassName = function() {
        return "ReflectBlock"
    }
    ,
    Object.defineProperty(e.prototype, "incident", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "normal", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = this._outputs[0];
        return t.compilationString += this._declareOutput(r, t) + (" = reflect(" + this.incident.associatedVariableName + ".xyz, " + this.normal.associatedVariableName + `.xyz);\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.ReflectBlock", ReflectBlock);
var RefractBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Neutral) || this;
        return r.registerInput("incident", NodeMaterialBlockConnectionPointTypes.Vector3),
        r.registerInput("normal", NodeMaterialBlockConnectionPointTypes.Vector3),
        r.registerInput("ior", NodeMaterialBlockConnectionPointTypes.Float),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector3),
        r._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector4),
        r._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color3),
        r._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color4),
        r._inputs[1].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector4),
        r._inputs[1].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color3),
        r._inputs[1].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Color4),
        r
    }
    return e.prototype.getClassName = function() {
        return "RefractBlock"
    }
    ,
    Object.defineProperty(e.prototype, "incident", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "normal", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "ior", {
        get: function() {
            return this._inputs[2]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = this._outputs[0];
        return t.compilationString += this._declareOutput(r, t) + (" = refract(" + this.incident.associatedVariableName + ".xyz, " + this.normal.associatedVariableName + ".xyz, " + this.ior.associatedVariableName + `);\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.RefractBlock", RefractBlock);
var DesaturateBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Neutral) || this;
        return r.registerInput("color", NodeMaterialBlockConnectionPointTypes.Color3),
        r.registerInput("level", NodeMaterialBlockConnectionPointTypes.Float),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Color3),
        r
    }
    return e.prototype.getClassName = function() {
        return "DesaturateBlock"
    }
    ,
    Object.defineProperty(e.prototype, "color", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "level", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = this._outputs[0]
          , n = this.color
          , o = n.associatedVariableName
          , a = t._getFreeVariableName("colorMin")
          , s = t._getFreeVariableName("colorMax")
          , l = t._getFreeVariableName("colorMerge");
        return t.compilationString += "float " + a + " = min(min(" + o + ".x, " + o + ".y), " + o + `.z);\r
`,
        t.compilationString += "float " + s + " = max(max(" + o + ".x, " + o + ".y), " + o + `.z);\r
`,
        t.compilationString += "float " + l + " = 0.5 * (" + a + " + " + s + `);\r
`,
        t.compilationString += this._declareOutput(r, t) + (" = mix(" + o + ", vec3(" + l + ", " + l + ", " + l + "), " + this.level.associatedVariableName + `);\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.DesaturateBlock", DesaturateBlock);
var name$1z = "rgbdDecodePixelShader"
  , shader$1z = `
varying vec2 vUV;
uniform sampler2D textureSampler;
#include<helperFunctions>
void main(void)
{
gl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);
}`;
ShaderStore.ShadersStore[name$1z] = shader$1z;
var name$1y = "passPixelShader"
  , shader$1y = `
varying vec2 vUV;
uniform sampler2D textureSampler;
void main(void)
{
gl_FragColor=texture2D(textureSampler,vUV);
}`;
ShaderStore.ShadersStore[name$1y] = shader$1y;
var name$1x = "passCubePixelShader"
  , shader$1x = `
varying vec2 vUV;
uniform samplerCube textureSampler;
void main(void)
{
vec2 uv=vUV*2.0-1.0;
#ifdef POSITIVEX
gl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x));
#endif
#ifdef NEGATIVEX
gl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x));
#endif
#ifdef POSITIVEY
gl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x));
#endif
#ifdef NEGATIVEY
gl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x));
#endif
#ifdef POSITIVEZ
gl_FragColor=textureCube(textureSampler,vec3(uv,1.001));
#endif
#ifdef NEGATIVEZ
gl_FragColor=textureCube(textureSampler,vec3(uv,-1.001));
#endif
}`;
ShaderStore.ShadersStore[name$1x] = shader$1x;
var PassPostProcess = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a, s, l, u) {
        return n === void 0 && (n = null),
        l === void 0 && (l = 0),
        u === void 0 && (u = !1),
        i.call(this, t, "pass", null, null, r, n, o, a, s, void 0, l, void 0, null, u) || this
    }
    return e.prototype.getClassName = function() {
        return "PassPostProcess"
    }
    ,
    e._Parse = function(t, r, n, o) {
        return SerializationHelper.Parse(function() {
            return new e(t.name,t.options,r,t.renderTargetSamplingMode,t._engine,t.reusable)
        }, t, n, o)
    }
    ,
    e
}(PostProcess);
RegisterClass("BABYLON.PassPostProcess", PassPostProcess);
(function(i) {
    __extends(e, i);
    function e(t, r, n, o, a, s, l, u) {
        n === void 0 && (n = null),
        l === void 0 && (l = 0),
        u === void 0 && (u = !1);
        var c = i.call(this, t, "passCube", null, null, r, n, o, a, s, "#define POSITIVEX", l, void 0, null, u) || this;
        return c._face = 0,
        c
    }
    return Object.defineProperty(e.prototype, "face", {
        get: function() {
            return this._face
        },
        set: function(t) {
            if (!(t < 0 || t > 5))
                switch (this._face = t,
                this._face) {
                case 0:
                    this.updateEffect("#define POSITIVEX");
                    break;
                case 1:
                    this.updateEffect("#define NEGATIVEX");
                    break;
                case 2:
                    this.updateEffect("#define POSITIVEY");
                    break;
                case 3:
                    this.updateEffect("#define NEGATIVEY");
                    break;
                case 4:
                    this.updateEffect("#define POSITIVEZ");
                    break;
                case 5:
                    this.updateEffect("#define NEGATIVEZ");
                    break
                }
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getClassName = function() {
        return "PassCubePostProcess"
    }
    ,
    e._Parse = function(t, r, n, o) {
        return SerializationHelper.Parse(function() {
            return new e(t.name,t.options,r,t.renderTargetSamplingMode,t._engine,t.reusable)
        }, t, n, o)
    }
    ,
    e
}
)(PostProcess);
Engine._RescalePostProcessFactory = function(i) {
    return new PassPostProcess("rescale",1,null,2,i,!1,0)
}
;
function ApplyPostProcess(i, e, t, r, n, o) {
    var a = e.getEngine();
    return e.isReady = !1,
    n = n != null ? n : e.samplingMode,
    r = r != null ? r : e.type,
    o = o != null ? o : e.format,
    r === -1 && (r = 0),
    new Promise(function(s) {
        var l = new PostProcess("postprocess",i,null,null,1,null,n,a,!1,void 0,r,void 0,null,!1,o);
        l.externalTextureSamplerBinding = !0;
        var u = a.createRenderTargetTexture({
            width: e.width,
            height: e.height
        }, {
            generateDepthBuffer: !1,
            generateMipMaps: !1,
            generateStencilBuffer: !1,
            samplingMode: n,
            type: r,
            format: o
        });
        l.getEffect().executeWhenCompiled(function() {
            l.onApply = function(c) {
                c._bindTexture("textureSampler", e),
                c.setFloat2("scale", 1, 1)
            }
            ,
            t.postProcessManager.directRender([l], u, !0),
            a.restoreDefaultFramebuffer(),
            a._releaseTexture(e),
            l && l.dispose(),
            u._swapAndDie(e),
            e.type = r,
            e.format = 5,
            e.isReady = !0,
            s(e)
        })
    }
    )
}
var _FloatView, _Int32View;
function ToHalfFloat(i) {
    _FloatView || (_FloatView = new Float32Array(1),
    _Int32View = new Int32Array(_FloatView.buffer)),
    _FloatView[0] = i;
    var e = _Int32View[0]
      , t = e >> 16 & 32768
      , r = e >> 12 & 2047
      , n = e >> 23 & 255;
    return n < 103 ? t : n > 142 ? (t |= 31744,
    t |= (n == 255 ? 0 : 1) && e & 8388607,
    t) : n < 113 ? (r |= 2048,
    t |= (r >> 114 - n) + (r >> 113 - n & 1),
    t) : (t |= n - 112 << 10 | r >> 1,
    t += r & 1,
    t)
}
function FromHalfFloat(i) {
    var e = (i & 32768) >> 15
      , t = (i & 31744) >> 10
      , r = i & 1023;
    return t === 0 ? (e ? -1 : 1) * Math.pow(2, -14) * (r / Math.pow(2, 10)) : t == 31 ? r ? NaN : (e ? -1 : 1) * (1 / 0) : (e ? -1 : 1) * Math.pow(2, t - 15) * (1 + r / Math.pow(2, 10))
}
var RGBDTextureTools = function() {
    function i() {}
    return i.ExpandRGBDTexture = function(e) {
        var t = e._texture;
        if (!(!t || !e.isRGBD)) {
            var r = t.getEngine()
              , n = r.getCaps()
              , o = t.isReady
              , a = !1;
            n.textureHalfFloatRender && n.textureHalfFloatLinearFiltering ? (a = !0,
            t.type = 2) : n.textureFloatRender && n.textureFloatLinearFiltering && (a = !0,
            t.type = 1),
            a && (t.isReady = !1,
            t._isRGBD = !1,
            t.invertY = !1);
            var s = function() {
                if (a) {
                    var l = new PostProcess("rgbdDecode","rgbdDecode",null,null,1,null,3,r,!1,void 0,t.type,void 0,null,!1);
                    l.externalTextureSamplerBinding = !0;
                    var u = r.createRenderTargetTexture(t.width, {
                        generateDepthBuffer: !1,
                        generateMipMaps: !1,
                        generateStencilBuffer: !1,
                        samplingMode: t.samplingMode,
                        type: t.type,
                        format: 5
                    });
                    l.getEffect().executeWhenCompiled(function() {
                        l.onApply = function(c) {
                            c._bindTexture("textureSampler", t),
                            c.setFloat2("scale", 1, 1)
                        }
                        ,
                        e.getScene().postProcessManager.directRender([l], u, !0),
                        r.restoreDefaultFramebuffer(),
                        r._releaseTexture(t),
                        l && l.dispose(),
                        u._swapAndDie(t),
                        t.isReady = !0
                    })
                }
            };
            o ? s() : e.onLoadObservable.addOnce(s)
        }
    }
    ,
    i.EncodeTextureToRGBD = function(e, t, r) {
        return r === void 0 && (r = 0),
        ApplyPostProcess("rgbdEncode", e, t, r, 1, 5)
    }
    ,
    i
}()
  , _environmentBRDFBase64Texture = "data:image/png;base64, "
  , _instanceNumber = 0
  , GetEnvironmentBRDFTexture = function(i) {
    if (!i.environmentBRDFTexture) {
        var e = i.useDelayedTextureLoading;
        i.useDelayedTextureLoading = !1;
        var t = i._blockEntityCollection;
        i._blockEntityCollection = !1;
        var r = Texture.CreateFromBase64String(_environmentBRDFBase64Texture, "EnvironmentBRDFTexture" + _instanceNumber++, i, !0, !1, Texture.BILINEAR_SAMPLINGMODE);
        i._blockEntityCollection = t;
        var n = i.getEngine().getLoadedTexturesCache()
          , o = n.indexOf(r.getInternalTexture());
        o !== -1 && n.splice(o, 1),
        r.isRGBD = !0,
        r.wrapU = Texture.CLAMP_ADDRESSMODE,
        r.wrapV = Texture.CLAMP_ADDRESSMODE,
        i.environmentBRDFTexture = r,
        i.useDelayedTextureLoading = e,
        RGBDTextureTools.ExpandRGBDTexture(r),
        i.getEngine().onContextRestoredObservable.add(function() {
            r.isRGBD = !0;
            var a = function() {
                r.isReady() ? RGBDTextureTools.ExpandRGBDTexture(r) : Tools.SetImmediate(a)
            };
            a()
        })
    }
    return i.environmentBRDFTexture
}
  , PBRClearCoatConfiguration = function() {
    function i(e) {
        this._isEnabled = !1,
        this.isEnabled = !1,
        this.intensity = 1,
        this.roughness = 0,
        this._indexOfRefraction = i._DefaultIndexOfRefraction,
        this.indexOfRefraction = i._DefaultIndexOfRefraction,
        this._texture = null,
        this.texture = null,
        this._useRoughnessFromMainTexture = !0,
        this.useRoughnessFromMainTexture = !0,
        this._textureRoughness = null,
        this.textureRoughness = null,
        this._remapF0OnInterfaceChange = !0,
        this.remapF0OnInterfaceChange = !0,
        this._bumpTexture = null,
        this.bumpTexture = null,
        this._isTintEnabled = !1,
        this.isTintEnabled = !1,
        this.tintColor = Color3.White(),
        this.tintColorAtDistance = 1,
        this.tintThickness = 1,
        this._tintTexture = null,
        this.tintTexture = null,
        this._internalMarkAllSubMeshesAsTexturesDirty = e
    }
    return i.prototype._markAllSubMeshesAsTexturesDirty = function() {
        this._internalMarkAllSubMeshesAsTexturesDirty()
    }
    ,
    i.prototype.isReadyForSubMesh = function(e, t, r, n) {
        return this._isEnabled ? !(e._areTexturesDirty && t.texturesEnabled && (this._texture && MaterialFlags.ClearCoatTextureEnabled && !this._texture.isReadyOrNotBlocking() || this._textureRoughness && MaterialFlags.ClearCoatTextureEnabled && !this._textureRoughness.isReadyOrNotBlocking() || r.getCaps().standardDerivatives && this._bumpTexture && MaterialFlags.ClearCoatBumpTextureEnabled && !n && !this._bumpTexture.isReady() || this._isTintEnabled && this._tintTexture && MaterialFlags.ClearCoatTintTextureEnabled && !this._tintTexture.isReadyOrNotBlocking())) : !0
    }
    ,
    i.prototype.prepareDefines = function(e, t) {
        var r;
        this._isEnabled ? (e.CLEARCOAT = !0,
        e.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE = this._useRoughnessFromMainTexture,
        e.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL = this._texture !== null && this._texture._texture === ((r = this._textureRoughness) === null || r === void 0 ? void 0 : r._texture) && this._texture.checkTransformsAreIdentical(this._textureRoughness),
        e.CLEARCOAT_REMAP_F0 = this._remapF0OnInterfaceChange,
        e._areTexturesDirty && t.texturesEnabled && (this._texture && MaterialFlags.ClearCoatTextureEnabled ? MaterialHelper.PrepareDefinesForMergedUV(this._texture, e, "CLEARCOAT_TEXTURE") : e.CLEARCOAT_TEXTURE = !1,
        this._textureRoughness && MaterialFlags.ClearCoatTextureEnabled ? MaterialHelper.PrepareDefinesForMergedUV(this._textureRoughness, e, "CLEARCOAT_TEXTURE_ROUGHNESS") : e.CLEARCOAT_TEXTURE_ROUGHNESS = !1,
        this._bumpTexture && MaterialFlags.ClearCoatBumpTextureEnabled ? MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, e, "CLEARCOAT_BUMP") : e.CLEARCOAT_BUMP = !1,
        e.CLEARCOAT_DEFAULTIOR = this._indexOfRefraction === i._DefaultIndexOfRefraction,
        this._isTintEnabled ? (e.CLEARCOAT_TINT = !0,
        this._tintTexture && MaterialFlags.ClearCoatTintTextureEnabled ? (MaterialHelper.PrepareDefinesForMergedUV(this._tintTexture, e, "CLEARCOAT_TINT_TEXTURE"),
        e.CLEARCOAT_TINT_GAMMATEXTURE = this._tintTexture.gammaSpace) : e.CLEARCOAT_TINT_TEXTURE = !1) : (e.CLEARCOAT_TINT = !1,
        e.CLEARCOAT_TINT_TEXTURE = !1))) : (e.CLEARCOAT = !1,
        e.CLEARCOAT_TEXTURE = !1,
        e.CLEARCOAT_TEXTURE_ROUGHNESS = !1,
        e.CLEARCOAT_BUMP = !1,
        e.CLEARCOAT_TINT = !1,
        e.CLEARCOAT_TINT_TEXTURE = !1,
        e.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE = !1,
        e.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL = !1)
    }
    ,
    i.prototype.bindForSubMesh = function(e, t, r, n, o, a, s, l) {
        var u, c, h, f, d, _, g, m;
        if (!!this._isEnabled) {
            var v = l.materialDefines
              , y = v.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL;
            if (!e.useUbo || !o || !e.isSync) {
                y && MaterialFlags.ClearCoatTextureEnabled ? (e.updateFloat4("vClearCoatInfos", this._texture.coordinatesIndex, this._texture.level, -1, -1),
                MaterialHelper.BindTextureMatrix(this._texture, e, "clearCoat")) : (this._texture || this._textureRoughness) && MaterialFlags.ClearCoatTextureEnabled && (e.updateFloat4("vClearCoatInfos", (c = (u = this._texture) === null || u === void 0 ? void 0 : u.coordinatesIndex) !== null && c !== void 0 ? c : 0, (f = (h = this._texture) === null || h === void 0 ? void 0 : h.level) !== null && f !== void 0 ? f : 0, (_ = (d = this._textureRoughness) === null || d === void 0 ? void 0 : d.coordinatesIndex) !== null && _ !== void 0 ? _ : 0, (m = (g = this._textureRoughness) === null || g === void 0 ? void 0 : g.level) !== null && m !== void 0 ? m : 0),
                this._texture && MaterialHelper.BindTextureMatrix(this._texture, e, "clearCoat"),
                this._textureRoughness && !y && !v.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE && MaterialHelper.BindTextureMatrix(this._textureRoughness, e, "clearCoatRoughness")),
                this._bumpTexture && r.getCaps().standardDerivatives && MaterialFlags.ClearCoatTextureEnabled && !n && (e.updateFloat2("vClearCoatBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level),
                MaterialHelper.BindTextureMatrix(this._bumpTexture, e, "clearCoatBump"),
                t._mirroredCameraPosition ? e.updateFloat2("vClearCoatTangentSpaceParams", a ? 1 : -1, s ? 1 : -1) : e.updateFloat2("vClearCoatTangentSpaceParams", a ? -1 : 1, s ? -1 : 1)),
                this._tintTexture && MaterialFlags.ClearCoatTintTextureEnabled && (e.updateFloat2("vClearCoatTintInfos", this._tintTexture.coordinatesIndex, this._tintTexture.level),
                MaterialHelper.BindTextureMatrix(this._tintTexture, e, "clearCoatTint")),
                e.updateFloat2("vClearCoatParams", this.intensity, this.roughness);
                var b = 1 - this._indexOfRefraction
                  , T = 1 + this._indexOfRefraction
                  , C = Math.pow(-b / T, 2)
                  , A = 1 / this._indexOfRefraction;
                e.updateFloat4("vClearCoatRefractionParams", C, A, b, T),
                this._isTintEnabled && (e.updateFloat4("vClearCoatTintParams", this.tintColor.r, this.tintColor.g, this.tintColor.b, Math.max(1e-5, this.tintThickness)),
                e.updateFloat("clearCoatColorAtDistance", Math.max(1e-5, this.tintColorAtDistance)))
            }
            t.texturesEnabled && (this._texture && MaterialFlags.ClearCoatTextureEnabled && e.setTexture("clearCoatSampler", this._texture),
            this._textureRoughness && !y && !v.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE && MaterialFlags.ClearCoatTextureEnabled && e.setTexture("clearCoatRoughnessSampler", this._textureRoughness),
            this._bumpTexture && r.getCaps().standardDerivatives && MaterialFlags.ClearCoatBumpTextureEnabled && !n && e.setTexture("clearCoatBumpSampler", this._bumpTexture),
            this._isTintEnabled && this._tintTexture && MaterialFlags.ClearCoatTintTextureEnabled && e.setTexture("clearCoatTintSampler", this._tintTexture))
        }
    }
    ,
    i.prototype.hasTexture = function(e) {
        return this._texture === e || this._textureRoughness === e || this._bumpTexture === e || this._tintTexture === e
    }
    ,
    i.prototype.getActiveTextures = function(e) {
        this._texture && e.push(this._texture),
        this._textureRoughness && e.push(this._textureRoughness),
        this._bumpTexture && e.push(this._bumpTexture),
        this._tintTexture && e.push(this._tintTexture)
    }
    ,
    i.prototype.getAnimatables = function(e) {
        this._texture && this._texture.animations && this._texture.animations.length > 0 && e.push(this._texture),
        this._textureRoughness && this._textureRoughness.animations && this._textureRoughness.animations.length > 0 && e.push(this._textureRoughness),
        this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0 && e.push(this._bumpTexture),
        this._tintTexture && this._tintTexture.animations && this._tintTexture.animations.length > 0 && e.push(this._tintTexture)
    }
    ,
    i.prototype.dispose = function(e) {
        var t, r, n, o;
        e && ((t = this._texture) === null || t === void 0 || t.dispose(),
        (r = this._textureRoughness) === null || r === void 0 || r.dispose(),
        (n = this._bumpTexture) === null || n === void 0 || n.dispose(),
        (o = this._tintTexture) === null || o === void 0 || o.dispose())
    }
    ,
    i.prototype.getClassName = function() {
        return "PBRClearCoatConfiguration"
    }
    ,
    i.AddFallbacks = function(e, t, r) {
        return e.CLEARCOAT_BUMP && t.addFallback(r++, "CLEARCOAT_BUMP"),
        e.CLEARCOAT_TINT && t.addFallback(r++, "CLEARCOAT_TINT"),
        e.CLEARCOAT && t.addFallback(r++, "CLEARCOAT"),
        r
    }
    ,
    i.AddUniforms = function(e) {
        e.push("vClearCoatTangentSpaceParams", "vClearCoatParams", "vClearCoatRefractionParams", "vClearCoatTintParams", "clearCoatColorAtDistance", "clearCoatMatrix", "clearCoatRoughnessMatrix", "clearCoatBumpMatrix", "clearCoatTintMatrix", "vClearCoatInfos", "vClearCoatBumpInfos", "vClearCoatTintInfos")
    }
    ,
    i.AddSamplers = function(e) {
        e.push("clearCoatSampler", "clearCoatRoughnessSampler", "clearCoatBumpSampler", "clearCoatTintSampler")
    }
    ,
    i.PrepareUniformBuffer = function(e) {
        e.addUniform("vClearCoatParams", 2),
        e.addUniform("vClearCoatRefractionParams", 4),
        e.addUniform("vClearCoatInfos", 4),
        e.addUniform("clearCoatMatrix", 16),
        e.addUniform("clearCoatRoughnessMatrix", 16),
        e.addUniform("vClearCoatBumpInfos", 2),
        e.addUniform("vClearCoatTangentSpaceParams", 2),
        e.addUniform("clearCoatBumpMatrix", 16),
        e.addUniform("vClearCoatTintParams", 4),
        e.addUniform("clearCoatColorAtDistance", 1),
        e.addUniform("vClearCoatTintInfos", 2),
        e.addUniform("clearCoatTintMatrix", 16)
    }
    ,
    i.prototype.copyTo = function(e) {
        SerializationHelper.Clone(function() {
            return e
        }, this)
    }
    ,
    i.prototype.serialize = function() {
        return SerializationHelper.Serialize(this)
    }
    ,
    i.prototype.parse = function(e, t, r) {
        var n = this;
        SerializationHelper.Parse(function() {
            return n
        }, e, t, r)
    }
    ,
    i._DefaultIndexOfRefraction = 1.5,
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], i.prototype, "isEnabled", void 0),
    __decorate([serialize()], i.prototype, "intensity", void 0),
    __decorate([serialize()], i.prototype, "roughness", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], i.prototype, "indexOfRefraction", void 0),
    __decorate([serializeAsTexture(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], i.prototype, "texture", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], i.prototype, "useRoughnessFromMainTexture", void 0),
    __decorate([serializeAsTexture(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], i.prototype, "textureRoughness", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], i.prototype, "remapF0OnInterfaceChange", void 0),
    __decorate([serializeAsTexture(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], i.prototype, "bumpTexture", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], i.prototype, "isTintEnabled", void 0),
    __decorate([serializeAsColor3()], i.prototype, "tintColor", void 0),
    __decorate([serialize()], i.prototype, "tintColorAtDistance", void 0),
    __decorate([serialize()], i.prototype, "tintThickness", void 0),
    __decorate([serializeAsTexture(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], i.prototype, "tintTexture", void 0),
    i
}()
  , PBRAnisotropicConfiguration = function() {
    function i(e) {
        this._isEnabled = !1,
        this.isEnabled = !1,
        this.intensity = 1,
        this.direction = new Vector2(1,0),
        this._texture = null,
        this.texture = null,
        this._internalMarkAllSubMeshesAsTexturesDirty = e
    }
    return i.prototype._markAllSubMeshesAsTexturesDirty = function() {
        this._internalMarkAllSubMeshesAsTexturesDirty()
    }
    ,
    i.prototype.isReadyForSubMesh = function(e, t) {
        return this._isEnabled ? !(e._areTexturesDirty && t.texturesEnabled && this._texture && MaterialFlags.AnisotropicTextureEnabled && !this._texture.isReadyOrNotBlocking()) : !0
    }
    ,
    i.prototype.prepareDefines = function(e, t, r) {
        this._isEnabled ? (e.ANISOTROPIC = this._isEnabled,
        this._isEnabled && !t.isVerticesDataPresent(VertexBuffer.TangentKind) && (e._needUVs = !0,
        e.MAINUV1 = !0),
        e._areTexturesDirty && r.texturesEnabled && (this._texture && MaterialFlags.AnisotropicTextureEnabled ? MaterialHelper.PrepareDefinesForMergedUV(this._texture, e, "ANISOTROPIC_TEXTURE") : e.ANISOTROPIC_TEXTURE = !1)) : (e.ANISOTROPIC = !1,
        e.ANISOTROPIC_TEXTURE = !1)
    }
    ,
    i.prototype.bindForSubMesh = function(e, t, r) {
        !this._isEnabled || ((!e.useUbo || !r || !e.isSync) && (this._texture && MaterialFlags.AnisotropicTextureEnabled && (e.updateFloat2("vAnisotropyInfos", this._texture.coordinatesIndex, this._texture.level),
        MaterialHelper.BindTextureMatrix(this._texture, e, "anisotropy")),
        e.updateFloat3("vAnisotropy", this.direction.x, this.direction.y, this.intensity)),
        t.texturesEnabled && this._texture && MaterialFlags.AnisotropicTextureEnabled && e.setTexture("anisotropySampler", this._texture))
    }
    ,
    i.prototype.hasTexture = function(e) {
        return this._texture === e
    }
    ,
    i.prototype.getActiveTextures = function(e) {
        this._texture && e.push(this._texture)
    }
    ,
    i.prototype.getAnimatables = function(e) {
        this._texture && this._texture.animations && this._texture.animations.length > 0 && e.push(this._texture)
    }
    ,
    i.prototype.dispose = function(e) {
        e && this._texture && this._texture.dispose()
    }
    ,
    i.prototype.getClassName = function() {
        return "PBRAnisotropicConfiguration"
    }
    ,
    i.AddFallbacks = function(e, t, r) {
        return e.ANISOTROPIC && t.addFallback(r++, "ANISOTROPIC"),
        r
    }
    ,
    i.AddUniforms = function(e) {
        e.push("vAnisotropy", "vAnisotropyInfos", "anisotropyMatrix")
    }
    ,
    i.PrepareUniformBuffer = function(e) {
        e.addUniform("vAnisotropy", 3),
        e.addUniform("vAnisotropyInfos", 2),
        e.addUniform("anisotropyMatrix", 16)
    }
    ,
    i.AddSamplers = function(e) {
        e.push("anisotropySampler")
    }
    ,
    i.prototype.copyTo = function(e) {
        SerializationHelper.Clone(function() {
            return e
        }, this)
    }
    ,
    i.prototype.serialize = function() {
        return SerializationHelper.Serialize(this)
    }
    ,
    i.prototype.parse = function(e, t, r) {
        var n = this;
        SerializationHelper.Parse(function() {
            return n
        }, e, t, r)
    }
    ,
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], i.prototype, "isEnabled", void 0),
    __decorate([serialize()], i.prototype, "intensity", void 0),
    __decorate([serializeAsVector2()], i.prototype, "direction", void 0),
    __decorate([serializeAsTexture(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], i.prototype, "texture", void 0),
    i
}()
  , PBRBRDFConfiguration = function() {
    function i(e) {
        this._useEnergyConservation = i.DEFAULT_USE_ENERGY_CONSERVATION,
        this.useEnergyConservation = i.DEFAULT_USE_ENERGY_CONSERVATION,
        this._useSmithVisibilityHeightCorrelated = i.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,
        this.useSmithVisibilityHeightCorrelated = i.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,
        this._useSphericalHarmonics = i.DEFAULT_USE_SPHERICAL_HARMONICS,
        this.useSphericalHarmonics = i.DEFAULT_USE_SPHERICAL_HARMONICS,
        this._useSpecularGlossinessInputEnergyConservation = i.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,
        this.useSpecularGlossinessInputEnergyConservation = i.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,
        this._internalMarkAllSubMeshesAsMiscDirty = e
    }
    return i.prototype._markAllSubMeshesAsMiscDirty = function() {
        this._internalMarkAllSubMeshesAsMiscDirty()
    }
    ,
    i.prototype.prepareDefines = function(e) {
        e.BRDF_V_HEIGHT_CORRELATED = this._useSmithVisibilityHeightCorrelated,
        e.MS_BRDF_ENERGY_CONSERVATION = this._useEnergyConservation && this._useSmithVisibilityHeightCorrelated,
        e.SPHERICAL_HARMONICS = this._useSphericalHarmonics,
        e.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION = this._useSpecularGlossinessInputEnergyConservation
    }
    ,
    i.prototype.getClassName = function() {
        return "PBRBRDFConfiguration"
    }
    ,
    i.prototype.copyTo = function(e) {
        SerializationHelper.Clone(function() {
            return e
        }, this)
    }
    ,
    i.prototype.serialize = function() {
        return SerializationHelper.Serialize(this)
    }
    ,
    i.prototype.parse = function(e, t, r) {
        var n = this;
        SerializationHelper.Parse(function() {
            return n
        }, e, t, r)
    }
    ,
    i.DEFAULT_USE_ENERGY_CONSERVATION = !0,
    i.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED = !0,
    i.DEFAULT_USE_SPHERICAL_HARMONICS = !0,
    i.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION = !0,
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsMiscDirty")], i.prototype, "useEnergyConservation", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsMiscDirty")], i.prototype, "useSmithVisibilityHeightCorrelated", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsMiscDirty")], i.prototype, "useSphericalHarmonics", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsMiscDirty")], i.prototype, "useSpecularGlossinessInputEnergyConservation", void 0),
    i
}()
  , PBRSheenConfiguration = function() {
    function i(e) {
        this._isEnabled = !1,
        this.isEnabled = !1,
        this._linkSheenWithAlbedo = !1,
        this.linkSheenWithAlbedo = !1,
        this.intensity = 1,
        this.color = Color3.White(),
        this._texture = null,
        this.texture = null,
        this._useRoughnessFromMainTexture = !0,
        this.useRoughnessFromMainTexture = !0,
        this._roughness = null,
        this.roughness = null,
        this._textureRoughness = null,
        this.textureRoughness = null,
        this._albedoScaling = !1,
        this.albedoScaling = !1,
        this._internalMarkAllSubMeshesAsTexturesDirty = e
    }
    return i.prototype._markAllSubMeshesAsTexturesDirty = function() {
        this._internalMarkAllSubMeshesAsTexturesDirty()
    }
    ,
    i.prototype.isReadyForSubMesh = function(e, t) {
        return this._isEnabled ? !(e._areTexturesDirty && t.texturesEnabled && (this._texture && MaterialFlags.SheenTextureEnabled && !this._texture.isReadyOrNotBlocking() || this._textureRoughness && MaterialFlags.SheenTextureEnabled && !this._textureRoughness.isReadyOrNotBlocking())) : !0
    }
    ,
    i.prototype.prepareDefines = function(e, t) {
        var r;
        this._isEnabled ? (e.SHEEN = this._isEnabled,
        e.SHEEN_LINKWITHALBEDO = this._linkSheenWithAlbedo,
        e.SHEEN_ROUGHNESS = this._roughness !== null,
        e.SHEEN_ALBEDOSCALING = this._albedoScaling,
        e.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE = this._useRoughnessFromMainTexture,
        e.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL = this._texture !== null && this._texture._texture === ((r = this._textureRoughness) === null || r === void 0 ? void 0 : r._texture) && this._texture.checkTransformsAreIdentical(this._textureRoughness),
        e._areTexturesDirty && t.texturesEnabled && (this._texture && MaterialFlags.SheenTextureEnabled ? (MaterialHelper.PrepareDefinesForMergedUV(this._texture, e, "SHEEN_TEXTURE"),
        e.SHEEN_GAMMATEXTURE = this._texture.gammaSpace) : e.SHEEN_TEXTURE = !1,
        this._textureRoughness && MaterialFlags.SheenTextureEnabled ? MaterialHelper.PrepareDefinesForMergedUV(this._textureRoughness, e, "SHEEN_TEXTURE_ROUGHNESS") : e.SHEEN_TEXTURE_ROUGHNESS = !1)) : (e.SHEEN = !1,
        e.SHEEN_TEXTURE = !1,
        e.SHEEN_TEXTURE_ROUGHNESS = !1,
        e.SHEEN_LINKWITHALBEDO = !1,
        e.SHEEN_ROUGHNESS = !1,
        e.SHEEN_ALBEDOSCALING = !1,
        e.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE = !1,
        e.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL = !1)
    }
    ,
    i.prototype.bindForSubMesh = function(e, t, r, n) {
        var o, a, s, l, u, c, h, f;
        if (!!this._isEnabled) {
            var d = n.materialDefines
              , _ = d.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL;
            (!e.useUbo || !r || !e.isSync) && (_ && MaterialFlags.SheenTextureEnabled ? (e.updateFloat4("vSheenInfos", this._texture.coordinatesIndex, this._texture.level, -1, -1),
            MaterialHelper.BindTextureMatrix(this._texture, e, "sheen")) : (this._texture || this._textureRoughness) && MaterialFlags.SheenTextureEnabled && (e.updateFloat4("vSheenInfos", (a = (o = this._texture) === null || o === void 0 ? void 0 : o.coordinatesIndex) !== null && a !== void 0 ? a : 0, (l = (s = this._texture) === null || s === void 0 ? void 0 : s.level) !== null && l !== void 0 ? l : 0, (c = (u = this._textureRoughness) === null || u === void 0 ? void 0 : u.coordinatesIndex) !== null && c !== void 0 ? c : 0, (f = (h = this._textureRoughness) === null || h === void 0 ? void 0 : h.level) !== null && f !== void 0 ? f : 0),
            this._texture && MaterialHelper.BindTextureMatrix(this._texture, e, "sheen"),
            this._textureRoughness && !_ && !d.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE && MaterialHelper.BindTextureMatrix(this._textureRoughness, e, "sheenRoughness")),
            e.updateFloat4("vSheenColor", this.color.r, this.color.g, this.color.b, this.intensity),
            this._roughness !== null && e.updateFloat("vSheenRoughness", this._roughness)),
            t.texturesEnabled && (this._texture && MaterialFlags.SheenTextureEnabled && e.setTexture("sheenSampler", this._texture),
            this._textureRoughness && !_ && !d.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE && MaterialFlags.SheenTextureEnabled && e.setTexture("sheenRoughnessSampler", this._textureRoughness))
        }
    }
    ,
    i.prototype.hasTexture = function(e) {
        return this._texture === e || this._textureRoughness === e
    }
    ,
    i.prototype.getActiveTextures = function(e) {
        this._texture && e.push(this._texture),
        this._textureRoughness && e.push(this._textureRoughness)
    }
    ,
    i.prototype.getAnimatables = function(e) {
        this._texture && this._texture.animations && this._texture.animations.length > 0 && e.push(this._texture),
        this._textureRoughness && this._textureRoughness.animations && this._textureRoughness.animations.length > 0 && e.push(this._textureRoughness)
    }
    ,
    i.prototype.dispose = function(e) {
        var t, r;
        e && ((t = this._texture) === null || t === void 0 || t.dispose(),
        (r = this._textureRoughness) === null || r === void 0 || r.dispose())
    }
    ,
    i.prototype.getClassName = function() {
        return "PBRSheenConfiguration"
    }
    ,
    i.AddFallbacks = function(e, t, r) {
        return e.SHEEN && t.addFallback(r++, "SHEEN"),
        r
    }
    ,
    i.AddUniforms = function(e) {
        e.push("vSheenColor", "vSheenRoughness", "vSheenInfos", "sheenMatrix", "sheenRoughnessMatrix")
    }
    ,
    i.PrepareUniformBuffer = function(e) {
        e.addUniform("vSheenColor", 4),
        e.addUniform("vSheenRoughness", 1),
        e.addUniform("vSheenInfos", 4),
        e.addUniform("sheenMatrix", 16),
        e.addUniform("sheenRoughnessMatrix", 16)
    }
    ,
    i.AddSamplers = function(e) {
        e.push("sheenSampler"),
        e.push("sheenRoughnessSampler")
    }
    ,
    i.prototype.copyTo = function(e) {
        SerializationHelper.Clone(function() {
            return e
        }, this)
    }
    ,
    i.prototype.serialize = function() {
        return SerializationHelper.Serialize(this)
    }
    ,
    i.prototype.parse = function(e, t, r) {
        var n = this;
        SerializationHelper.Parse(function() {
            return n
        }, e, t, r)
    }
    ,
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], i.prototype, "isEnabled", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], i.prototype, "linkSheenWithAlbedo", void 0),
    __decorate([serialize()], i.prototype, "intensity", void 0),
    __decorate([serializeAsColor3()], i.prototype, "color", void 0),
    __decorate([serializeAsTexture(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], i.prototype, "texture", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], i.prototype, "useRoughnessFromMainTexture", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], i.prototype, "roughness", void 0),
    __decorate([serializeAsTexture(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], i.prototype, "textureRoughness", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], i.prototype, "albedoScaling", void 0),
    i
}()
  , PBRSubSurfaceConfiguration = function() {
    function i(e, t, r) {
        this._isRefractionEnabled = !1,
        this.isRefractionEnabled = !1,
        this._isTranslucencyEnabled = !1,
        this.isTranslucencyEnabled = !1,
        this._isScatteringEnabled = !1,
        this.isScatteringEnabled = !1,
        this._scatteringDiffusionProfileIndex = 0,
        this.refractionIntensity = 1,
        this.translucencyIntensity = 1,
        this.useAlbedoToTintRefraction = !1,
        this.useAlbedoToTintTranslucency = !1,
        this._thicknessTexture = null,
        this.thicknessTexture = null,
        this._refractionTexture = null,
        this.refractionTexture = null,
        this._indexOfRefraction = 1.5,
        this.indexOfRefraction = 1.5,
        this._volumeIndexOfRefraction = -1,
        this._invertRefractionY = !1,
        this.invertRefractionY = !1,
        this._linkRefractionWithTransparency = !1,
        this.linkRefractionWithTransparency = !1,
        this.minimumThickness = 0,
        this.maximumThickness = 1,
        this.useThicknessAsDepth = !1,
        this.tintColor = Color3.White(),
        this.tintColorAtDistance = 1,
        this.diffusionDistance = Color3.White(),
        this._useMaskFromThicknessTexture = !1,
        this.useMaskFromThicknessTexture = !1,
        this._refractionIntensityTexture = null,
        this.refractionIntensityTexture = null,
        this._translucencyIntensityTexture = null,
        this.translucencyIntensityTexture = null,
        this._useGltfStyleTextures = !1,
        this.useGltfStyleTextures = !1,
        this._internalMarkAllSubMeshesAsTexturesDirty = e,
        this._internalMarkScenePrePassDirty = t,
        this._scene = r
    }
    return Object.defineProperty(i.prototype, "scatteringDiffusionProfile", {
        get: function() {
            return this._scene.subSurfaceConfiguration ? this._scene.subSurfaceConfiguration.ssDiffusionProfileColors[this._scatteringDiffusionProfileIndex] : null
        },
        set: function(e) {
            !this._scene.enableSubSurfaceForPrePass() || e && (this._scatteringDiffusionProfileIndex = this._scene.subSurfaceConfiguration.addDiffusionProfile(e))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "volumeIndexOfRefraction", {
        get: function() {
            return this._volumeIndexOfRefraction >= 1 ? this._volumeIndexOfRefraction : this._indexOfRefraction
        },
        set: function(e) {
            e >= 1 ? this._volumeIndexOfRefraction = e : this._volumeIndexOfRefraction = -1
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype._markAllSubMeshesAsTexturesDirty = function() {
        this._internalMarkAllSubMeshesAsTexturesDirty()
    }
    ,
    i.prototype._markScenePrePassDirty = function() {
        this._internalMarkAllSubMeshesAsTexturesDirty(),
        this._internalMarkScenePrePassDirty()
    }
    ,
    i.prototype.isReadyForSubMesh = function(e, t) {
        if (!this._isRefractionEnabled && !this._isTranslucencyEnabled && !this._isScatteringEnabled)
            return !0;
        if (e._areTexturesDirty && t.texturesEnabled) {
            if (this._thicknessTexture && MaterialFlags.ThicknessTextureEnabled && !this._thicknessTexture.isReadyOrNotBlocking())
                return !1;
            var r = this._getRefractionTexture(t);
            if (r && MaterialFlags.RefractionTextureEnabled && !r.isReadyOrNotBlocking())
                return !1
        }
        return !0
    }
    ,
    i.prototype.prepareDefines = function(e, t) {
        if (!this._isRefractionEnabled && !this._isTranslucencyEnabled && !this._isScatteringEnabled) {
            e.SUBSURFACE = !1,
            e.SS_TRANSLUCENCY = !1,
            e.SS_SCATTERING = !1,
            e.SS_REFRACTION = !1;
            return
        }
        if (e._areTexturesDirty) {
            if (e.SUBSURFACE = !1,
            e.SS_TRANSLUCENCY = this._isTranslucencyEnabled,
            e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE = !1,
            e.SS_SCATTERING = this._isScatteringEnabled,
            e.SS_THICKNESSANDMASK_TEXTURE = !1,
            e.SS_REFRACTIONINTENSITY_TEXTURE = !1,
            e.SS_TRANSLUCENCYINTENSITY_TEXTURE = !1,
            e.SS_HAS_THICKNESS = !1,
            e.SS_MASK_FROM_THICKNESS_TEXTURE = !1,
            e.SS_USE_GLTF_TEXTURES = !1,
            e.SS_REFRACTION = !1,
            e.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE = !1,
            e.SS_REFRACTIONMAP_3D = !1,
            e.SS_GAMMAREFRACTION = !1,
            e.SS_RGBDREFRACTION = !1,
            e.SS_LINEARSPECULARREFRACTION = !1,
            e.SS_REFRACTIONMAP_OPPOSITEZ = !1,
            e.SS_LODINREFRACTIONALPHA = !1,
            e.SS_LINKREFRACTIONTOTRANSPARENCY = !1,
            e.SS_ALBEDOFORREFRACTIONTINT = !1,
            e.SS_ALBEDOFORTRANSLUCENCYTINT = !1,
            e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC = !1,
            e.SS_USE_THICKNESS_AS_DEPTH = !1,
            this._isRefractionEnabled || this._isTranslucencyEnabled || this._isScatteringEnabled) {
                e.SUBSURFACE = !0;
                var r = !!this._thicknessTexture && !!this._refractionIntensityTexture && this._refractionIntensityTexture.checkTransformsAreIdentical(this._thicknessTexture) && this._refractionIntensityTexture._texture === this._thicknessTexture._texture
                  , n = !!this._thicknessTexture && !!this._translucencyIntensityTexture && this._translucencyIntensityTexture.checkTransformsAreIdentical(this._thicknessTexture) && this._translucencyIntensityTexture._texture === this._thicknessTexture._texture
                  , o = (r || !this._refractionIntensityTexture) && (n || !this._translucencyIntensityTexture);
                e._areTexturesDirty && t.texturesEnabled && (this._thicknessTexture && MaterialFlags.ThicknessTextureEnabled && MaterialHelper.PrepareDefinesForMergedUV(this._thicknessTexture, e, "SS_THICKNESSANDMASK_TEXTURE"),
                this._refractionIntensityTexture && MaterialFlags.RefractionIntensityTextureEnabled && !o && MaterialHelper.PrepareDefinesForMergedUV(this._refractionIntensityTexture, e, "SS_REFRACTIONINTENSITY_TEXTURE"),
                this._translucencyIntensityTexture && MaterialFlags.TranslucencyIntensityTextureEnabled && !o && MaterialHelper.PrepareDefinesForMergedUV(this._translucencyIntensityTexture, e, "SS_TRANSLUCENCYINTENSITY_TEXTURE")),
                e.SS_HAS_THICKNESS = this.maximumThickness - this.minimumThickness !== 0,
                e.SS_MASK_FROM_THICKNESS_TEXTURE = (this._useMaskFromThicknessTexture || !!this._refractionIntensityTexture || !!this._translucencyIntensityTexture) && o,
                e.SS_USE_GLTF_TEXTURES = this._useGltfStyleTextures,
                e.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE = (this._useMaskFromThicknessTexture || !!this._refractionIntensityTexture) && o,
                e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE = (this._useMaskFromThicknessTexture || !!this._translucencyIntensityTexture) && o
            }
            if (this._isRefractionEnabled && t.texturesEnabled) {
                var a = this._getRefractionTexture(t);
                a && MaterialFlags.RefractionTextureEnabled && (e.SS_REFRACTION = !0,
                e.SS_REFRACTIONMAP_3D = a.isCube,
                e.SS_GAMMAREFRACTION = a.gammaSpace,
                e.SS_RGBDREFRACTION = a.isRGBD,
                e.SS_LINEARSPECULARREFRACTION = a.linearSpecularLOD,
                e.SS_REFRACTIONMAP_OPPOSITEZ = a.invertZ,
                e.SS_LODINREFRACTIONALPHA = a.lodLevelInAlpha,
                e.SS_LINKREFRACTIONTOTRANSPARENCY = this._linkRefractionWithTransparency,
                e.SS_ALBEDOFORREFRACTIONTINT = this.useAlbedoToTintRefraction,
                e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC = a.isCube && a.boundingBoxSize,
                e.SS_USE_THICKNESS_AS_DEPTH = this.useThicknessAsDepth)
            }
            this._isTranslucencyEnabled && (e.SS_ALBEDOFORTRANSLUCENCYTINT = this.useAlbedoToTintTranslucency)
        }
    }
    ,
    i.prototype.hardBindForSubMesh = function(e, t, r, n, o, a, s) {
        if (!(!this._isRefractionEnabled && !this._isTranslucencyEnabled && !this._isScatteringEnabled)) {
            s.getRenderingMesh().getWorldMatrix().decompose(TmpVectors.Vector3[0]);
            var l = Math.max(Math.abs(TmpVectors.Vector3[0].x), Math.abs(TmpVectors.Vector3[0].y), Math.abs(TmpVectors.Vector3[0].z));
            e.updateFloat2("vThicknessParam", this.minimumThickness * l, (this.maximumThickness - this.minimumThickness) * l)
        }
    }
    ,
    i.prototype.bindForSubMesh = function(e, t, r, n, o, a, s) {
        if (!(!this._isRefractionEnabled && !this._isTranslucencyEnabled && !this._isScatteringEnabled)) {
            var l = s.materialDefines
              , u = this._getRefractionTexture(t);
            if (!e.useUbo || !n || !e.isSync) {
                if (this._thicknessTexture && MaterialFlags.ThicknessTextureEnabled && (e.updateFloat2("vThicknessInfos", this._thicknessTexture.coordinatesIndex, this._thicknessTexture.level),
                MaterialHelper.BindTextureMatrix(this._thicknessTexture, e, "thickness")),
                this._refractionIntensityTexture && MaterialFlags.RefractionIntensityTextureEnabled && l.SS_REFRACTIONINTENSITY_TEXTURE && (e.updateFloat2("vRefractionIntensityInfos", this._refractionIntensityTexture.coordinatesIndex, this._refractionIntensityTexture.level),
                MaterialHelper.BindTextureMatrix(this._refractionIntensityTexture, e, "refractionIntensity")),
                this._translucencyIntensityTexture && MaterialFlags.TranslucencyIntensityTextureEnabled && l.SS_TRANSLUCENCYINTENSITY_TEXTURE && (e.updateFloat2("vTranslucencyIntensityInfos", this._translucencyIntensityTexture.coordinatesIndex, this._translucencyIntensityTexture.level),
                MaterialHelper.BindTextureMatrix(this._translucencyIntensityTexture, e, "translucencyIntensity")),
                u && MaterialFlags.RefractionTextureEnabled) {
                    e.updateMatrix("refractionMatrix", u.getReflectionTextureMatrix());
                    var c = 1;
                    u.isCube || u.depth && (c = u.depth);
                    var h = u.getSize().width
                      , f = this.volumeIndexOfRefraction;
                    if (e.updateFloat4("vRefractionInfos", u.level, 1 / f, c, this._invertRefractionY ? -1 : 1),
                    e.updateFloat4("vRefractionMicrosurfaceInfos", h, u.lodGenerationScale, u.lodGenerationOffset, 1 / this.indexOfRefraction),
                    a && e.updateFloat2("vRefractionFilteringInfo", h, Scalar.Log2(h)),
                    u.boundingBoxSize) {
                        var d = u;
                        e.updateVector3("vRefractionPosition", d.boundingBoxPosition),
                        e.updateVector3("vRefractionSize", d.boundingBoxSize)
                    }
                }
                this.isScatteringEnabled && e.updateFloat("scatteringDiffusionProfile", this._scatteringDiffusionProfileIndex),
                e.updateColor3("vDiffusionDistance", this.diffusionDistance),
                e.updateFloat4("vTintColor", this.tintColor.r, this.tintColor.g, this.tintColor.b, Math.max(1e-5, this.tintColorAtDistance)),
                e.updateFloat3("vSubSurfaceIntensity", this.refractionIntensity, this.translucencyIntensity, 0)
            }
            t.texturesEnabled && (this._thicknessTexture && MaterialFlags.ThicknessTextureEnabled && e.setTexture("thicknessSampler", this._thicknessTexture),
            this._refractionIntensityTexture && MaterialFlags.RefractionIntensityTextureEnabled && l.SS_REFRACTIONINTENSITY_TEXTURE && e.setTexture("refractionIntensitySampler", this._refractionIntensityTexture),
            this._translucencyIntensityTexture && MaterialFlags.TranslucencyIntensityTextureEnabled && l.SS_TRANSLUCENCYINTENSITY_TEXTURE && e.setTexture("translucencyIntensitySampler", this._translucencyIntensityTexture),
            u && MaterialFlags.RefractionTextureEnabled && (o ? e.setTexture("refractionSampler", u) : (e.setTexture("refractionSampler", u._lodTextureMid || u),
            e.setTexture("refractionSamplerLow", u._lodTextureLow || u),
            e.setTexture("refractionSamplerHigh", u._lodTextureHigh || u))))
        }
    }
    ,
    i.prototype.unbind = function(e) {
        return this._refractionTexture && this._refractionTexture.isRenderTarget ? (e.setTexture("refractionSampler", null),
        !0) : !1
    }
    ,
    i.prototype._getRefractionTexture = function(e) {
        return this._refractionTexture ? this._refractionTexture : this._isRefractionEnabled ? e.environmentTexture : null
    }
    ,
    Object.defineProperty(i.prototype, "disableAlphaBlending", {
        get: function() {
            return this.isRefractionEnabled && this._linkRefractionWithTransparency
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.fillRenderTargetTextures = function(e) {
        MaterialFlags.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget && e.push(this._refractionTexture)
    }
    ,
    i.prototype.hasTexture = function(e) {
        return this._thicknessTexture === e || this._refractionTexture === e
    }
    ,
    i.prototype.hasRenderTargetTextures = function() {
        return !!(MaterialFlags.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget)
    }
    ,
    i.prototype.getActiveTextures = function(e) {
        this._thicknessTexture && e.push(this._thicknessTexture),
        this._refractionTexture && e.push(this._refractionTexture)
    }
    ,
    i.prototype.getAnimatables = function(e) {
        this._thicknessTexture && this._thicknessTexture.animations && this._thicknessTexture.animations.length > 0 && e.push(this._thicknessTexture),
        this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0 && e.push(this._refractionTexture)
    }
    ,
    i.prototype.dispose = function(e) {
        e && (this._thicknessTexture && this._thicknessTexture.dispose(),
        this._refractionTexture && this._refractionTexture.dispose())
    }
    ,
    i.prototype.getClassName = function() {
        return "PBRSubSurfaceConfiguration"
    }
    ,
    i.AddFallbacks = function(e, t, r) {
        return e.SS_SCATTERING && t.addFallback(r++, "SS_SCATTERING"),
        e.SS_TRANSLUCENCY && t.addFallback(r++, "SS_TRANSLUCENCY"),
        r
    }
    ,
    i.AddUniforms = function(e) {
        e.push("vDiffusionDistance", "vTintColor", "vSubSurfaceIntensity", "vRefractionMicrosurfaceInfos", "vRefractionFilteringInfo", "vRefractionInfos", "vThicknessInfos", "vRefractionIntensityInfos", "vTranslucencyIntensityInfos", "vThicknessParam", "vRefractionPosition", "vRefractionSize", "refractionMatrix", "thicknessMatrix", "refractionIntensityMatrix", "translucencyIntensityMatrix", "scatteringDiffusionProfile")
    }
    ,
    i.AddSamplers = function(e) {
        e.push("thicknessSampler", "refractionIntensitySampler", "translucencyIntensitySampler", "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh")
    }
    ,
    i.PrepareUniformBuffer = function(e) {
        e.addUniform("vRefractionMicrosurfaceInfos", 4),
        e.addUniform("vRefractionFilteringInfo", 2),
        e.addUniform("vTranslucencyIntensityInfos", 2),
        e.addUniform("vRefractionInfos", 4),
        e.addUniform("refractionMatrix", 16),
        e.addUniform("vThicknessInfos", 2),
        e.addUniform("vRefractionIntensityInfos", 2),
        e.addUniform("thicknessMatrix", 16),
        e.addUniform("refractionIntensityMatrix", 16),
        e.addUniform("translucencyIntensityMatrix", 16),
        e.addUniform("vThicknessParam", 2),
        e.addUniform("vDiffusionDistance", 3),
        e.addUniform("vTintColor", 4),
        e.addUniform("vSubSurfaceIntensity", 3),
        e.addUniform("vRefractionPosition", 3),
        e.addUniform("vRefractionSize", 3),
        e.addUniform("scatteringDiffusionProfile", 1)
    }
    ,
    i.prototype.copyTo = function(e) {
        SerializationHelper.Clone(function() {
            return e
        }, this)
    }
    ,
    i.prototype.serialize = function() {
        return SerializationHelper.Serialize(this)
    }
    ,
    i.prototype.parse = function(e, t, r) {
        var n = this;
        SerializationHelper.Parse(function() {
            return n
        }, e, t, r)
    }
    ,
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], i.prototype, "isRefractionEnabled", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], i.prototype, "isTranslucencyEnabled", void 0),
    __decorate([serialize(), expandToProperty("_markScenePrePassDirty")], i.prototype, "isScatteringEnabled", void 0),
    __decorate([serialize()], i.prototype, "_scatteringDiffusionProfileIndex", void 0),
    __decorate([serialize()], i.prototype, "refractionIntensity", void 0),
    __decorate([serialize()], i.prototype, "translucencyIntensity", void 0),
    __decorate([serialize()], i.prototype, "useAlbedoToTintRefraction", void 0),
    __decorate([serialize()], i.prototype, "useAlbedoToTintTranslucency", void 0),
    __decorate([serializeAsTexture(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], i.prototype, "thicknessTexture", void 0),
    __decorate([serializeAsTexture(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], i.prototype, "refractionTexture", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], i.prototype, "indexOfRefraction", void 0),
    __decorate([serialize()], i.prototype, "_volumeIndexOfRefraction", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")], i.prototype, "volumeIndexOfRefraction", null),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], i.prototype, "invertRefractionY", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], i.prototype, "linkRefractionWithTransparency", void 0),
    __decorate([serialize()], i.prototype, "minimumThickness", void 0),
    __decorate([serialize()], i.prototype, "maximumThickness", void 0),
    __decorate([serialize()], i.prototype, "useThicknessAsDepth", void 0),
    __decorate([serializeAsColor3()], i.prototype, "tintColor", void 0),
    __decorate([serialize()], i.prototype, "tintColorAtDistance", void 0),
    __decorate([serializeAsColor3()], i.prototype, "diffusionDistance", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], i.prototype, "useMaskFromThicknessTexture", void 0),
    __decorate([serializeAsTexture(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], i.prototype, "refractionIntensityTexture", void 0),
    __decorate([serializeAsTexture(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], i.prototype, "translucencyIntensityTexture", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], i.prototype, "useGltfStyleTextures", void 0),
    i
}()
  , SH3ylmBasisConstants = [Math.sqrt(1 / (4 * Math.PI)), -Math.sqrt(3 / (4 * Math.PI)), Math.sqrt(3 / (4 * Math.PI)), -Math.sqrt(3 / (4 * Math.PI)), Math.sqrt(15 / (4 * Math.PI)), -Math.sqrt(15 / (4 * Math.PI)), Math.sqrt(5 / (16 * Math.PI)), -Math.sqrt(15 / (4 * Math.PI)), Math.sqrt(15 / (16 * Math.PI))]
  , SH3ylmBasisTrigonometricTerms = [function(i) {
    return 1
}
, function(i) {
    return i.y
}
, function(i) {
    return i.z
}
, function(i) {
    return i.x
}
, function(i) {
    return i.x * i.y
}
, function(i) {
    return i.y * i.z
}
, function(i) {
    return 3 * i.z * i.z - 1
}
, function(i) {
    return i.x * i.z
}
, function(i) {
    return i.x * i.x - i.y * i.y
}
]
  , applySH3 = function(i, e) {
    return SH3ylmBasisConstants[i] * SH3ylmBasisTrigonometricTerms[i](e)
}
  , SHCosKernelConvolution = [Math.PI, 2 * Math.PI / 3, 2 * Math.PI / 3, 2 * Math.PI / 3, Math.PI / 4, Math.PI / 4, Math.PI / 4, Math.PI / 4, Math.PI / 4]
  , SphericalHarmonics = function() {
    function i() {
        this.preScaled = !1,
        this.l00 = Vector3.Zero(),
        this.l1_1 = Vector3.Zero(),
        this.l10 = Vector3.Zero(),
        this.l11 = Vector3.Zero(),
        this.l2_2 = Vector3.Zero(),
        this.l2_1 = Vector3.Zero(),
        this.l20 = Vector3.Zero(),
        this.l21 = Vector3.Zero(),
        this.l22 = Vector3.Zero()
    }
    return i.prototype.addLight = function(e, t, r) {
        TmpVectors.Vector3[0].set(t.r, t.g, t.b);
        var n = TmpVectors.Vector3[0]
          , o = TmpVectors.Vector3[1];
        n.scaleToRef(r, o),
        o.scaleToRef(applySH3(0, e), TmpVectors.Vector3[2]),
        this.l00.addInPlace(TmpVectors.Vector3[2]),
        o.scaleToRef(applySH3(1, e), TmpVectors.Vector3[2]),
        this.l1_1.addInPlace(TmpVectors.Vector3[2]),
        o.scaleToRef(applySH3(2, e), TmpVectors.Vector3[2]),
        this.l10.addInPlace(TmpVectors.Vector3[2]),
        o.scaleToRef(applySH3(3, e), TmpVectors.Vector3[2]),
        this.l11.addInPlace(TmpVectors.Vector3[2]),
        o.scaleToRef(applySH3(4, e), TmpVectors.Vector3[2]),
        this.l2_2.addInPlace(TmpVectors.Vector3[2]),
        o.scaleToRef(applySH3(5, e), TmpVectors.Vector3[2]),
        this.l2_1.addInPlace(TmpVectors.Vector3[2]),
        o.scaleToRef(applySH3(6, e), TmpVectors.Vector3[2]),
        this.l20.addInPlace(TmpVectors.Vector3[2]),
        o.scaleToRef(applySH3(7, e), TmpVectors.Vector3[2]),
        this.l21.addInPlace(TmpVectors.Vector3[2]),
        o.scaleToRef(applySH3(8, e), TmpVectors.Vector3[2]),
        this.l22.addInPlace(TmpVectors.Vector3[2])
    }
    ,
    i.prototype.scaleInPlace = function(e) {
        this.l00.scaleInPlace(e),
        this.l1_1.scaleInPlace(e),
        this.l10.scaleInPlace(e),
        this.l11.scaleInPlace(e),
        this.l2_2.scaleInPlace(e),
        this.l2_1.scaleInPlace(e),
        this.l20.scaleInPlace(e),
        this.l21.scaleInPlace(e),
        this.l22.scaleInPlace(e)
    }
    ,
    i.prototype.convertIncidentRadianceToIrradiance = function() {
        this.l00.scaleInPlace(SHCosKernelConvolution[0]),
        this.l1_1.scaleInPlace(SHCosKernelConvolution[1]),
        this.l10.scaleInPlace(SHCosKernelConvolution[2]),
        this.l11.scaleInPlace(SHCosKernelConvolution[3]),
        this.l2_2.scaleInPlace(SHCosKernelConvolution[4]),
        this.l2_1.scaleInPlace(SHCosKernelConvolution[5]),
        this.l20.scaleInPlace(SHCosKernelConvolution[6]),
        this.l21.scaleInPlace(SHCosKernelConvolution[7]),
        this.l22.scaleInPlace(SHCosKernelConvolution[8])
    }
    ,
    i.prototype.convertIrradianceToLambertianRadiance = function() {
        this.scaleInPlace(1 / Math.PI)
    }
    ,
    i.prototype.preScaleForRendering = function() {
        this.preScaled = !0,
        this.l00.scaleInPlace(SH3ylmBasisConstants[0]),
        this.l1_1.scaleInPlace(SH3ylmBasisConstants[1]),
        this.l10.scaleInPlace(SH3ylmBasisConstants[2]),
        this.l11.scaleInPlace(SH3ylmBasisConstants[3]),
        this.l2_2.scaleInPlace(SH3ylmBasisConstants[4]),
        this.l2_1.scaleInPlace(SH3ylmBasisConstants[5]),
        this.l20.scaleInPlace(SH3ylmBasisConstants[6]),
        this.l21.scaleInPlace(SH3ylmBasisConstants[7]),
        this.l22.scaleInPlace(SH3ylmBasisConstants[8])
    }
    ,
    i.prototype.updateFromArray = function(e) {
        return Vector3.FromArrayToRef(e[0], 0, this.l00),
        Vector3.FromArrayToRef(e[1], 0, this.l1_1),
        Vector3.FromArrayToRef(e[2], 0, this.l10),
        Vector3.FromArrayToRef(e[3], 0, this.l11),
        Vector3.FromArrayToRef(e[4], 0, this.l2_2),
        Vector3.FromArrayToRef(e[5], 0, this.l2_1),
        Vector3.FromArrayToRef(e[6], 0, this.l20),
        Vector3.FromArrayToRef(e[7], 0, this.l21),
        Vector3.FromArrayToRef(e[8], 0, this.l22),
        this
    }
    ,
    i.prototype.updateFromFloatsArray = function(e) {
        return Vector3.FromFloatsToRef(e[0], e[1], e[2], this.l00),
        Vector3.FromFloatsToRef(e[3], e[4], e[5], this.l1_1),
        Vector3.FromFloatsToRef(e[6], e[7], e[8], this.l10),
        Vector3.FromFloatsToRef(e[9], e[10], e[11], this.l11),
        Vector3.FromFloatsToRef(e[12], e[13], e[14], this.l2_2),
        Vector3.FromFloatsToRef(e[15], e[16], e[17], this.l2_1),
        Vector3.FromFloatsToRef(e[18], e[19], e[20], this.l20),
        Vector3.FromFloatsToRef(e[21], e[22], e[23], this.l21),
        Vector3.FromFloatsToRef(e[24], e[25], e[26], this.l22),
        this
    }
    ,
    i.FromArray = function(e) {
        var t = new i;
        return t.updateFromArray(e)
    }
    ,
    i.FromPolynomial = function(e) {
        var t = new i;
        return t.l00 = e.xx.scale(.376127).add(e.yy.scale(.376127)).add(e.zz.scale(.376126)),
        t.l1_1 = e.y.scale(.977204),
        t.l10 = e.z.scale(.977204),
        t.l11 = e.x.scale(.977204),
        t.l2_2 = e.xy.scale(1.16538),
        t.l2_1 = e.yz.scale(1.16538),
        t.l20 = e.zz.scale(1.34567).subtract(e.xx.scale(.672834)).subtract(e.yy.scale(.672834)),
        t.l21 = e.zx.scale(1.16538),
        t.l22 = e.xx.scale(1.16538).subtract(e.yy.scale(1.16538)),
        t.l1_1.scaleInPlace(-1),
        t.l11.scaleInPlace(-1),
        t.l2_1.scaleInPlace(-1),
        t.l21.scaleInPlace(-1),
        t.scaleInPlace(Math.PI),
        t
    }
    ,
    i
}()
  , SphericalPolynomial = function() {
    function i() {
        this.x = Vector3.Zero(),
        this.y = Vector3.Zero(),
        this.z = Vector3.Zero(),
        this.xx = Vector3.Zero(),
        this.yy = Vector3.Zero(),
        this.zz = Vector3.Zero(),
        this.xy = Vector3.Zero(),
        this.yz = Vector3.Zero(),
        this.zx = Vector3.Zero()
    }
    return Object.defineProperty(i.prototype, "preScaledHarmonics", {
        get: function() {
            return this._harmonics || (this._harmonics = SphericalHarmonics.FromPolynomial(this)),
            this._harmonics.preScaled || this._harmonics.preScaleForRendering(),
            this._harmonics
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.addAmbient = function(e) {
        TmpVectors.Vector3[0].copyFromFloats(e.r, e.g, e.b);
        var t = TmpVectors.Vector3[0];
        this.xx.addInPlace(t),
        this.yy.addInPlace(t),
        this.zz.addInPlace(t)
    }
    ,
    i.prototype.scaleInPlace = function(e) {
        this.x.scaleInPlace(e),
        this.y.scaleInPlace(e),
        this.z.scaleInPlace(e),
        this.xx.scaleInPlace(e),
        this.yy.scaleInPlace(e),
        this.zz.scaleInPlace(e),
        this.yz.scaleInPlace(e),
        this.zx.scaleInPlace(e),
        this.xy.scaleInPlace(e)
    }
    ,
    i.prototype.updateFromHarmonics = function(e) {
        return this._harmonics = e,
        this.x.copyFrom(e.l11),
        this.x.scaleInPlace(1.02333).scaleInPlace(-1),
        this.y.copyFrom(e.l1_1),
        this.y.scaleInPlace(1.02333).scaleInPlace(-1),
        this.z.copyFrom(e.l10),
        this.z.scaleInPlace(1.02333),
        this.xx.copyFrom(e.l00),
        TmpVectors.Vector3[0].copyFrom(e.l20).scaleInPlace(.247708),
        TmpVectors.Vector3[1].copyFrom(e.l22).scaleInPlace(.429043),
        this.xx.scaleInPlace(.886277).subtractInPlace(TmpVectors.Vector3[0]).addInPlace(TmpVectors.Vector3[1]),
        this.yy.copyFrom(e.l00),
        this.yy.scaleInPlace(.886277).subtractInPlace(TmpVectors.Vector3[0]).subtractInPlace(TmpVectors.Vector3[1]),
        this.zz.copyFrom(e.l00),
        TmpVectors.Vector3[0].copyFrom(e.l20).scaleInPlace(.495417),
        this.zz.scaleInPlace(.886277).addInPlace(TmpVectors.Vector3[0]),
        this.yz.copyFrom(e.l2_1),
        this.yz.scaleInPlace(.858086).scaleInPlace(-1),
        this.zx.copyFrom(e.l21),
        this.zx.scaleInPlace(.858086).scaleInPlace(-1),
        this.xy.copyFrom(e.l2_2),
        this.xy.scaleInPlace(.858086),
        this.scaleInPlace(1 / Math.PI),
        this
    }
    ,
    i.FromHarmonics = function(e) {
        var t = new i;
        return t.updateFromHarmonics(e)
    }
    ,
    i.FromArray = function(e) {
        var t = new i;
        return Vector3.FromArrayToRef(e[0], 0, t.x),
        Vector3.FromArrayToRef(e[1], 0, t.y),
        Vector3.FromArrayToRef(e[2], 0, t.z),
        Vector3.FromArrayToRef(e[3], 0, t.xx),
        Vector3.FromArrayToRef(e[4], 0, t.yy),
        Vector3.FromArrayToRef(e[5], 0, t.zz),
        Vector3.FromArrayToRef(e[6], 0, t.yz),
        Vector3.FromArrayToRef(e[7], 0, t.zx),
        Vector3.FromArrayToRef(e[8], 0, t.xy),
        t
    }
    ,
    i
}()
  , FileFaceOrientation = function() {
    function i(e, t, r, n) {
        this.name = e,
        this.worldAxisForNormal = t,
        this.worldAxisForFileX = r,
        this.worldAxisForFileY = n
    }
    return i
}()
  , CubeMapToSphericalPolynomialTools = function() {
    function i() {}
    return i.ConvertCubeMapTextureToSphericalPolynomial = function(e) {
        var t = this, r;
        if (!e.isCube)
            return null;
        (r = e.getScene()) === null || r === void 0 || r.getEngine().flushFramebuffer();
        var n = e.getSize().width, o = e.readPixels(0, void 0, void 0, !1), a = e.readPixels(1, void 0, void 0, !1), s, l;
        e.isRenderTarget ? (s = e.readPixels(3, void 0, void 0, !1),
        l = e.readPixels(2, void 0, void 0, !1)) : (s = e.readPixels(2, void 0, void 0, !1),
        l = e.readPixels(3, void 0, void 0, !1));
        var u = e.readPixels(4, void 0, void 0, !1)
          , c = e.readPixels(5, void 0, void 0, !1)
          , h = e.gammaSpace
          , f = 5
          , d = 0;
        return (e.textureType == 1 || e.textureType == 2) && (d = 1),
        new Promise(function(_, g) {
            Promise.all([a, o, s, l, u, c]).then(function(m) {
                var v = m[0]
                  , y = m[1]
                  , b = m[2]
                  , T = m[3]
                  , C = m[4]
                  , A = m[5]
                  , S = {
                    size: n,
                    right: y,
                    left: v,
                    up: b,
                    down: T,
                    front: C,
                    back: A,
                    format: f,
                    type: d,
                    gammaSpace: h
                };
                _(t.ConvertCubeMapToSphericalPolynomial(S))
            })
        }
        )
    }
    ,
    i.ConvertCubeMapToSphericalPolynomial = function(e) {
        for (var t = new SphericalHarmonics, r = 0, n = 2 / e.size, o = n, a = n * .5 - 1, s = 0; s < 6; s++)
            for (var l = this.FileFaces[s], u = e[l.name], c = a, h = e.format === 5 ? 4 : 3, f = 0; f < e.size; f++) {
                for (var d = a, _ = 0; _ < e.size; _++) {
                    var g = l.worldAxisForFileX.scale(d).add(l.worldAxisForFileY.scale(c)).add(l.worldAxisForNormal);
                    g.normalize();
                    var m = Math.pow(1 + d * d + c * c, -3 / 2)
                      , v = u[f * e.size * h + _ * h + 0]
                      , y = u[f * e.size * h + _ * h + 1]
                      , b = u[f * e.size * h + _ * h + 2];
                    isNaN(v) && (v = 0),
                    isNaN(y) && (y = 0),
                    isNaN(b) && (b = 0),
                    e.type === 0 && (v /= 255,
                    y /= 255,
                    b /= 255),
                    e.gammaSpace && (v = Math.pow(Scalar.Clamp(v), ToLinearSpace),
                    y = Math.pow(Scalar.Clamp(y), ToLinearSpace),
                    b = Math.pow(Scalar.Clamp(b), ToLinearSpace));
                    var T = 4096;
                    v = Scalar.Clamp(v, 0, T),
                    y = Scalar.Clamp(y, 0, T),
                    b = Scalar.Clamp(b, 0, T);
                    var C = new Color3(v,y,b);
                    t.addLight(g, C, m),
                    r += m,
                    d += n
                }
                c += o
            }
        var A = 4 * Math.PI
          , S = 6
          , P = A * S / 6
          , R = P / r;
        return t.scaleInPlace(R),
        t.convertIncidentRadianceToIrradiance(),
        t.convertIrradianceToLambertianRadiance(),
        SphericalPolynomial.FromHarmonics(t)
    }
    ,
    i.FileFaces = [new FileFaceOrientation("right",new Vector3(1,0,0),new Vector3(0,0,-1),new Vector3(0,-1,0)), new FileFaceOrientation("left",new Vector3(-1,0,0),new Vector3(0,0,1),new Vector3(0,-1,0)), new FileFaceOrientation("up",new Vector3(0,1,0),new Vector3(1,0,0),new Vector3(0,0,1)), new FileFaceOrientation("down",new Vector3(0,-1,0),new Vector3(1,0,0),new Vector3(0,0,-1)), new FileFaceOrientation("front",new Vector3(0,0,1),new Vector3(1,0,0),new Vector3(0,-1,0)), new FileFaceOrientation("back",new Vector3(0,0,-1),new Vector3(-1,0,0),new Vector3(0,-1,0))],
    i
}();
BaseTexture.prototype.forceSphericalPolynomialsRecompute = function() {
    this._texture && (this._texture._sphericalPolynomial = null,
    this._texture._sphericalPolynomialPromise = null,
    this._texture._sphericalPolynomialComputed = !1)
}
;
Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
    get: function() {
        var i = this;
        if (this._texture) {
            if (this._texture._sphericalPolynomial || this._texture._sphericalPolynomialComputed)
                return this._texture._sphericalPolynomial;
            if (this._texture.isReady)
                return this._texture._sphericalPolynomialPromise || (this._texture._sphericalPolynomialPromise = CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this),
                this._texture._sphericalPolynomialPromise === null ? this._texture._sphericalPolynomialComputed = !0 : this._texture._sphericalPolynomialPromise.then(function(e) {
                    i._texture._sphericalPolynomial = e,
                    i._texture._sphericalPolynomialComputed = !0
                })),
                null
        }
        return null
    },
    set: function(i) {
        this._texture && (this._texture._sphericalPolynomial = i)
    },
    enumerable: !0,
    configurable: !0
});
var name$1w = "pbrFragmentDeclaration"
  , shader$1w = `uniform vec4 vEyePosition;
uniform vec3 vReflectionColor;
uniform vec4 vAlbedoColor;

uniform vec4 vLightingIntensity;
uniform vec4 vReflectivityColor;
uniform vec4 vMetallicReflectanceFactors;
uniform vec3 vEmissiveColor;
uniform float visibility;
uniform vec3 vAmbientColor;

#ifdef ALBEDO
uniform vec2 vAlbedoInfos;
#endif
#ifdef AMBIENT
uniform vec4 vAmbientInfos;
#endif
#ifdef BUMP
uniform vec3 vBumpInfos;
uniform vec2 vTangentSpaceParams;
#endif
#ifdef OPACITY
uniform vec2 vOpacityInfos;
#endif
#ifdef EMISSIVE
uniform vec2 vEmissiveInfos;
#endif
#ifdef LIGHTMAP
uniform vec2 vLightmapInfos;
#endif
#ifdef REFLECTIVITY
uniform vec3 vReflectivityInfos;
#endif
#ifdef MICROSURFACEMAP
uniform vec2 vMicroSurfaceSamplerInfos;
#endif

#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(SS_REFRACTION) || defined(PREPASS)
uniform mat4 view;
#endif

#ifdef REFLECTION
uniform vec2 vReflectionInfos;
#ifdef REALTIME_FILTERING
uniform vec2 vReflectionFilteringInfo;
#endif
uniform mat4 reflectionMatrix;
uniform vec3 vReflectionMicrosurfaceInfos;
#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)
uniform vec3 vReflectionPosition;
uniform vec3 vReflectionSize;
#endif
#endif

#if defined(SS_REFRACTION) && defined(SS_USE_LOCAL_REFRACTIONMAP_CUBIC)
uniform vec3 vRefractionPosition;
uniform vec3 vRefractionSize;
#endif

#ifdef CLEARCOAT
uniform vec2 vClearCoatParams;
uniform vec4 vClearCoatRefractionParams;
#if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS)
uniform vec4 vClearCoatInfos;
#endif
#ifdef CLEARCOAT_TEXTURE
uniform mat4 clearCoatMatrix;
#endif
#ifdef CLEARCOAT_TEXTURE_ROUGHNESS
uniform mat4 clearCoatRoughnessMatrix;
#endif
#ifdef CLEARCOAT_BUMP
uniform vec2 vClearCoatBumpInfos;
uniform vec2 vClearCoatTangentSpaceParams;
uniform mat4 clearCoatBumpMatrix;
#endif
#ifdef CLEARCOAT_TINT
uniform vec4 vClearCoatTintParams;
uniform float clearCoatColorAtDistance;
#ifdef CLEARCOAT_TINT_TEXTURE
uniform vec2 vClearCoatTintInfos;
uniform mat4 clearCoatTintMatrix;
#endif
#endif
#endif

#ifdef ANISOTROPIC
uniform vec3 vAnisotropy;
#ifdef ANISOTROPIC_TEXTURE
uniform vec2 vAnisotropyInfos;
uniform mat4 anisotropyMatrix;
#endif
#endif

#ifdef SHEEN
uniform vec4 vSheenColor;
#ifdef SHEEN_ROUGHNESS
uniform float vSheenRoughness;
#endif
#if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS)
uniform vec4 vSheenInfos;
#endif
#ifdef SHEEN_TEXTURE
uniform mat4 sheenMatrix;
#endif
#ifdef SHEEN_TEXTURE_ROUGHNESS
uniform mat4 sheenRoughnessMatrix;
#endif
#endif

#ifdef SUBSURFACE
#ifdef SS_REFRACTION
uniform vec4 vRefractionMicrosurfaceInfos;
uniform vec4 vRefractionInfos;
uniform mat4 refractionMatrix;
#ifdef REALTIME_FILTERING
uniform vec2 vRefractionFilteringInfo;
#endif
#endif
#ifdef SS_THICKNESSANDMASK_TEXTURE
uniform vec2 vThicknessInfos;
uniform mat4 thicknessMatrix;
#endif
#ifdef SS_REFRACTIONINTENSITY_TEXTURE
uniform vec2 vRefractionIntensityInfos;
uniform mat4 refractionIntensityMatrix;
#endif
#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE
uniform vec2 vTranslucencyIntensityInfos;
uniform mat4 translucencyIntensityMatrix;
#endif
uniform vec2 vThicknessParam;
uniform vec3 vDiffusionDistance;
uniform vec4 vTintColor;
uniform vec3 vSubSurfaceIntensity;
#endif
#ifdef PREPASS
#ifdef SS_SCATTERING
uniform float scatteringDiffusionProfile;
#endif
#endif
#if DEBUGMODE>0
uniform vec2 vDebugMode;
#endif
#ifdef DETAIL
uniform vec4 vDetailInfos;
#endif
#ifdef USESPHERICALFROMREFLECTIONMAP
#ifdef SPHERICAL_HARMONICS
uniform vec3 vSphericalL00;
uniform vec3 vSphericalL1_1;
uniform vec3 vSphericalL10;
uniform vec3 vSphericalL11;
uniform vec3 vSphericalL2_2;
uniform vec3 vSphericalL2_1;
uniform vec3 vSphericalL20;
uniform vec3 vSphericalL21;
uniform vec3 vSphericalL22;
#else
uniform vec3 vSphericalX;
uniform vec3 vSphericalY;
uniform vec3 vSphericalZ;
uniform vec3 vSphericalXX_ZZ;
uniform vec3 vSphericalYY_ZZ;
uniform vec3 vSphericalZZ;
uniform vec3 vSphericalXY;
uniform vec3 vSphericalYZ;
uniform vec3 vSphericalZX;
#endif
#endif
`;
ShaderStore.IncludesShadersStore[name$1w] = shader$1w;
var name$1v = "pbrUboDeclaration"
  , shader$1v = `layout(std140,column_major) uniform;





















uniform Material {
vec2 vAlbedoInfos;
vec4 vAmbientInfos;
vec2 vOpacityInfos;
vec2 vEmissiveInfos;
vec2 vLightmapInfos;
vec3 vReflectivityInfos;
vec2 vMicroSurfaceSamplerInfos;
vec2 vReflectionInfos;
vec2 vReflectionFilteringInfo;
vec3 vReflectionPosition;
vec3 vReflectionSize;
vec3 vBumpInfos;
mat4 albedoMatrix;
mat4 ambientMatrix;
mat4 opacityMatrix;
mat4 emissiveMatrix;
mat4 lightmapMatrix;
mat4 reflectivityMatrix;
mat4 microSurfaceSamplerMatrix;
mat4 bumpMatrix;
vec2 vTangentSpaceParams;
mat4 reflectionMatrix;
vec3 vReflectionColor;
vec4 vAlbedoColor;
vec4 vLightingIntensity;
vec3 vReflectionMicrosurfaceInfos;
float pointSize;
vec4 vReflectivityColor;
vec3 vEmissiveColor;
vec3 vAmbientColor;
vec2 vDebugMode;
vec4 vMetallicReflectanceFactors;
vec2 vMetallicReflectanceInfos;
mat4 metallicReflectanceMatrix;
vec2 vReflectanceInfos;
mat4 reflectanceMatrix;
vec2 vClearCoatParams;
vec4 vClearCoatRefractionParams;
vec4 vClearCoatInfos;
mat4 clearCoatMatrix;
mat4 clearCoatRoughnessMatrix;
vec2 vClearCoatBumpInfos;
vec2 vClearCoatTangentSpaceParams;
mat4 clearCoatBumpMatrix;
vec4 vClearCoatTintParams;
float clearCoatColorAtDistance;
vec2 vClearCoatTintInfos;
mat4 clearCoatTintMatrix;
vec3 vAnisotropy;
vec2 vAnisotropyInfos;
mat4 anisotropyMatrix;
vec4 vSheenColor;
float vSheenRoughness;
vec4 vSheenInfos;
mat4 sheenMatrix;
mat4 sheenRoughnessMatrix;
vec4 vRefractionMicrosurfaceInfos;
vec2 vRefractionFilteringInfo;
vec2 vTranslucencyIntensityInfos;
vec4 vRefractionInfos;
mat4 refractionMatrix;
vec2 vThicknessInfos;
vec2 vRefractionIntensityInfos;
mat4 thicknessMatrix;
mat4 refractionIntensityMatrix;
mat4 translucencyIntensityMatrix;
vec2 vThicknessParam;
vec3 vDiffusionDistance;
vec4 vTintColor;
vec3 vSubSurfaceIntensity;
vec3 vRefractionPosition;
vec3 vRefractionSize;
float scatteringDiffusionProfile;
vec4 vDetailInfos;
mat4 detailMatrix;
vec3 vSphericalL00;
vec3 vSphericalL1_1;
vec3 vSphericalL10;
vec3 vSphericalL11;
vec3 vSphericalL2_2;
vec3 vSphericalL2_1;
vec3 vSphericalL20;
vec3 vSphericalL21;
vec3 vSphericalL22;
vec3 vSphericalX;
vec3 vSphericalY;
vec3 vSphericalZ;
vec3 vSphericalXX_ZZ;
vec3 vSphericalYY_ZZ;
vec3 vSphericalZZ;
vec3 vSphericalXY;
vec3 vSphericalYZ;
vec3 vSphericalZX;
};
#include<sceneUboDeclaration>
#include<meshUboDeclaration>
`;
ShaderStore.IncludesShadersStore[name$1v] = shader$1v;
var name$1u = "pbrFragmentExtraDeclaration"
  , shader$1u = `
varying vec3 vPositionW;
#if DEBUGMODE>0
varying vec4 vClipSpacePosition;
#endif
#include<mainUVVaryingDeclaration>[1..7]
#ifdef NORMAL
varying vec3 vNormalW;
#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)
varying vec3 vEnvironmentIrradiance;
#endif
#endif
#ifdef VERTEXCOLOR
varying vec4 vColor;
#endif`;
ShaderStore.IncludesShadersStore[name$1u] = shader$1u;
var name$1t = "samplerFragmentAlternateDeclaration"
  , shader$1t = `#ifdef _DEFINENAME_
#if _DEFINENAME_DIRECTUV == 1
#define v_VARYINGNAME_UV vMainUV1
#elif _DEFINENAME_DIRECTUV == 2
#define v_VARYINGNAME_UV vMainUV2
#elif _DEFINENAME_DIRECTUV == 3
#define v_VARYINGNAME_UV vMainUV3
#elif _DEFINENAME_DIRECTUV == 4
#define v_VARYINGNAME_UV vMainUV4
#elif _DEFINENAME_DIRECTUV == 5
#define v_VARYINGNAME_UV vMainUV5
#elif _DEFINENAME_DIRECTUV == 6
#define v_VARYINGNAME_UV vMainUV6
#else
varying vec2 v_VARYINGNAME_UV;
#endif
#endif
`;
ShaderStore.IncludesShadersStore[name$1t] = shader$1t;
var name$1s = "pbrFragmentSamplersDeclaration"
  , shader$1s = `#include<samplerFragmentDeclaration>(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_SAMPLERNAME_,albedo)
#include<samplerFragmentDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient)
#include<samplerFragmentDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity)
#include<samplerFragmentDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive)
#include<samplerFragmentDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap)
#include<samplerFragmentDeclaration>(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_SAMPLERNAME_,reflectivity)
#include<samplerFragmentDeclaration>(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_SAMPLERNAME_,microSurface)
#include<samplerFragmentDeclaration>(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_SAMPLERNAME_,metallicReflectance)
#include<samplerFragmentDeclaration>(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_SAMPLERNAME_,reflectance)
#ifdef CLEARCOAT
#include<samplerFragmentDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_SAMPLERNAME_,clearCoat)
#include<samplerFragmentAlternateDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness)
#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL)
uniform sampler2D clearCoatRoughnessSampler;
#endif
#include<samplerFragmentDeclaration>(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_SAMPLERNAME_,clearCoatBump)
#include<samplerFragmentDeclaration>(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_SAMPLERNAME_,clearCoatTint)
#endif
#ifdef SHEEN
#include<samplerFragmentDeclaration>(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_SAMPLERNAME_,sheen)
#include<samplerFragmentAlternateDeclaration>(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness)
#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL)
uniform sampler2D sheenRoughnessSampler;
#endif
#endif
#ifdef ANISOTROPIC
#include<samplerFragmentDeclaration>(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_SAMPLERNAME_,anisotropy)
#endif

#ifdef REFLECTION
#ifdef REFLECTIONMAP_3D
#define sampleReflection(s,c) textureCube(s,c)
uniform samplerCube reflectionSampler;
#ifdef LODBASEDMICROSFURACE
#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)
#else
uniform samplerCube reflectionSamplerLow;
uniform samplerCube reflectionSamplerHigh;
#endif
#ifdef USEIRRADIANCEMAP
uniform samplerCube irradianceSampler;
#endif
#else
#define sampleReflection(s,c) texture2D(s,c)
uniform sampler2D reflectionSampler;
#ifdef LODBASEDMICROSFURACE
#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)
#else
uniform sampler2D reflectionSamplerLow;
uniform sampler2D reflectionSamplerHigh;
#endif
#ifdef USEIRRADIANCEMAP
uniform sampler2D irradianceSampler;
#endif
#endif
#ifdef REFLECTIONMAP_SKYBOX
varying vec3 vPositionUVW;
#else
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
varying vec3 vDirectionW;
#endif
#endif
#endif
#ifdef ENVIRONMENTBRDF
uniform sampler2D environmentBrdfSampler;
#endif

#ifdef SUBSURFACE
#ifdef SS_REFRACTION
#ifdef SS_REFRACTIONMAP_3D
#define sampleRefraction(s,c) textureCube(s,c)
uniform samplerCube refractionSampler;
#ifdef LODBASEDMICROSFURACE
#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)
#else
uniform samplerCube refractionSamplerLow;
uniform samplerCube refractionSamplerHigh;
#endif
#else
#define sampleRefraction(s,c) texture2D(s,c)
uniform sampler2D refractionSampler;
#ifdef LODBASEDMICROSFURACE
#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)
#else
uniform sampler2D refractionSamplerLow;
uniform sampler2D refractionSamplerHigh;
#endif
#endif
#endif
#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_SAMPLERNAME_,thickness)
#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_SAMPLERNAME_,refractionIntensity)
#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_SAMPLERNAME_,translucencyIntensity)
#endif`;
ShaderStore.IncludesShadersStore[name$1s] = shader$1s;
var name$1r = "subSurfaceScatteringFunctions"
  , shader$1r = `bool testLightingForSSS(float diffusionProfile)
{
return diffusionProfile<1.;
}`;
ShaderStore.IncludesShadersStore[name$1r] = shader$1r;
var name$1q = "importanceSampling"
  , shader$1q = `




























vec3 hemisphereCosSample(vec2 u) {

float phi=2.*PI*u.x;
float cosTheta2=1.-u.y;
float cosTheta=sqrt(cosTheta2);
float sinTheta=sqrt(1.-cosTheta2);
return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);
}





































vec3 hemisphereImportanceSampleDggx(vec2 u,float a) {

float phi=2.*PI*u.x;

float cosTheta2=(1.-u.y)/(1.+(a+1.)*((a-1.)*u.y));
float cosTheta=sqrt(cosTheta2);
float sinTheta=sqrt(1.-cosTheta2);
return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);
}

























































vec3 hemisphereImportanceSampleDCharlie(vec2 u,float a) {

float phi=2.*PI*u.x;
float sinTheta=pow(u.y,a/(2.*a+1.));
float cosTheta=sqrt(1.-sinTheta*sinTheta);
return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);
}`;
ShaderStore.IncludesShadersStore[name$1q] = shader$1q;
var name$1p = "pbrHelperFunctions"
  , shader$1p = `
#define RECIPROCAL_PI2 0.15915494
#define RECIPROCAL_PI 0.31830988618

#define MINIMUMVARIANCE 0.0005
float convertRoughnessToAverageSlope(float roughness)
{

return square(roughness)+MINIMUMVARIANCE;
}
float fresnelGrazingReflectance(float reflectance0) {


float reflectance90=saturate(reflectance0*25.0);
return reflectance90;
}
vec2 getAARoughnessFactors(vec3 normalVector) {
#ifdef SPECULARAA
vec3 nDfdx=dFdx(normalVector.xyz);
vec3 nDfdy=dFdy(normalVector.xyz);
float slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));

float geometricRoughnessFactor=pow(saturate(slopeSquare),0.333);

float geometricAlphaGFactor=sqrt(slopeSquare);

geometricAlphaGFactor*=0.75;
return vec2(geometricRoughnessFactor,geometricAlphaGFactor);
#else
return vec2(0.);
#endif
}
#ifdef ANISOTROPIC


vec2 getAnisotropicRoughness(float alphaG,float anisotropy) {
float alphaT=max(alphaG*(1.0+anisotropy),MINIMUMVARIANCE);
float alphaB=max(alphaG*(1.0-anisotropy),MINIMUMVARIANCE);
return vec2(alphaT,alphaB);
}


vec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy) {
vec3 anisotropicFrameDirection=anisotropy>=0.0 ? B : T;
vec3 anisotropicFrameTangent=cross(normalize(anisotropicFrameDirection),V);
vec3 anisotropicFrameNormal=cross(anisotropicFrameTangent,anisotropicFrameDirection);
vec3 anisotropicNormal=normalize(mix(N,anisotropicFrameNormal,abs(anisotropy)));
return anisotropicNormal;

}
#endif
#if defined(CLEARCOAT) || defined(SS_REFRACTION)



vec3 cocaLambert(vec3 alpha,float distance) {
return exp(-alpha*distance);
}

vec3 cocaLambert(float NdotVRefract,float NdotLRefract,vec3 alpha,float thickness) {
return cocaLambert(alpha,(thickness*((NdotLRefract+NdotVRefract)/(NdotLRefract*NdotVRefract))));
}

vec3 computeColorAtDistanceInMedia(vec3 color,float distance) {
return -log(color)/distance;
}
vec3 computeClearCoatAbsorption(float NdotVRefract,float NdotLRefract,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {
vec3 clearCoatAbsorption=mix(vec3(1.0),
cocaLambert(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness),
clearCoatIntensity);
return clearCoatAbsorption;
}
#endif




#ifdef MICROSURFACEAUTOMATIC
float computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)
{
const float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;
float reflectivityLuminance=getLuminance(reflectivityColor);
float reflectivityLuma=sqrt(reflectivityLuminance);
microSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;
return microSurface;
}
#endif`;
ShaderStore.IncludesShadersStore[name$1p] = shader$1p;
var name$1o = "harmonicsFunctions"
  , shader$1o = `#ifdef USESPHERICALFROMREFLECTIONMAP
#ifdef SPHERICAL_HARMONICS







vec3 computeEnvironmentIrradiance(vec3 normal) {
return vSphericalL00
+vSphericalL1_1*(normal.y)
+vSphericalL10*(normal.z)
+vSphericalL11*(normal.x)
+vSphericalL2_2*(normal.y*normal.x)
+vSphericalL2_1*(normal.y*normal.z)
+vSphericalL20*((3.0*normal.z*normal.z)-1.0)
+vSphericalL21*(normal.z*normal.x)
+vSphericalL22*(normal.x*normal.x-(normal.y*normal.y));
}
#else

vec3 computeEnvironmentIrradiance(vec3 normal) {









float Nx=normal.x;
float Ny=normal.y;
float Nz=normal.z;
vec3 C1=vSphericalZZ.rgb;
vec3 Cx=vSphericalX.rgb;
vec3 Cy=vSphericalY.rgb;
vec3 Cz=vSphericalZ.rgb;
vec3 Cxx_zz=vSphericalXX_ZZ.rgb;
vec3 Cyy_zz=vSphericalYY_ZZ.rgb;
vec3 Cxy=vSphericalXY.rgb;
vec3 Cyz=vSphericalYZ.rgb;
vec3 Czx=vSphericalZX.rgb;
vec3 a1=Cyy_zz*Ny+Cy;
vec3 a2=Cyz*Nz+a1;
vec3 b1=Czx*Nz+Cx;
vec3 b2=Cxy*Ny+b1;
vec3 b3=Cxx_zz*Nx+b2;
vec3 t1=Cz*Nz+C1;
vec3 t2=a2*Ny+t1;
vec3 t3=b3*Nx+t2;
return t3;
}
#endif
#endif`;
ShaderStore.IncludesShadersStore[name$1o] = shader$1o;
var name$1n = "pbrDirectLightingSetupFunctions"
  , shader$1n = `
struct preLightingInfo
{

vec3 lightOffset;
float lightDistanceSquared;
float lightDistance;

float attenuation;

vec3 L;
vec3 H;
float NdotV;
float NdotLUnclamped;
float NdotL;
float VdotH;
float roughness;
};
preLightingInfo computePointAndSpotPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {
preLightingInfo result;

result.lightOffset=lightData.xyz-vPositionW;
result.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);

result.lightDistance=sqrt(result.lightDistanceSquared);

result.L=normalize(result.lightOffset);
result.H=normalize(V+result.L);
result.VdotH=saturate(dot(V,result.H));
result.NdotLUnclamped=dot(N,result.L);
result.NdotL=saturateEps(result.NdotLUnclamped);
return result;
}
preLightingInfo computeDirectionalPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {
preLightingInfo result;

result.lightDistance=length(-lightData.xyz);

result.L=normalize(-lightData.xyz);
result.H=normalize(V+result.L);
result.VdotH=saturate(dot(V,result.H));
result.NdotLUnclamped=dot(N,result.L);
result.NdotL=saturateEps(result.NdotLUnclamped);
return result;
}
preLightingInfo computeHemisphericPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {
preLightingInfo result;


result.NdotL=dot(N,lightData.xyz)*0.5+0.5;
result.NdotL=saturateEps(result.NdotL);
result.NdotLUnclamped=result.NdotL;
#ifdef SPECULARTERM
result.L=normalize(lightData.xyz);
result.H=normalize(V+result.L);
result.VdotH=saturate(dot(V,result.H));
#endif
return result;
}`;
ShaderStore.IncludesShadersStore[name$1n] = shader$1n;
var name$1m = "pbrDirectLightingFalloffFunctions"
  , shader$1m = `float computeDistanceLightFalloff_Standard(vec3 lightOffset,float range)
{
return max(0.,1.0-length(lightOffset)/range);
}
float computeDistanceLightFalloff_Physical(float lightDistanceSquared)
{
return 1.0/maxEps(lightDistanceSquared);
}
float computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange)
{
float lightDistanceFalloff=1.0/maxEps(lightDistanceSquared);
float factor=lightDistanceSquared*inverseSquaredRange;
float attenuation=saturate(1.0-factor*factor);
attenuation*=attenuation;

lightDistanceFalloff*=attenuation;
return lightDistanceFalloff;
}
float computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange)
{
#ifdef USEPHYSICALLIGHTFALLOFF
return computeDistanceLightFalloff_Physical(lightDistanceSquared);
#elif defined(USEGLTFLIGHTFALLOFF)
return computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange);
#else
return computeDistanceLightFalloff_Standard(lightOffset,range);
#endif
}
float computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)
{
float falloff=0.0;
float cosAngle=maxEps(dot(-lightDirection,directionToLightCenterW));
if (cosAngle>=cosHalfAngle)
{
falloff=max(0.,pow(cosAngle,exponent));
}
return falloff;
}
float computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle)
{
const float kMinusLog2ConeAngleIntensityRatio=6.64385618977;





float concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);


vec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);
float falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));
return falloff;
}
float computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset)
{



float cd=dot(-lightDirection,directionToLightCenterW);
float falloff=saturate(cd*lightAngleScale+lightAngleOffset);

falloff*=falloff;
return falloff;
}
float computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset)
{
#ifdef USEPHYSICALLIGHTFALLOFF
return computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle);
#elif defined(USEGLTFLIGHTFALLOFF)
return computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset);
#else
return computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent);
#endif
}`;
ShaderStore.IncludesShadersStore[name$1m] = shader$1m;
var name$1l = "pbrBRDFFunctions"
  , shader$1l = `
#define FRESNEL_MAXIMUM_ON_ROUGH 0.25




#ifdef MS_BRDF_ENERGY_CONSERVATION


vec3 getEnergyConservationFactor(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {
return 1.0+specularEnvironmentR0*(1.0/environmentBrdf.y-1.0);
}
#endif
#ifdef ENVIRONMENTBRDF
vec3 getBRDFLookup(float NdotV,float perceptualRoughness) {

vec2 UV=vec2(NdotV,perceptualRoughness);

vec4 brdfLookup=texture2D(environmentBrdfSampler,UV);
#ifdef ENVIRONMENTBRDF_RGBD
brdfLookup.rgb=fromRGBD(brdfLookup.rgba);
#endif
return brdfLookup.rgb;
}
vec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 specularEnvironmentR90,const vec3 environmentBrdf) {
#ifdef BRDF_V_HEIGHT_CORRELATED
vec3 reflectance=(specularEnvironmentR90-specularEnvironmentR0)*environmentBrdf.x+specularEnvironmentR0*environmentBrdf.y;

#else
vec3 reflectance=specularEnvironmentR0*environmentBrdf.x+specularEnvironmentR90*environmentBrdf.y;
#endif
return reflectance;
}
vec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {
#ifdef BRDF_V_HEIGHT_CORRELATED
vec3 reflectance=mix(environmentBrdf.xxx,environmentBrdf.yyy,specularEnvironmentR0);
#else
vec3 reflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;
#endif
return reflectance;
}
#endif

#if !defined(ENVIRONMENTBRDF) || defined(REFLECTIONMAP_SKYBOX) || defined(ALPHAFRESNEL)
vec3 getReflectanceFromAnalyticalBRDFLookup_Jones(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)
{

float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);
return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));
}
#endif
#if defined(SHEEN) && defined(ENVIRONMENTBRDF)

vec3 getSheenReflectanceFromBRDFLookup(const vec3 reflectance0,const vec3 environmentBrdf) {
vec3 sheenEnvironmentReflectance=reflectance0*environmentBrdf.b;
return sheenEnvironmentReflectance;
}
#endif
























vec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)
{
return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);
}
float fresnelSchlickGGX(float VdotH,float reflectance0,float reflectance90)
{
return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);
}
#ifdef CLEARCOAT





vec3 getR0RemappedForClearCoat(vec3 f0) {
#ifdef CLEARCOAT_DEFAULTIOR
#ifdef MOBILE
return saturate(f0*(f0*0.526868+0.529324)-0.0482256);
#else
return saturate(f0*(f0*(0.941892-0.263008*f0)+0.346479)-0.0285998);
#endif
#else
vec3 s=sqrt(f0);
vec3 t=(vClearCoatRefractionParams.z+vClearCoatRefractionParams.w*s)/(vClearCoatRefractionParams.w+vClearCoatRefractionParams.z*s);
return t*t;
#endif
}
#endif






float normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)
{



float a2=square(alphaG);
float d=NdotH*NdotH*(a2-1.0)+1.0;
return a2/(PI*d*d);
}
#ifdef SHEEN


float normalDistributionFunction_CharlieSheen(float NdotH,float alphaG)
{
float invR=1./alphaG;
float cos2h=NdotH*NdotH;
float sin2h=1.-cos2h;
return (2.+invR)*pow(sin2h,invR*.5)/(2.*PI);
}
#endif
#ifdef ANISOTROPIC


float normalDistributionFunction_BurleyGGX_Anisotropic(float NdotH,float TdotH,float BdotH,const vec2 alphaTB) {
float a2=alphaTB.x*alphaTB.y;
vec3 v=vec3(alphaTB.y*TdotH,alphaTB.x*BdotH,a2*NdotH);
float v2=dot(v,v);
float w2=a2/v2;
return a2*w2*w2*RECIPROCAL_PI;
}
#endif




#ifdef BRDF_V_HEIGHT_CORRELATED



float smithVisibility_GGXCorrelated(float NdotL,float NdotV,float alphaG) {
#ifdef MOBILE

float GGXV=NdotL*(NdotV*(1.0-alphaG)+alphaG);
float GGXL=NdotV*(NdotL*(1.0-alphaG)+alphaG);
return 0.5/(GGXV+GGXL);
#else
float a2=alphaG*alphaG;
float GGXV=NdotL*sqrt(NdotV*(NdotV-a2*NdotV)+a2);
float GGXL=NdotV*sqrt(NdotL*(NdotL-a2*NdotL)+a2);
return 0.5/(GGXV+GGXL);
#endif
}
#else















float smithVisibilityG1_TrowbridgeReitzGGXFast(float dot,float alphaG)
{
#ifdef MOBILE

return 1.0/(dot+alphaG+(1.0-alphaG)*dot ));
#else
float alphaSquared=alphaG*alphaG;
return 1.0/(dot+sqrt(alphaSquared+(1.0-alphaSquared)*dot*dot));
#endif
}
float smithVisibility_TrowbridgeReitzGGXFast(float NdotL,float NdotV,float alphaG)
{
float visibility=smithVisibilityG1_TrowbridgeReitzGGXFast(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGXFast(NdotV,alphaG);

return visibility;
}
#endif
#ifdef ANISOTROPIC


float smithVisibility_GGXCorrelated_Anisotropic(float NdotL,float NdotV,float TdotV,float BdotV,float TdotL,float BdotL,const vec2 alphaTB) {
float lambdaV=NdotL*length(vec3(alphaTB.x*TdotV,alphaTB.y*BdotV,NdotV));
float lambdaL=NdotV*length(vec3(alphaTB.x*TdotL,alphaTB.y*BdotL,NdotL));
float v=0.5/(lambdaV+lambdaL);
return v;
}
#endif
#ifdef CLEARCOAT
float visibility_Kelemen(float VdotH) {



return 0.25/(VdotH*VdotH);
}
#endif
#ifdef SHEEN



float visibility_Ashikhmin(float NdotL,float NdotV)
{
return 1./(4.*(NdotL+NdotV-NdotL*NdotV));
}

#endif







float diffuseBRDF_Burley(float NdotL,float NdotV,float VdotH,float roughness) {


float diffuseFresnelNV=pow5(saturateEps(1.0-NdotL));
float diffuseFresnelNL=pow5(saturateEps(1.0-NdotV));
float diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;
float fresnel =
(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *
(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);
return fresnel/PI;
}
#ifdef SS_TRANSLUCENCY


vec3 transmittanceBRDF_Burley(const vec3 tintColor,const vec3 diffusionDistance,float thickness) {
vec3 S=1./maxEps(diffusionDistance);
vec3 temp=exp((-0.333333333*thickness)*S);
return tintColor.rgb*0.25*(temp*temp*temp+3.0*temp);
}


float computeWrappedDiffuseNdotL(float NdotL,float w) {
float t=1.0+w;
float invt2=1.0/square(t);
return saturate((NdotL+w)*invt2);
}
#endif
`;
ShaderStore.IncludesShadersStore[name$1l] = shader$1l;
var name$1k = "hdrFilteringFunctions"
  , shader$1k = `#ifdef NUM_SAMPLES
#if NUM_SAMPLES>0
#if defined(WEBGL2) || defined(WEBGPU)


float radicalInverse_VdC(uint bits)
{
bits=(bits << 16u) | (bits >> 16u);
bits=((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u);
bits=((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u);
bits=((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u);
bits=((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u);
return float(bits)*2.3283064365386963e-10;
}
vec2 hammersley(uint i,uint N)
{
return vec2(float(i)/float(N),radicalInverse_VdC(i));
}
#else
float vanDerCorpus(int n,int base)
{
float invBase=1.0/float(base);
float denom=1.0;
float result=0.0;
for(int i=0; i<32; ++i)
{
if(n>0)
{
denom=mod(float(n),2.0);
result+=denom*invBase;
invBase=invBase/2.0;
n=int(float(n)/2.0);
}
}
return result;
}
vec2 hammersley(int i,int N)
{
return vec2(float(i)/float(N),vanDerCorpus(i,2));
}
#endif
float log4(float x) {
return log2(x)/2.;
}
const float NUM_SAMPLES_FLOAT=float(NUM_SAMPLES);
const float NUM_SAMPLES_FLOAT_INVERSED=1./NUM_SAMPLES_FLOAT;
const float K=4.;



















































































































#define inline
vec3 irradiance(samplerCube inputTexture,vec3 inputN,vec2 filteringInfo)
{
vec3 n=normalize(inputN);
vec3 result=vec3(0.0);
vec3 tangent=abs(n.z)<0.999 ? vec3(0.,0.,1.) : vec3(1.,0.,0.);
tangent=normalize(cross(tangent,n));
vec3 bitangent=cross(n,tangent);
mat3 tbn=mat3(tangent,bitangent,n);
float maxLevel=filteringInfo.y;
float dim0=filteringInfo.x;
float omegaP=(4.*PI)/(6.*dim0*dim0);
#if defined(WEBGL2) || defined(WEBGPU)
for(uint i=0u; i<NUM_SAMPLES; ++i)
#else
for(int i=0; i<NUM_SAMPLES; ++i)
#endif
{
vec2 Xi=hammersley(i,NUM_SAMPLES);
vec3 Ls=hemisphereCosSample(Xi);
Ls=normalize(Ls);
vec3 Ns=vec3(0.,0.,1.);
float NoL=dot(Ns,Ls);
if (NoL>0.) {
float pdf_inversed=PI/NoL;
float omegaS=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;
float l=log4(omegaS)-log4(omegaP)+log4(K);
float mipLevel=clamp(l,0.0,maxLevel);
vec3 c=textureCubeLodEXT(inputTexture,tbn*Ls,mipLevel).rgb;
#ifdef GAMMA_INPUT
c=toLinearSpace(c);
#endif
result+=c;
}
}
result=result*NUM_SAMPLES_FLOAT_INVERSED;
return result;
}
#define inline
vec3 radiance(float alphaG,samplerCube inputTexture,vec3 inputN,vec2 filteringInfo)
{
vec3 n=normalize(inputN);
if (alphaG == 0.) {
vec3 c=textureCube(inputTexture,n).rgb;
#ifdef GAMMA_INPUT
c=toLinearSpace(c);
#endif
return c;
} else {
vec3 result=vec3(0.);
vec3 tangent=abs(n.z)<0.999 ? vec3(0.,0.,1.) : vec3(1.,0.,0.);
tangent=normalize(cross(tangent,n));
vec3 bitangent=cross(n,tangent);
mat3 tbn=mat3(tangent,bitangent,n);
float maxLevel=filteringInfo.y;
float dim0=filteringInfo.x;
float omegaP=(4.*PI)/(6.*dim0*dim0);
float weight=0.;
#if defined(WEBGL2) || defined(WEBGPU)
for(uint i=0u; i<NUM_SAMPLES; ++i)
#else
for(int i=0; i<NUM_SAMPLES; ++i)
#endif
{
vec2 Xi=hammersley(i,NUM_SAMPLES);
vec3 H=hemisphereImportanceSampleDggx(Xi,alphaG);
float NoV=1.;
float NoH=H.z;
float NoH2=H.z*H.z;
float NoL=2.*NoH2-1.;
vec3 L=vec3(2.*NoH*H.x,2.*NoH*H.y,NoL);
L=normalize(L);
if (NoL>0.) {
float pdf_inversed=4./normalDistributionFunction_TrowbridgeReitzGGX(NoH,alphaG);
float omegaS=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;
float l=log4(omegaS)-log4(omegaP)+log4(K);
float mipLevel=clamp(float(l),0.0,maxLevel);
weight+=NoL;
vec3 c=textureCubeLodEXT(inputTexture,tbn*L,mipLevel).rgb;
#ifdef GAMMA_INPUT
c=toLinearSpace(c);
#endif
result+=c*NoL;
}
}
result=result/weight;
return result;
}
}
#endif
#endif`;
ShaderStore.IncludesShadersStore[name$1k] = shader$1k;
var name$1j = "pbrDirectLightingFunctions"
  , shader$1j = `#define CLEARCOATREFLECTANCE90 1.0

struct lightingInfo
{
vec3 diffuse;
#ifdef SPECULARTERM
vec3 specular;
#endif
#ifdef CLEARCOAT


vec4 clearCoat;
#endif
#ifdef SHEEN
vec3 sheen;
#endif
};

float adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance) {
#if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF)

float lightRoughness=lightRadius/lightDistance;

float totalRoughness=saturate(lightRoughness+roughness);
return totalRoughness;
#else
return roughness;
#endif
}
vec3 computeHemisphericDiffuseLighting(preLightingInfo info,vec3 lightColor,vec3 groundColor) {
return mix(groundColor,lightColor,info.NdotL);
}
vec3 computeDiffuseLighting(preLightingInfo info,vec3 lightColor) {
float diffuseTerm=diffuseBRDF_Burley(info.NdotL,info.NdotV,info.VdotH,info.roughness);
return diffuseTerm*info.attenuation*info.NdotL*lightColor;
}
#define inline
vec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){
vec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);
strq/=strq.w;
vec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;
return toLinearSpace(textureColor);
}
#ifdef SS_TRANSLUCENCY
vec3 computeDiffuseAndTransmittedLighting(preLightingInfo info,vec3 lightColor,vec3 transmittance) {
float NdotL=absEps(info.NdotLUnclamped);

float wrapNdotL=computeWrappedDiffuseNdotL(NdotL,0.02);

float trAdapt=step(0.,info.NdotLUnclamped);
vec3 transmittanceNdotL=mix(transmittance*wrapNdotL,vec3(wrapNdotL),trAdapt);
float diffuseTerm=diffuseBRDF_Burley(NdotL,info.NdotV,info.VdotH,info.roughness);
return diffuseTerm*transmittanceNdotL*info.attenuation*lightColor;
}
#endif
#ifdef SPECULARTERM
vec3 computeSpecularLighting(preLightingInfo info,vec3 N,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {
float NdotH=saturateEps(dot(N,info.H));
float roughness=max(info.roughness,geometricRoughnessFactor);
float alphaG=convertRoughnessToAverageSlope(roughness);
vec3 fresnel=fresnelSchlickGGX(info.VdotH,reflectance0,reflectance90);
float distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);
#ifdef BRDF_V_HEIGHT_CORRELATED
float smithVisibility=smithVisibility_GGXCorrelated(info.NdotL,info.NdotV,alphaG);
#else
float smithVisibility=smithVisibility_TrowbridgeReitzGGXFast(info.NdotL,info.NdotV,alphaG);
#endif
vec3 specTerm=fresnel*distribution*smithVisibility;
return specTerm*info.attenuation*info.NdotL*lightColor;
}
#endif
#ifdef ANISOTROPIC
vec3 computeAnisotropicSpecularLighting(preLightingInfo info,vec3 V,vec3 N,vec3 T,vec3 B,float anisotropy,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {
float NdotH=saturateEps(dot(N,info.H));
float TdotH=dot(T,info.H);
float BdotH=dot(B,info.H);
float TdotV=dot(T,V);
float BdotV=dot(B,V);
float TdotL=dot(T,info.L);
float BdotL=dot(B,info.L);
float alphaG=convertRoughnessToAverageSlope(info.roughness);
vec2 alphaTB=getAnisotropicRoughness(alphaG,anisotropy);
alphaTB=max(alphaTB,square(geometricRoughnessFactor));
vec3 fresnel=fresnelSchlickGGX(info.VdotH,reflectance0,reflectance90);
float distribution=normalDistributionFunction_BurleyGGX_Anisotropic(NdotH,TdotH,BdotH,alphaTB);
float smithVisibility=smithVisibility_GGXCorrelated_Anisotropic(info.NdotL,info.NdotV,TdotV,BdotV,TdotL,BdotL,alphaTB);
vec3 specTerm=fresnel*distribution*smithVisibility;
return specTerm*info.attenuation*info.NdotL*lightColor;
}
#endif
#ifdef CLEARCOAT
vec4 computeClearCoatLighting(preLightingInfo info,vec3 Ncc,float geometricRoughnessFactor,float clearCoatIntensity,vec3 lightColor) {
float NccdotL=saturateEps(dot(Ncc,info.L));
float NccdotH=saturateEps(dot(Ncc,info.H));
float clearCoatRoughness=max(info.roughness,geometricRoughnessFactor);
float alphaG=convertRoughnessToAverageSlope(clearCoatRoughness);
float fresnel=fresnelSchlickGGX(info.VdotH,vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);
fresnel*=clearCoatIntensity;
float distribution=normalDistributionFunction_TrowbridgeReitzGGX(NccdotH,alphaG);
float kelemenVisibility=visibility_Kelemen(info.VdotH);
float clearCoatTerm=fresnel*distribution*kelemenVisibility;
return vec4(
clearCoatTerm*info.attenuation*NccdotL*lightColor,
1.0-fresnel
);
}
vec3 computeClearCoatLightingAbsorption(float NdotVRefract,vec3 L,vec3 Ncc,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {
vec3 LRefract=-refract(L,Ncc,vClearCoatRefractionParams.y);
float NdotLRefract=saturateEps(dot(Ncc,LRefract));
vec3 absorption=computeClearCoatAbsorption(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness,clearCoatIntensity);
return absorption;
}
#endif
#ifdef SHEEN
vec3 computeSheenLighting(preLightingInfo info,vec3 N,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {
float NdotH=saturateEps(dot(N,info.H));
float roughness=max(info.roughness,geometricRoughnessFactor);
float alphaG=convertRoughnessToAverageSlope(roughness);


float fresnel=1.;
float distribution=normalDistributionFunction_CharlieSheen(NdotH,alphaG);

float visibility=visibility_Ashikhmin(info.NdotL,info.NdotV);

float sheenTerm=fresnel*distribution*visibility;
return sheenTerm*info.attenuation*info.NdotL*lightColor;
}
#endif
`;
ShaderStore.IncludesShadersStore[name$1j] = shader$1j;
var name$1i = "pbrIBLFunctions"
  , shader$1i = `#if defined(REFLECTION) || defined(SS_REFRACTION)
float getLodFromAlphaG(float cubeMapDimensionPixels,float microsurfaceAverageSlope) {
float microsurfaceAverageSlopeTexels=cubeMapDimensionPixels*microsurfaceAverageSlope;
float lod=log2(microsurfaceAverageSlopeTexels);
return lod;
}
float getLinearLodFromRoughness(float cubeMapDimensionPixels,float roughness) {
float lod=log2(cubeMapDimensionPixels)*roughness;
return lod;
}
#endif
#if defined(ENVIRONMENTBRDF) && defined(RADIANCEOCCLUSION)
float environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {


float temp=NdotVUnclamped+ambientOcclusion;
return saturate(square(temp)-1.0+ambientOcclusion);
}
#endif
#if defined(ENVIRONMENTBRDF) && defined(HORIZONOCCLUSION)
float environmentHorizonOcclusion(vec3 view,vec3 normal,vec3 geometricNormal) {

vec3 reflection=reflect(view,normal);
float temp=saturate(1.0+1.1*dot(reflection,geometricNormal));
return square(temp);
}
#endif




#if defined(LODINREFLECTIONALPHA) || defined(SS_LODINREFRACTIONALPHA)


#define UNPACK_LOD(x) (1.0-x)*255.0
float getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {
float microsurfaceAverageSlope=alphaG;






microsurfaceAverageSlope*=sqrt(abs(NdotV));
return getLodFromAlphaG(cubeMapDimensionPixels,microsurfaceAverageSlope);
}
#endif`;
ShaderStore.IncludesShadersStore[name$1i] = shader$1i;
var name$1h = "pbrBlockAlbedoOpacity"
  , shader$1h = `struct albedoOpacityOutParams
{
vec3 surfaceAlbedo;
float alpha;
};
#define pbr_inline
void albedoOpacityBlock(
in vec4 vAlbedoColor,
#ifdef ALBEDO
in vec4 albedoTexture,
in vec2 albedoInfos,
#endif
#ifdef OPACITY
in vec4 opacityMap,
in vec2 vOpacityInfos,
#endif
#ifdef DETAIL
in vec4 detailColor,
in vec4 vDetailInfos,
#endif
out albedoOpacityOutParams outParams
)
{

vec3 surfaceAlbedo=vAlbedoColor.rgb;
float alpha=vAlbedoColor.a;
#ifdef ALBEDO
#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)
alpha*=albedoTexture.a;
#endif
#ifdef GAMMAALBEDO
surfaceAlbedo*=toLinearSpace(albedoTexture.rgb);
#else
surfaceAlbedo*=albedoTexture.rgb;
#endif
surfaceAlbedo*=albedoInfos.y;
#endif
#ifdef VERTEXCOLOR
surfaceAlbedo*=vColor.rgb;
#endif
#ifdef DETAIL
float detailAlbedo=2.0*mix(0.5,detailColor.r,vDetailInfos.y);
surfaceAlbedo.rgb=surfaceAlbedo.rgb*detailAlbedo*detailAlbedo;
#endif
#define CUSTOM_FRAGMENT_UPDATE_ALBEDO

#ifdef OPACITY
#ifdef OPACITYRGB
alpha=getLuminance(opacityMap.rgb);
#else
alpha*=opacityMap.a;
#endif
alpha*=vOpacityInfos.y;
#endif
#ifdef VERTEXALPHA
alpha*=vColor.a;
#endif
#if !defined(SS_LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)
#ifdef ALPHATEST
if (alpha<ALPHATESTVALUE)
discard;
#ifndef ALPHABLEND

alpha=1.0;
#endif
#endif
#endif
outParams.surfaceAlbedo=surfaceAlbedo;
outParams.alpha=alpha;
}
`;
ShaderStore.IncludesShadersStore[name$1h] = shader$1h;
var name$1g = "pbrBlockReflectivity"
  , shader$1g = `struct reflectivityOutParams
{
float microSurface;
float roughness;
vec3 surfaceReflectivityColor;
#ifdef METALLICWORKFLOW
vec3 surfaceAlbedo;
#endif
#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)
vec3 ambientOcclusionColor;
#endif
#if DEBUGMODE>0
vec4 surfaceMetallicColorMap;
vec4 surfaceReflectivityColorMap;
vec2 metallicRoughness;
vec3 metallicF0;
#endif
};
#define pbr_inline
void reflectivityBlock(
in vec4 vReflectivityColor,
#ifdef METALLICWORKFLOW
in vec3 surfaceAlbedo,
in vec4 metallicReflectanceFactors,
#endif
#ifdef REFLECTIVITY
in vec3 reflectivityInfos,
in vec4 surfaceMetallicOrReflectivityColorMap,
#endif
#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)
in vec3 ambientOcclusionColorIn,
#endif
#ifdef MICROSURFACEMAP
in vec4 microSurfaceTexel,
#endif
#ifdef DETAIL
in vec4 detailColor,
in vec4 vDetailInfos,
#endif
out reflectivityOutParams outParams
)
{
float microSurface=vReflectivityColor.a;
vec3 surfaceReflectivityColor=vReflectivityColor.rgb;
#ifdef METALLICWORKFLOW
vec2 metallicRoughness=surfaceReflectivityColor.rg;
#ifdef REFLECTIVITY
#if DEBUGMODE>0
outParams.surfaceMetallicColorMap=surfaceMetallicOrReflectivityColorMap;
#endif
#ifdef AOSTOREINMETALMAPRED
vec3 aoStoreInMetalMap=vec3(surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r);
outParams.ambientOcclusionColor=mix(ambientOcclusionColorIn,aoStoreInMetalMap,reflectivityInfos.z);
#endif
#ifdef METALLNESSSTOREINMETALMAPBLUE
metallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.b;
#else
metallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.r;
#endif
#ifdef ROUGHNESSSTOREINMETALMAPALPHA
metallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.a;
#else
#ifdef ROUGHNESSSTOREINMETALMAPGREEN
metallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.g;
#endif
#endif
#endif
#ifdef DETAIL
float detailRoughness=mix(0.5,detailColor.b,vDetailInfos.w);
float loLerp=mix(0.,metallicRoughness.g,detailRoughness*2.);
float hiLerp=mix(metallicRoughness.g,1.,(detailRoughness-0.5)*2.);
metallicRoughness.g=mix(loLerp,hiLerp,step(detailRoughness,0.5));
#endif
#ifdef MICROSURFACEMAP
metallicRoughness.g*=microSurfaceTexel.r;
#endif
#if DEBUGMODE>0
outParams.metallicRoughness=metallicRoughness;
#endif
#define CUSTOM_FRAGMENT_UPDATE_METALLICROUGHNESS

microSurface=1.0-metallicRoughness.g;

vec3 baseColor=surfaceAlbedo;
#ifdef FROSTBITE_REFLECTANCE






outParams.surfaceAlbedo=baseColor.rgb*(1.0-metallicRoughness.r);

surfaceReflectivityColor=mix(0.16*reflectance*reflectance,baseColor,metallicRoughness.r);
#else
vec3 metallicF0=metallicReflectanceFactors.rgb;
#if DEBUGMODE>0
outParams.metallicF0=metallicF0;
#endif

outParams.surfaceAlbedo=mix(baseColor.rgb*(1.0-metallicF0),vec3(0.,0.,0.),metallicRoughness.r);

surfaceReflectivityColor=mix(metallicF0,baseColor,metallicRoughness.r);
#endif
#else
#ifdef REFLECTIVITY
surfaceReflectivityColor*=surfaceMetallicOrReflectivityColorMap.rgb;
#if DEBUGMODE>0
outParams.surfaceReflectivityColorMap=surfaceMetallicOrReflectivityColorMap;
#endif
#ifdef MICROSURFACEFROMREFLECTIVITYMAP
microSurface*=surfaceMetallicOrReflectivityColorMap.a;
microSurface*=reflectivityInfos.z;
#else
#ifdef MICROSURFACEAUTOMATIC
microSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);
#endif
#ifdef MICROSURFACEMAP
microSurface*=microSurfaceTexel.r;
#endif
#define CUSTOM_FRAGMENT_UPDATE_MICROSURFACE
#endif
#endif
#endif

microSurface=saturate(microSurface);

float roughness=1.-microSurface;
outParams.microSurface=microSurface;
outParams.roughness=roughness;
outParams.surfaceReflectivityColor=surfaceReflectivityColor;
}
`;
ShaderStore.IncludesShadersStore[name$1g] = shader$1g;
var name$1f = "pbrBlockAmbientOcclusion"
  , shader$1f = `struct ambientOcclusionOutParams
{
vec3 ambientOcclusionColor;
#if DEBUGMODE>0
vec3 ambientOcclusionColorMap;
#endif
};
#define pbr_inline
void ambientOcclusionBlock(
#ifdef AMBIENT
in vec3 ambientOcclusionColorMap_,
in vec4 vAmbientInfos,
#endif
out ambientOcclusionOutParams outParams
)
{
vec3 ambientOcclusionColor=vec3(1.,1.,1.);
#ifdef AMBIENT
vec3 ambientOcclusionColorMap=ambientOcclusionColorMap_*vAmbientInfos.y;
#ifdef AMBIENTINGRAYSCALE
ambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);
#endif
ambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);
#if DEBUGMODE>0
outParams.ambientOcclusionColorMap=ambientOcclusionColorMap;
#endif
#endif
outParams.ambientOcclusionColor=ambientOcclusionColor;
}
`;
ShaderStore.IncludesShadersStore[name$1f] = shader$1f;
var name$1e = "pbrBlockAlphaFresnel"
  , shader$1e = `#ifdef ALPHAFRESNEL
#if defined(ALPHATEST) || defined(ALPHABLEND)
struct alphaFresnelOutParams
{
float alpha;
};
#define pbr_inline
void alphaFresnelBlock(
in vec3 normalW,
in vec3 viewDirectionW,
in float alpha,
in float microSurface,
out alphaFresnelOutParams outParams
)
{



float opacityPerceptual=alpha;
#ifdef LINEARALPHAFRESNEL
float opacity0=opacityPerceptual;
#else
float opacity0=opacityPerceptual*opacityPerceptual;
#endif
float opacity90=fresnelGrazingReflectance(opacity0);
vec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);

outParams.alpha=getReflectanceFromAnalyticalBRDFLookup_Jones(saturate(dot(viewDirectionW,normalForward)),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;
#ifdef ALPHATEST
if (outParams.alpha<ALPHATESTVALUE)
discard;
#ifndef ALPHABLEND

outParams.alpha=1.0;
#endif
#endif
}
#endif
#endif
`;
ShaderStore.IncludesShadersStore[name$1e] = shader$1e;
var name$1d = "pbrBlockAnisotropic"
  , shader$1d = `#ifdef ANISOTROPIC
struct anisotropicOutParams
{
float anisotropy;
vec3 anisotropicTangent;
vec3 anisotropicBitangent;
vec3 anisotropicNormal;
#if DEBUGMODE>0
vec3 anisotropyMapData;
#endif
};
#define pbr_inline
void anisotropicBlock(
in vec3 vAnisotropy,
#ifdef ANISOTROPIC_TEXTURE
in vec3 anisotropyMapData,
#endif
in mat3 TBN,
in vec3 normalW,
in vec3 viewDirectionW,
out anisotropicOutParams outParams
)
{
float anisotropy=vAnisotropy.b;
vec3 anisotropyDirection=vec3(vAnisotropy.xy,0.);
#ifdef ANISOTROPIC_TEXTURE
anisotropy*=anisotropyMapData.b;
anisotropyDirection.rg*=anisotropyMapData.rg*2.0-1.0;
#if DEBUGMODE>0
outParams.anisotropyMapData=anisotropyMapData;
#endif
#endif
mat3 anisoTBN=mat3(normalize(TBN[0]),normalize(TBN[1]),normalize(TBN[2]));
vec3 anisotropicTangent=normalize(anisoTBN*anisotropyDirection);
vec3 anisotropicBitangent=normalize(cross(anisoTBN[2],anisotropicTangent));
outParams.anisotropy=anisotropy;
outParams.anisotropicTangent=anisotropicTangent;
outParams.anisotropicBitangent=anisotropicBitangent;
outParams.anisotropicNormal=getAnisotropicBentNormals(anisotropicTangent,anisotropicBitangent,normalW,viewDirectionW,anisotropy);
}
#endif
`;
ShaderStore.IncludesShadersStore[name$1d] = shader$1d;
var name$1c = "pbrBlockReflection"
  , shader$1c = `#ifdef REFLECTION
struct reflectionOutParams
{
vec4 environmentRadiance;
vec3 environmentIrradiance;
#ifdef REFLECTIONMAP_3D
vec3 reflectionCoords;
#else
vec2 reflectionCoords;
#endif
#ifdef SS_TRANSLUCENCY
#ifdef USESPHERICALFROMREFLECTIONMAP
#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)
vec3 irradianceVector;
#endif
#endif
#endif
};
#define pbr_inline
void createReflectionCoords(
in vec3 vPositionW,
in vec3 normalW,
#ifdef ANISOTROPIC
in anisotropicOutParams anisotropicOut,
#endif
#ifdef REFLECTIONMAP_3D
out vec3 reflectionCoords
#else
out vec2 reflectionCoords
#endif
)
{
#ifdef ANISOTROPIC
vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),anisotropicOut.anisotropicNormal);
#else
vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);
#endif
#ifdef REFLECTIONMAP_OPPOSITEZ
reflectionVector.z*=-1.0;
#endif

#ifdef REFLECTIONMAP_3D
reflectionCoords=reflectionVector;
#else
reflectionCoords=reflectionVector.xy;
#ifdef REFLECTIONMAP_PROJECTION
reflectionCoords/=reflectionVector.z;
#endif
reflectionCoords.y=1.0-reflectionCoords.y;
#endif
}
#define pbr_inline
#define inline
void sampleReflectionTexture(
in float alphaG,
in vec3 vReflectionMicrosurfaceInfos,
in vec2 vReflectionInfos,
in vec3 vReflectionColor,
#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
in float NdotVUnclamped,
#endif
#ifdef LINEARSPECULARREFLECTION
in float roughness,
#endif
#ifdef REFLECTIONMAP_3D
in samplerCube reflectionSampler,
const vec3 reflectionCoords,
#else
in sampler2D reflectionSampler,
const vec2 reflectionCoords,
#endif
#ifndef LODBASEDMICROSFURACE
#ifdef REFLECTIONMAP_3D
in samplerCube reflectionSamplerLow,
in samplerCube reflectionSamplerHigh,
#else
in sampler2D reflectionSamplerLow,
in sampler2D reflectionSamplerHigh,
#endif
#endif
#ifdef REALTIME_FILTERING
in vec2 vReflectionFilteringInfo,
#endif
out vec4 environmentRadiance
)
{

#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
float reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);
#elif defined(LINEARSPECULARREFLECTION)
float reflectionLOD=getLinearLodFromRoughness(vReflectionMicrosurfaceInfos.x,roughness);
#else
float reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG);
#endif
#ifdef LODBASEDMICROSFURACE

reflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;
#ifdef LODINREFLECTIONALPHA









float automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);
float requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);
#else
float requestedReflectionLOD=reflectionLOD;
#endif
#ifdef REALTIME_FILTERING
environmentRadiance=vec4(radiance(alphaG,reflectionSampler,reflectionCoords,vReflectionFilteringInfo),1.0);
#else
environmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);
#endif
#else
float lodReflectionNormalized=saturate(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x));
float lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;
vec4 environmentMid=sampleReflection(reflectionSampler,reflectionCoords);
if (lodReflectionNormalizedDoubled<1.0){
environmentRadiance=mix(
sampleReflection(reflectionSamplerHigh,reflectionCoords),
environmentMid,
lodReflectionNormalizedDoubled
);
} else {
environmentRadiance=mix(
environmentMid,
sampleReflection(reflectionSamplerLow,reflectionCoords),
lodReflectionNormalizedDoubled-1.0
);
}
#endif
#ifdef RGBDREFLECTION
environmentRadiance.rgb=fromRGBD(environmentRadiance);
#endif
#ifdef GAMMAREFLECTION
environmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);
#endif

environmentRadiance.rgb*=vReflectionInfos.x;
environmentRadiance.rgb*=vReflectionColor.rgb;
}
#define pbr_inline
#define inline
void reflectionBlock(
in vec3 vPositionW,
in vec3 normalW,
in float alphaG,
in vec3 vReflectionMicrosurfaceInfos,
in vec2 vReflectionInfos,
in vec3 vReflectionColor,
#ifdef ANISOTROPIC
in anisotropicOutParams anisotropicOut,
#endif
#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
in float NdotVUnclamped,
#endif
#ifdef LINEARSPECULARREFLECTION
in float roughness,
#endif
#ifdef REFLECTIONMAP_3D
in samplerCube reflectionSampler,
#else
in sampler2D reflectionSampler,
#endif
#if defined(NORMAL) && defined(USESPHERICALINVERTEX)
in vec3 vEnvironmentIrradiance,
#endif
#ifdef USESPHERICALFROMREFLECTIONMAP
#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)
in mat4 reflectionMatrix,
#endif
#endif
#ifdef USEIRRADIANCEMAP
#ifdef REFLECTIONMAP_3D
in samplerCube irradianceSampler,
#else
in sampler2D irradianceSampler,
#endif
#endif
#ifndef LODBASEDMICROSFURACE
#ifdef REFLECTIONMAP_3D
in samplerCube reflectionSamplerLow,
in samplerCube reflectionSamplerHigh,
#else
in sampler2D reflectionSamplerLow,
in sampler2D reflectionSamplerHigh,
#endif
#endif
#ifdef REALTIME_FILTERING
in vec2 vReflectionFilteringInfo,
#endif
out reflectionOutParams outParams
)
{

vec4 environmentRadiance=vec4(0.,0.,0.,0.);
#ifdef REFLECTIONMAP_3D
vec3 reflectionCoords=vec3(0.);
#else
vec2 reflectionCoords=vec2(0.);
#endif
createReflectionCoords(
vPositionW,
normalW,
#ifdef ANISOTROPIC
anisotropicOut,
#endif
reflectionCoords
);
sampleReflectionTexture(
alphaG,
vReflectionMicrosurfaceInfos,
vReflectionInfos,
vReflectionColor,
#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
NdotVUnclamped,
#endif
#ifdef LINEARSPECULARREFLECTION
roughness,
#endif
#ifdef REFLECTIONMAP_3D
reflectionSampler,
reflectionCoords,
#else
reflectionSampler,
reflectionCoords,
#endif
#ifndef LODBASEDMICROSFURACE
reflectionSamplerLow,
reflectionSamplerHigh,
#endif
#ifdef REALTIME_FILTERING
vReflectionFilteringInfo,
#endif
environmentRadiance
);

vec3 environmentIrradiance=vec3(0.,0.,0.);
#ifdef USESPHERICALFROMREFLECTIONMAP
#if defined(NORMAL) && defined(USESPHERICALINVERTEX)
environmentIrradiance=vEnvironmentIrradiance;
#else
#ifdef ANISOTROPIC
vec3 irradianceVector=vec3(reflectionMatrix*vec4(anisotropicOut.anisotropicNormal,0)).xyz;
#else
vec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;
#endif
#ifdef REFLECTIONMAP_OPPOSITEZ
irradianceVector.z*=-1.0;
#endif
#ifdef INVERTCUBICMAP
irradianceVector.y*=-1.0;
#endif
#if defined(REALTIME_FILTERING)
environmentIrradiance=irradiance(reflectionSampler,irradianceVector,vReflectionFilteringInfo);
#else
environmentIrradiance=computeEnvironmentIrradiance(irradianceVector);
#endif
#ifdef SS_TRANSLUCENCY
outParams.irradianceVector=irradianceVector;
#endif
#endif
#elif defined(USEIRRADIANCEMAP)
vec4 environmentIrradiance4=sampleReflection(irradianceSampler,reflectionCoords);
environmentIrradiance=environmentIrradiance4.rgb;
#ifdef RGBDREFLECTION
environmentIrradiance.rgb=fromRGBD(environmentIrradiance4);
#endif
#ifdef GAMMAREFLECTION
environmentIrradiance.rgb=toLinearSpace(environmentIrradiance.rgb);
#endif
#endif
environmentIrradiance*=vReflectionColor.rgb;
outParams.environmentRadiance=environmentRadiance;
outParams.environmentIrradiance=environmentIrradiance;
outParams.reflectionCoords=reflectionCoords;
}
#endif
`;
ShaderStore.IncludesShadersStore[name$1c] = shader$1c;
var name$1b = "pbrBlockSheen"
  , shader$1b = `#ifdef SHEEN
struct sheenOutParams
{
float sheenIntensity;
vec3 sheenColor;
float sheenRoughness;
#ifdef SHEEN_LINKWITHALBEDO
vec3 surfaceAlbedo;
#endif
#if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)
float sheenAlbedoScaling;
#endif
#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)
vec3 finalSheenRadianceScaled;
#endif
#if DEBUGMODE>0
vec4 sheenMapData;
vec3 sheenEnvironmentReflectance;
#endif
};
#define pbr_inline
#define inline
void sheenBlock(
in vec4 vSheenColor,
#ifdef SHEEN_ROUGHNESS
in float vSheenRoughness,
#if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE)
in vec4 sheenMapRoughnessData,
#endif
#endif
in float roughness,
#ifdef SHEEN_TEXTURE
in vec4 sheenMapData,
in float sheenMapLevel,
#endif
in float reflectance,
#ifdef SHEEN_LINKWITHALBEDO
in vec3 baseColor,
in vec3 surfaceAlbedo,
#endif
#ifdef ENVIRONMENTBRDF
in float NdotV,
in vec3 environmentBrdf,
#endif
#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)
in vec2 AARoughnessFactors,
in vec3 vReflectionMicrosurfaceInfos,
in vec2 vReflectionInfos,
in vec3 vReflectionColor,
in vec4 vLightingIntensity,
#ifdef REFLECTIONMAP_3D
in samplerCube reflectionSampler,
in vec3 reflectionCoords,
#else
in sampler2D reflectionSampler,
in vec2 reflectionCoords,
#endif
in float NdotVUnclamped,
#ifndef LODBASEDMICROSFURACE
#ifdef REFLECTIONMAP_3D
in samplerCube reflectionSamplerLow,
in samplerCube reflectionSamplerHigh,
#else
in sampler2D reflectionSamplerLow,
in sampler2D reflectionSamplerHigh,
#endif
#endif
#ifdef REALTIME_FILTERING
in vec2 vReflectionFilteringInfo,
#endif
#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION)
in float seo,
#endif
#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)
in float eho,
#endif
#endif
out sheenOutParams outParams
)
{
float sheenIntensity=vSheenColor.a;
#ifdef SHEEN_TEXTURE
#if DEBUGMODE>0
outParams.sheenMapData=sheenMapData;
#endif
#endif
#ifdef SHEEN_LINKWITHALBEDO
float sheenFactor=pow5(1.0-sheenIntensity);
vec3 sheenColor=baseColor.rgb*(1.0-sheenFactor);
float sheenRoughness=sheenIntensity;
outParams.surfaceAlbedo=surfaceAlbedo*sheenFactor;
#ifdef SHEEN_TEXTURE
sheenIntensity*=sheenMapData.a;
#endif
#else
vec3 sheenColor=vSheenColor.rgb;
#ifdef SHEEN_TEXTURE
#ifdef SHEEN_GAMMATEXTURE
sheenColor.rgb*=toLinearSpace(sheenMapData.rgb);
#else
sheenColor.rgb*=sheenMapData.rgb;
#endif
sheenColor.rgb*=sheenMapLevel;
#endif
#ifdef SHEEN_ROUGHNESS
float sheenRoughness=vSheenRoughness;
#ifdef SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE
#if defined(SHEEN_TEXTURE)
sheenRoughness*=sheenMapData.a;
#endif
#elif defined(SHEEN_TEXTURE_ROUGHNESS)
#ifdef SHEEN_TEXTURE_ROUGHNESS_IDENTICAL
sheenRoughness*=sheenMapData.a;
#else
sheenRoughness*=sheenMapRoughnessData.a;
#endif
#endif
#else
float sheenRoughness=roughness;
#ifdef SHEEN_TEXTURE
sheenIntensity*=sheenMapData.a;
#endif
#endif

#if !defined(SHEEN_ALBEDOSCALING)
sheenIntensity*=(1.-reflectance);
#endif

sheenColor*=sheenIntensity;
#endif

#ifdef ENVIRONMENTBRDF

#ifdef SHEEN_ROUGHNESS
vec3 environmentSheenBrdf=getBRDFLookup(NdotV,sheenRoughness);
#else
vec3 environmentSheenBrdf=environmentBrdf;
#endif

#endif
#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)
float sheenAlphaG=convertRoughnessToAverageSlope(sheenRoughness);
#ifdef SPECULARAA

sheenAlphaG+=AARoughnessFactors.y;
#endif
vec4 environmentSheenRadiance=vec4(0.,0.,0.,0.);
sampleReflectionTexture(
sheenAlphaG,
vReflectionMicrosurfaceInfos,
vReflectionInfos,
vReflectionColor,
#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
NdotVUnclamped,
#endif
#ifdef LINEARSPECULARREFLECTION
sheenRoughness,
#endif
reflectionSampler,
reflectionCoords,
#ifndef LODBASEDMICROSFURACE
reflectionSamplerLow,
reflectionSamplerHigh,
#endif
#ifdef REALTIME_FILTERING
vReflectionFilteringInfo,
#endif
environmentSheenRadiance
);
vec3 sheenEnvironmentReflectance=getSheenReflectanceFromBRDFLookup(sheenColor,environmentSheenBrdf);
#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION)
sheenEnvironmentReflectance*=seo;
#endif
#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)
sheenEnvironmentReflectance*=eho;
#endif
#if DEBUGMODE>0
outParams.sheenEnvironmentReflectance=sheenEnvironmentReflectance;
#endif
outParams.finalSheenRadianceScaled=
environmentSheenRadiance.rgb *
sheenEnvironmentReflectance *
vLightingIntensity.z;





#endif
#if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)



outParams.sheenAlbedoScaling=1.0-sheenIntensity*max(max(sheenColor.r,sheenColor.g),sheenColor.b)*environmentSheenBrdf.b;
#endif

outParams.sheenIntensity=sheenIntensity;
outParams.sheenColor=sheenColor;
outParams.sheenRoughness=sheenRoughness;
}
#endif
`;
ShaderStore.IncludesShadersStore[name$1b] = shader$1b;
var name$1a = "pbrBlockClearcoat"
  , shader$1a = `struct clearcoatOutParams
{
vec3 specularEnvironmentR0;
float conservationFactor;
vec3 clearCoatNormalW;
vec2 clearCoatAARoughnessFactors;
float clearCoatIntensity;
float clearCoatRoughness;
#ifdef REFLECTION
vec3 finalClearCoatRadianceScaled;
#endif
#ifdef CLEARCOAT_TINT
vec3 absorption;
float clearCoatNdotVRefract;
vec3 clearCoatColor;
float clearCoatThickness;
#endif
#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)
vec3 energyConservationFactorClearCoat;
#endif
#if DEBUGMODE>0
mat3 TBNClearCoat;
vec2 clearCoatMapData;
vec4 clearCoatTintMapData;
vec4 environmentClearCoatRadiance;
float clearCoatNdotV;
vec3 clearCoatEnvironmentReflectance;
#endif
};
#ifdef CLEARCOAT
#define pbr_inline
#define inline
void clearcoatBlock(
in vec3 vPositionW,
in vec3 geometricNormalW,
in vec3 viewDirectionW,
in vec2 vClearCoatParams,
#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)
in vec4 clearCoatMapRoughnessData,
#endif
in vec3 specularEnvironmentR0,
#ifdef CLEARCOAT_TEXTURE
in vec2 clearCoatMapData,
#endif
#ifdef CLEARCOAT_TINT
in vec4 vClearCoatTintParams,
in float clearCoatColorAtDistance,
in vec4 vClearCoatRefractionParams,
#ifdef CLEARCOAT_TINT_TEXTURE
in vec4 clearCoatTintMapData,
#endif
#endif
#ifdef CLEARCOAT_BUMP
in vec2 vClearCoatBumpInfos,
in vec4 clearCoatBumpMapData,
in vec2 vClearCoatBumpUV,
#if defined(TANGENT) && defined(NORMAL)
in mat3 vTBN,
#else
in vec2 vClearCoatTangentSpaceParams,
#endif
#ifdef OBJECTSPACE_NORMALMAP
in mat4 normalMatrix,
#endif
#endif
#if defined(FORCENORMALFORWARD) && defined(NORMAL)
in vec3 faceNormal,
#endif
#ifdef REFLECTION
in vec3 vReflectionMicrosurfaceInfos,
in vec2 vReflectionInfos,
in vec3 vReflectionColor,
in vec4 vLightingIntensity,
#ifdef REFLECTIONMAP_3D
in samplerCube reflectionSampler,
#else
in sampler2D reflectionSampler,
#endif
#ifndef LODBASEDMICROSFURACE
#ifdef REFLECTIONMAP_3D
in samplerCube reflectionSamplerLow,
in samplerCube reflectionSamplerHigh,
#else
in sampler2D reflectionSamplerLow,
in sampler2D reflectionSamplerHigh,
#endif
#endif
#ifdef REALTIME_FILTERING
in vec2 vReflectionFilteringInfo,
#endif
#endif
#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)
#ifdef RADIANCEOCCLUSION
in float ambientMonochrome,
#endif
#endif
#if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING)
in float frontFacingMultiplier,
#endif
out clearcoatOutParams outParams
)
{

float clearCoatIntensity=vClearCoatParams.x;
float clearCoatRoughness=vClearCoatParams.y;
#ifdef CLEARCOAT_TEXTURE
clearCoatIntensity*=clearCoatMapData.x;
#ifdef CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE
clearCoatRoughness*=clearCoatMapData.y;
#endif
#if DEBUGMODE>0
outParams.clearCoatMapData=clearCoatMapData;
#endif
#endif
#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)
#ifdef CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL
clearCoatRoughness*=clearCoatMapData.y;
#else
clearCoatRoughness*=clearCoatMapRoughnessData.y;
#endif
#endif
outParams.clearCoatIntensity=clearCoatIntensity;
outParams.clearCoatRoughness=clearCoatRoughness;
#ifdef CLEARCOAT_TINT
vec3 clearCoatColor=vClearCoatTintParams.rgb;
float clearCoatThickness=vClearCoatTintParams.a;
#ifdef CLEARCOAT_TINT_TEXTURE
#ifdef CLEARCOAT_TINT_GAMMATEXTURE
clearCoatColor*=toLinearSpace(clearCoatTintMapData.rgb);
#else
clearCoatColor*=clearCoatTintMapData.rgb;
#endif
clearCoatThickness*=clearCoatTintMapData.a;
#if DEBUGMODE>0
outParams.clearCoatTintMapData=clearCoatTintMapData;
#endif
#endif
outParams.clearCoatColor=computeColorAtDistanceInMedia(clearCoatColor,clearCoatColorAtDistance);
outParams.clearCoatThickness=clearCoatThickness;
#endif




#ifdef CLEARCOAT_REMAP_F0
vec3 specularEnvironmentR0Updated=getR0RemappedForClearCoat(specularEnvironmentR0);
#else
vec3 specularEnvironmentR0Updated=specularEnvironmentR0;
#endif
outParams.specularEnvironmentR0=mix(specularEnvironmentR0,specularEnvironmentR0Updated,clearCoatIntensity);

vec3 clearCoatNormalW=geometricNormalW;
#ifdef CLEARCOAT_BUMP
#ifdef NORMALXYSCALE
float clearCoatNormalScale=1.0;
#else
float clearCoatNormalScale=vClearCoatBumpInfos.y;
#endif
#if defined(TANGENT) && defined(NORMAL)
mat3 TBNClearCoat=vTBN;
#else

vec2 TBNClearCoatUV=vClearCoatBumpUV*frontFacingMultiplier;
mat3 TBNClearCoat=cotangent_frame(clearCoatNormalW*clearCoatNormalScale,vPositionW,TBNClearCoatUV,vClearCoatTangentSpaceParams);
#endif
#if DEBUGMODE>0
outParams.TBNClearCoat=TBNClearCoat;
#endif
#ifdef OBJECTSPACE_NORMALMAP
clearCoatNormalW=normalize(clearCoatBumpMapData.xyz*2.0-1.0);
clearCoatNormalW=normalize(mat3(normalMatrix)*clearCoatNormalW);
#else
clearCoatNormalW=perturbNormal(TBNClearCoat,clearCoatBumpMapData.xyz,vClearCoatBumpInfos.y);
#endif
#endif
#if defined(FORCENORMALFORWARD) && defined(NORMAL)
clearCoatNormalW*=sign(dot(clearCoatNormalW,faceNormal));
#endif
#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)
clearCoatNormalW=clearCoatNormalW*frontFacingMultiplier;
#endif
outParams.clearCoatNormalW=clearCoatNormalW;

outParams.clearCoatAARoughnessFactors=getAARoughnessFactors(clearCoatNormalW.xyz);

float clearCoatNdotVUnclamped=dot(clearCoatNormalW,viewDirectionW);

float clearCoatNdotV=absEps(clearCoatNdotVUnclamped);
#if DEBUGMODE>0
outParams.clearCoatNdotV=clearCoatNdotV;
#endif
#ifdef CLEARCOAT_TINT

vec3 clearCoatVRefract=-refract(vPositionW,clearCoatNormalW,vClearCoatRefractionParams.y);

outParams.clearCoatNdotVRefract=absEps(dot(clearCoatNormalW,clearCoatVRefract));
#endif
#if defined(ENVIRONMENTBRDF) && (!defined(REFLECTIONMAP_SKYBOX) || defined(MS_BRDF_ENERGY_CONSERVATION))

vec3 environmentClearCoatBrdf=getBRDFLookup(clearCoatNdotV,clearCoatRoughness);
#endif

#if defined(REFLECTION)
float clearCoatAlphaG=convertRoughnessToAverageSlope(clearCoatRoughness);
#ifdef SPECULARAA

clearCoatAlphaG+=outParams.clearCoatAARoughnessFactors.y;
#endif
vec4 environmentClearCoatRadiance=vec4(0.,0.,0.,0.);
vec3 clearCoatReflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),clearCoatNormalW);
#ifdef REFLECTIONMAP_OPPOSITEZ
clearCoatReflectionVector.z*=-1.0;
#endif

#ifdef REFLECTIONMAP_3D
vec3 clearCoatReflectionCoords=clearCoatReflectionVector;
#else
vec2 clearCoatReflectionCoords=clearCoatReflectionVector.xy;
#ifdef REFLECTIONMAP_PROJECTION
clearCoatReflectionCoords/=clearCoatReflectionVector.z;
#endif
clearCoatReflectionCoords.y=1.0-clearCoatReflectionCoords.y;
#endif
sampleReflectionTexture(
clearCoatAlphaG,
vReflectionMicrosurfaceInfos,
vReflectionInfos,
vReflectionColor,
#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
clearCoatNdotVUnclamped,
#endif
#ifdef LINEARSPECULARREFLECTION
clearCoatRoughness,
#endif
reflectionSampler,
clearCoatReflectionCoords,
#ifndef LODBASEDMICROSFURACE
reflectionSamplerLow,
reflectionSamplerHigh,
#endif
#ifdef REALTIME_FILTERING
vReflectionFilteringInfo,
#endif
environmentClearCoatRadiance
);
#if DEBUGMODE>0
outParams.environmentClearCoatRadiance=environmentClearCoatRadiance;
#endif

#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)
vec3 clearCoatEnvironmentReflectance=getReflectanceFromBRDFLookup(vec3(vClearCoatRefractionParams.x),environmentClearCoatBrdf);
#ifdef RADIANCEOCCLUSION
float clearCoatSeo=environmentRadianceOcclusion(ambientMonochrome,clearCoatNdotVUnclamped);
clearCoatEnvironmentReflectance*=clearCoatSeo;
#endif
#ifdef HORIZONOCCLUSION
#ifdef BUMP
#ifdef REFLECTIONMAP_3D
float clearCoatEho=environmentHorizonOcclusion(-viewDirectionW,clearCoatNormalW,geometricNormalW);
clearCoatEnvironmentReflectance*=clearCoatEho;
#endif
#endif
#endif
#else

vec3 clearCoatEnvironmentReflectance=getReflectanceFromAnalyticalBRDFLookup_Jones(clearCoatNdotV,vec3(1.),vec3(1.),sqrt(1.-clearCoatRoughness));
#endif
clearCoatEnvironmentReflectance*=clearCoatIntensity;
#if DEBUGMODE>0
outParams.clearCoatEnvironmentReflectance=clearCoatEnvironmentReflectance;
#endif
outParams.finalClearCoatRadianceScaled=
environmentClearCoatRadiance.rgb *
clearCoatEnvironmentReflectance *
vLightingIntensity.z;
#endif
#if defined(CLEARCOAT_TINT)

outParams.absorption=computeClearCoatAbsorption(outParams.clearCoatNdotVRefract,outParams.clearCoatNdotVRefract,outParams.clearCoatColor,clearCoatThickness,clearCoatIntensity);
#endif

float fresnelIBLClearCoat=fresnelSchlickGGX(clearCoatNdotV,vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);
fresnelIBLClearCoat*=clearCoatIntensity;
outParams.conservationFactor=(1.-fresnelIBLClearCoat);
#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)
outParams.energyConservationFactorClearCoat=getEnergyConservationFactor(outParams.specularEnvironmentR0,environmentClearCoatBrdf);
#endif
}
#endif
`;
ShaderStore.IncludesShadersStore[name$1a] = shader$1a;
var name$19 = "pbrBlockSubSurface"
  , shader$19 = `struct subSurfaceOutParams
{
vec3 specularEnvironmentReflectance;
#ifdef SS_REFRACTION
vec3 finalRefraction;
vec3 surfaceAlbedo;
#ifdef SS_LINKREFRACTIONTOTRANSPARENCY
float alpha;
#endif
#ifdef REFLECTION
float refractionFactorForIrradiance;
#endif
#endif
#ifdef SS_TRANSLUCENCY
vec3 transmittance;
float translucencyIntensity;
#ifdef REFLECTION
vec3 refractionIrradiance;
#endif
#endif
#if DEBUGMODE>0
vec4 thicknessMap;
vec4 environmentRefraction;
vec3 refractionTransmittance;
#endif
};
#ifdef SUBSURFACE
#define pbr_inline
#define inline
void subSurfaceBlock(
in vec3 vSubSurfaceIntensity,
in vec2 vThicknessParam,
in vec4 vTintColor,
in vec3 normalW,
in vec3 specularEnvironmentReflectance,
#ifdef SS_THICKNESSANDMASK_TEXTURE
in vec4 thicknessMap,
#endif
#ifdef SS_REFRACTIONINTENSITY_TEXTURE
in vec4 refractionIntensityMap,
#endif
#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE
in vec4 translucencyIntensityMap,
#endif
#ifdef REFLECTION
#ifdef SS_TRANSLUCENCY
in mat4 reflectionMatrix,
#ifdef USESPHERICALFROMREFLECTIONMAP
#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)
in vec3 irradianceVector_,
#endif
#if defined(REALTIME_FILTERING)
in samplerCube reflectionSampler,
in vec2 vReflectionFilteringInfo,
#endif
#endif
#ifdef USEIRRADIANCEMAP
#ifdef REFLECTIONMAP_3D
in samplerCube irradianceSampler,
#else
in sampler2D irradianceSampler,
#endif
#endif
#endif
#endif
#if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY)
in vec3 surfaceAlbedo,
#endif
#ifdef SS_REFRACTION
in vec3 vPositionW,
in vec3 viewDirectionW,
in mat4 view,
in vec4 vRefractionInfos,
in mat4 refractionMatrix,
in vec4 vRefractionMicrosurfaceInfos,
in vec4 vLightingIntensity,
#ifdef SS_LINKREFRACTIONTOTRANSPARENCY
in float alpha,
#endif
#ifdef SS_LODINREFRACTIONALPHA
in float NdotVUnclamped,
#endif
#ifdef SS_LINEARSPECULARREFRACTION
in float roughness,
#endif
in float alphaG,
#ifdef SS_REFRACTIONMAP_3D
in samplerCube refractionSampler,
#ifndef LODBASEDMICROSFURACE
in samplerCube refractionSamplerLow,
in samplerCube refractionSamplerHigh,
#endif
#else
in sampler2D refractionSampler,
#ifndef LODBASEDMICROSFURACE
in sampler2D refractionSamplerLow,
in sampler2D refractionSamplerHigh,
#endif
#endif
#ifdef ANISOTROPIC
in anisotropicOutParams anisotropicOut,
#endif
#ifdef REALTIME_FILTERING
in vec2 vRefractionFilteringInfo,
#endif
#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC
in vec3 refractionPosition,
in vec3 refractionSize,
#endif
#endif
#ifdef SS_TRANSLUCENCY
in vec3 vDiffusionDistance,
#endif
out subSurfaceOutParams outParams
)
{
outParams.specularEnvironmentReflectance=specularEnvironmentReflectance;



#ifdef SS_REFRACTION
float refractionIntensity=vSubSurfaceIntensity.x;
#ifdef SS_LINKREFRACTIONTOTRANSPARENCY
refractionIntensity*=(1.0-alpha);

outParams.alpha=1.0;
#endif
#endif
#ifdef SS_TRANSLUCENCY
float translucencyIntensity=vSubSurfaceIntensity.y;
#endif
#ifdef SS_THICKNESSANDMASK_TEXTURE
#if defined(SS_USE_GLTF_TEXTURES)
float thickness=thicknessMap.g*vThicknessParam.y+vThicknessParam.x;
#else
float thickness=thicknessMap.r*vThicknessParam.y+vThicknessParam.x;
#endif
#if DEBUGMODE>0
outParams.thicknessMap=thicknessMap;
#endif
#ifdef SS_MASK_FROM_THICKNESS_TEXTURE
#if defined(SS_REFRACTION) && defined(SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE)
#if defined(SS_USE_GLTF_TEXTURES)
refractionIntensity*=thicknessMap.r;
#else
refractionIntensity*=thicknessMap.g;
#endif
#endif
#if defined(SS_TRANSLUCENCY) && defined(SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE)
translucencyIntensity*=thicknessMap.b;
#endif
#endif
#else
float thickness=vThicknessParam.y;
#endif
#ifdef SS_REFRACTIONINTENSITY_TEXTURE
#ifdef SS_USE_GLTF_TEXTURES
refractionIntensity*=refractionIntensityMap.r;
#else
refractionIntensity*=refractionIntensityMap.g;
#endif
#endif
#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE
translucencyIntensity*=translucencyIntensityMap.b;
#endif



#ifdef SS_TRANSLUCENCY
thickness=maxEps(thickness);
vec3 transmittance=transmittanceBRDF_Burley(vTintColor.rgb,vDiffusionDistance,thickness);
transmittance*=translucencyIntensity;
outParams.transmittance=transmittance;
outParams.translucencyIntensity=translucencyIntensity;
#endif



#ifdef SS_REFRACTION
vec4 environmentRefraction=vec4(0.,0.,0.,0.);
#ifdef ANISOTROPIC
vec3 refractionVector=refract(-viewDirectionW,anisotropicOut.anisotropicNormal,vRefractionInfos.y);
#else
vec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);
#endif
#ifdef SS_REFRACTIONMAP_OPPOSITEZ
refractionVector.z*=-1.0;
#endif

#ifdef SS_REFRACTIONMAP_3D
#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC
refractionVector=parallaxCorrectNormal(vPositionW,refractionVector,refractionSize,refractionPosition);
#endif
refractionVector.y=refractionVector.y*vRefractionInfos.w;
vec3 refractionCoords=refractionVector;
refractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));
#else
#ifdef SS_USE_THICKNESS_AS_DEPTH
vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*thickness,1.0)));
#else
vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));
#endif
vec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;
refractionCoords.y=1.0-refractionCoords.y;
#endif


#ifdef SS_HAS_THICKNESS
float ior=vRefractionInfos.y;
#else
float ior=vRefractionMicrosurfaceInfos.w;
#endif


#ifdef SS_LODINREFRACTIONALPHA
float refractionAlphaG=alphaG;
refractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));
float refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG,NdotVUnclamped);
#elif defined(SS_LINEARSPECULARREFRACTION)
float refractionRoughness=alphaG;
refractionRoughness=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));
float refractionLOD=getLinearLodFromRoughness(vRefractionMicrosurfaceInfos.x,refractionRoughness);
#else
float refractionAlphaG=alphaG;
refractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));
float refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG);
#endif
#ifdef LODBASEDMICROSFURACE

refractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;
#ifdef SS_LODINREFRACTIONALPHA









float automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);
float requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);
#else
float requestedRefractionLOD=refractionLOD;
#endif
#ifdef REALTIME_FILTERING
environmentRefraction=vec4(radiance(alphaG,refractionSampler,refractionCoords,vRefractionFilteringInfo),1.0);
#else
environmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);
#endif
#else
float lodRefractionNormalized=saturate(refractionLOD/log2(vRefractionMicrosurfaceInfos.x));
float lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;
vec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);
if (lodRefractionNormalizedDoubled<1.0){
environmentRefraction=mix(
sampleRefraction(refractionSamplerHigh,refractionCoords),
environmentRefractionMid,
lodRefractionNormalizedDoubled
);
} else {
environmentRefraction=mix(
environmentRefractionMid,
sampleRefraction(refractionSamplerLow,refractionCoords),
lodRefractionNormalizedDoubled-1.0
);
}
#endif
#ifdef SS_RGBDREFRACTION
environmentRefraction.rgb=fromRGBD(environmentRefraction);
#endif
#ifdef SS_GAMMAREFRACTION
environmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);
#endif

environmentRefraction.rgb*=vRefractionInfos.x;
#endif



#ifdef SS_REFRACTION
vec3 refractionTransmittance=vec3(refractionIntensity);
#ifdef SS_THICKNESSANDMASK_TEXTURE
vec3 volumeAlbedo=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);





refractionTransmittance*=cocaLambert(volumeAlbedo,thickness);
#elif defined(SS_LINKREFRACTIONTOTRANSPARENCY)

float maxChannel=max(max(surfaceAlbedo.r,surfaceAlbedo.g),surfaceAlbedo.b);
vec3 volumeAlbedo=saturate(maxChannel*surfaceAlbedo);

environmentRefraction.rgb*=volumeAlbedo;
#else

vec3 volumeAlbedo=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);
refractionTransmittance*=cocaLambert(volumeAlbedo,vThicknessParam.y);
#endif
#ifdef SS_ALBEDOFORREFRACTIONTINT

environmentRefraction.rgb*=surfaceAlbedo.rgb;
#endif

outParams.surfaceAlbedo=surfaceAlbedo*(1.-refractionIntensity);
#ifdef REFLECTION

outParams.refractionFactorForIrradiance=(1.-refractionIntensity);

#endif
#ifdef UNUSED_MULTIPLEBOUNCES





vec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);
outParams.specularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,refractionIntensity);
#endif

refractionTransmittance*=1.0-outParams.specularEnvironmentReflectance;
#if DEBUGMODE>0
outParams.refractionTransmittance=refractionTransmittance;
#endif
outParams.finalRefraction=environmentRefraction.rgb*refractionTransmittance*vLightingIntensity.z;
#if DEBUGMODE>0
outParams.environmentRefraction=environmentRefraction;
#endif
#endif



#if defined(REFLECTION) && defined(SS_TRANSLUCENCY)
#if defined(NORMAL) && defined(USESPHERICALINVERTEX) || !defined(USESPHERICALFROMREFLECTIONMAP)
vec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;
#ifdef REFLECTIONMAP_OPPOSITEZ
irradianceVector.z*=-1.0;
#endif
#ifdef INVERTCUBICMAP
irradianceVector.y*=-1.0;
#endif
#else
vec3 irradianceVector=irradianceVector_;
#endif
#if defined(USESPHERICALFROMREFLECTIONMAP)
#if defined(REALTIME_FILTERING)
vec3 refractionIrradiance=irradiance(reflectionSampler,-irradianceVector,vReflectionFilteringInfo);
#else
vec3 refractionIrradiance=computeEnvironmentIrradiance(-irradianceVector);
#endif
#elif defined(USEIRRADIANCEMAP)
#ifdef REFLECTIONMAP_3D
vec3 irradianceCoords=irradianceVector;
#else
vec2 irradianceCoords=irradianceVector.xy;
#ifdef REFLECTIONMAP_PROJECTION
irradianceCoords/=irradianceVector.z;
#endif
irradianceCoords.y=1.0-irradianceCoords.y;
#endif
vec4 refractionIrradiance=sampleReflection(irradianceSampler,-irradianceCoords);
#ifdef RGBDREFLECTION
refractionIrradiance.rgb=fromRGBD(refractionIrradiance);
#endif
#ifdef GAMMAREFLECTION
refractionIrradiance.rgb=toLinearSpace(refractionIrradiance.rgb);
#endif
#else
vec4 refractionIrradiance=vec4(0.);
#endif
refractionIrradiance.rgb*=transmittance;
#ifdef SS_ALBEDOFORTRANSLUCENCYTINT

refractionIrradiance.rgb*=surfaceAlbedo.rgb;
#endif
outParams.refractionIrradiance=refractionIrradiance.rgb;
#endif
}
#endif
`;
ShaderStore.IncludesShadersStore[name$19] = shader$19;
var name$18 = "pbrBlockNormalGeometric"
  , shader$18 = `vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);
#ifdef NORMAL
vec3 normalW=normalize(vNormalW);
#else
vec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;
#endif
vec3 geometricNormalW=normalW;
#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)
geometricNormalW=gl_FrontFacing ? geometricNormalW : -geometricNormalW;
#endif
`;
ShaderStore.IncludesShadersStore[name$18] = shader$18;
var name$17 = "pbrBlockNormalFinal"
  , shader$17 = `#if defined(FORCENORMALFORWARD) && defined(NORMAL)
vec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;
#if defined(TWOSIDEDLIGHTING)
faceNormal=gl_FrontFacing ? faceNormal : -faceNormal;
#endif
normalW*=sign(dot(normalW,faceNormal));
#endif
#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)
normalW=gl_FrontFacing ? normalW : -normalW;
#endif
`;
ShaderStore.IncludesShadersStore[name$17] = shader$17;
var name$16 = "pbrBlockLightmapInit"
  , shader$16 = `#ifdef LIGHTMAP
vec4 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset);
#ifdef RGBDLIGHTMAP
lightmapColor.rgb=fromRGBD(lightmapColor);
#endif
#ifdef GAMMALIGHTMAP
lightmapColor.rgb=toLinearSpace(lightmapColor.rgb);
#endif
lightmapColor.rgb*=vLightmapInfos.y;
#endif
`;
ShaderStore.IncludesShadersStore[name$16] = shader$16;
var name$15 = "pbrBlockGeometryInfo"
  , shader$15 = `float NdotVUnclamped=dot(normalW,viewDirectionW);

float NdotV=absEps(NdotVUnclamped);
float alphaG=convertRoughnessToAverageSlope(roughness);
vec2 AARoughnessFactors=getAARoughnessFactors(normalW.xyz);
#ifdef SPECULARAA

alphaG+=AARoughnessFactors.y;
#endif
#if defined(ENVIRONMENTBRDF)

vec3 environmentBrdf=getBRDFLookup(NdotV,roughness);
#endif
#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)
#ifdef RADIANCEOCCLUSION
#ifdef AMBIENTINGRAYSCALE
float ambientMonochrome=aoOut.ambientOcclusionColor.r;
#else
float ambientMonochrome=getLuminance(aoOut.ambientOcclusionColor);
#endif
float seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);
#endif
#ifdef HORIZONOCCLUSION
#ifdef BUMP
#ifdef REFLECTIONMAP_3D
float eho=environmentHorizonOcclusion(-viewDirectionW,normalW,geometricNormalW);
#endif
#endif
#endif
#endif
`;
ShaderStore.IncludesShadersStore[name$15] = shader$15;
var name$14 = "pbrBlockReflectance0"
  , shader$14 = `float reflectance=max(max(reflectivityOut.surfaceReflectivityColor.r,reflectivityOut.surfaceReflectivityColor.g),reflectivityOut.surfaceReflectivityColor.b);
vec3 specularEnvironmentR0=reflectivityOut.surfaceReflectivityColor.rgb;
#ifdef METALLICWORKFLOW
vec3 specularEnvironmentR90=vec3(metallicReflectanceFactors.a);
#else
vec3 specularEnvironmentR90=vec3(1.0,1.0,1.0);
#endif

#ifdef ALPHAFRESNEL
float reflectance90=fresnelGrazingReflectance(reflectance);
specularEnvironmentR90=specularEnvironmentR90*reflectance90;
#endif
`;
ShaderStore.IncludesShadersStore[name$14] = shader$14;
var name$13 = "pbrBlockReflectance"
  , shader$13 = `#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)
vec3 specularEnvironmentReflectance=getReflectanceFromBRDFLookup(clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,environmentBrdf);
#ifdef RADIANCEOCCLUSION
specularEnvironmentReflectance*=seo;
#endif
#ifdef HORIZONOCCLUSION
#ifdef BUMP
#ifdef REFLECTIONMAP_3D
specularEnvironmentReflectance*=eho;
#endif
#endif
#endif
#else

vec3 specularEnvironmentReflectance=getReflectanceFromAnalyticalBRDFLookup_Jones(NdotV,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));
#endif
#ifdef CLEARCOAT
specularEnvironmentReflectance*=clearcoatOut.conservationFactor;
#if defined(CLEARCOAT_TINT)
specularEnvironmentReflectance*=clearcoatOut.absorption;
#endif
#endif
`;
ShaderStore.IncludesShadersStore[name$13] = shader$13;
var name$12 = "pbrBlockDirectLighting"
  , shader$12 = `vec3 diffuseBase=vec3(0.,0.,0.);
#ifdef SPECULARTERM
vec3 specularBase=vec3(0.,0.,0.);
#endif
#ifdef CLEARCOAT
vec3 clearCoatBase=vec3(0.,0.,0.);
#endif
#ifdef SHEEN
vec3 sheenBase=vec3(0.,0.,0.);
#endif

preLightingInfo preInfo;
lightingInfo info;
float shadow=1.;
#if defined(CLEARCOAT) && defined(CLEARCOAT_TINT)
vec3 absorption=vec3(0.);
#endif
`;
ShaderStore.IncludesShadersStore[name$12] = shader$12;
var name$11 = "pbrBlockFinalLitComponents"
  , shader$11 = `



#if defined(ENVIRONMENTBRDF)
#ifdef MS_BRDF_ENERGY_CONSERVATION
vec3 energyConservationFactor=getEnergyConservationFactor(clearcoatOut.specularEnvironmentR0,environmentBrdf);
#endif
#endif
#ifndef METALLICWORKFLOW
#ifdef SPECULAR_GLOSSINESS_ENERGY_CONSERVATION
surfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;
#endif
#endif
#if defined(SHEEN) && defined(SHEEN_ALBEDOSCALING) && defined(ENVIRONMENTBRDF)
surfaceAlbedo.rgb=sheenOut.sheenAlbedoScaling*surfaceAlbedo.rgb;
#endif

#ifdef REFLECTION
vec3 finalIrradiance=reflectionOut.environmentIrradiance;
#if defined(CLEARCOAT)
finalIrradiance*=clearcoatOut.conservationFactor;
#if defined(CLEARCOAT_TINT)
finalIrradiance*=clearcoatOut.absorption;
#endif
#endif
#if defined(SS_REFRACTION)
finalIrradiance*=subSurfaceOut.refractionFactorForIrradiance;
#endif
#if defined(SS_TRANSLUCENCY)
finalIrradiance*=(1.0-subSurfaceOut.translucencyIntensity);
finalIrradiance+=subSurfaceOut.refractionIrradiance;
#endif
finalIrradiance*=surfaceAlbedo.rgb;
finalIrradiance*=vLightingIntensity.z;
finalIrradiance*=aoOut.ambientOcclusionColor;
#endif

#ifdef SPECULARTERM
vec3 finalSpecular=specularBase;
finalSpecular=max(finalSpecular,0.0);
vec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;
#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)
finalSpecularScaled*=energyConservationFactor;
#endif
#if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)
finalSpecularScaled*=sheenOut.sheenAlbedoScaling;
#endif
#endif

#ifdef REFLECTION
vec3 finalRadiance=reflectionOut.environmentRadiance.rgb;
finalRadiance*=subSurfaceOut.specularEnvironmentReflectance;
vec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;
#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)
finalRadianceScaled*=energyConservationFactor;
#endif
#if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)
finalRadianceScaled*=sheenOut.sheenAlbedoScaling;
#endif
#endif

#ifdef SHEEN
vec3 finalSheen=sheenBase*sheenOut.sheenColor;
finalSheen=max(finalSheen,0.0);
vec3 finalSheenScaled=finalSheen*vLightingIntensity.x*vLightingIntensity.w;
#if defined(CLEARCOAT) && defined(REFLECTION) && defined(ENVIRONMENTBRDF)
sheenOut.finalSheenRadianceScaled*=clearcoatOut.conservationFactor;
#if defined(CLEARCOAT_TINT)
sheenOut.finalSheenRadianceScaled*=clearcoatOut.absorption;
#endif
#endif
#endif

#ifdef CLEARCOAT
vec3 finalClearCoat=clearCoatBase;
finalClearCoat=max(finalClearCoat,0.0);
vec3 finalClearCoatScaled=finalClearCoat*vLightingIntensity.x*vLightingIntensity.w;
#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)
finalClearCoatScaled*=clearcoatOut.energyConservationFactorClearCoat;
#endif
#ifdef SS_REFRACTION
subSurfaceOut.finalRefraction*=clearcoatOut.conservationFactor;
#ifdef CLEARCOAT_TINT
subSurfaceOut.finalRefraction*=clearcoatOut.absorption;
#endif
#endif
#endif

#ifdef ALPHABLEND
float luminanceOverAlpha=0.0;
#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)
luminanceOverAlpha+=getLuminance(finalRadianceScaled);
#if defined(CLEARCOAT)
luminanceOverAlpha+=getLuminance(clearcoatOut.finalClearCoatRadianceScaled);
#endif
#endif
#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)
luminanceOverAlpha+=getLuminance(finalSpecularScaled);
#endif
#if defined(CLEARCOAT) && defined(CLEARCOATOVERALPHA)
luminanceOverAlpha+=getLuminance(finalClearCoatScaled);
#endif
#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA) || defined(CLEARCOATOVERALPHA)
alpha=saturate(alpha+luminanceOverAlpha*luminanceOverAlpha);
#endif
#endif
`;
ShaderStore.IncludesShadersStore[name$11] = shader$11;
var name$10 = "pbrBlockFinalUnlitComponents"
  , shader$10 = `
vec3 finalDiffuse=diffuseBase;
finalDiffuse*=surfaceAlbedo.rgb;
finalDiffuse=max(finalDiffuse,0.0);
finalDiffuse*=vLightingIntensity.x;

vec3 finalAmbient=vAmbientColor;
finalAmbient*=surfaceAlbedo.rgb;

vec3 finalEmissive=vEmissiveColor;
#ifdef EMISSIVE
vec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;
#ifdef GAMMAEMISSIVE
finalEmissive*=toLinearSpace(emissiveColorTex.rgb);
#else
finalEmissive*=emissiveColorTex.rgb;
#endif
finalEmissive*=vEmissiveInfos.y;
#endif
finalEmissive*=vLightingIntensity.y;

#ifdef AMBIENT
vec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),aoOut.ambientOcclusionColor,vAmbientInfos.w);
#else
vec3 ambientOcclusionForDirectDiffuse=aoOut.ambientOcclusionColor;
#endif
finalAmbient*=aoOut.ambientOcclusionColor;
finalDiffuse*=ambientOcclusionForDirectDiffuse;
`;
ShaderStore.IncludesShadersStore[name$10] = shader$10;
var name$$ = "pbrBlockFinalColorComposition"
  , shader$$ = `vec4 finalColor=vec4(
finalAmbient +
finalDiffuse +
#ifndef UNLIT
#ifdef REFLECTION
finalIrradiance +
#endif
#ifdef SPECULARTERM
finalSpecularScaled +
#endif
#ifdef SHEEN
finalSheenScaled +
#endif
#ifdef CLEARCOAT
finalClearCoatScaled +
#endif
#ifdef REFLECTION
finalRadianceScaled +
#if defined(SHEEN) && defined(ENVIRONMENTBRDF)
sheenOut.finalSheenRadianceScaled +
#endif
#ifdef CLEARCOAT
clearcoatOut.finalClearCoatRadianceScaled +
#endif
#endif
#ifdef SS_REFRACTION
subSurfaceOut.finalRefraction +
#endif
#endif
finalEmissive,
alpha);

#ifdef LIGHTMAP
#ifndef LIGHTMAPEXCLUDED
#ifdef USELIGHTMAPASSHADOWMAP
finalColor.rgb*=lightmapColor.rgb;
#else
finalColor.rgb+=lightmapColor.rgb;
#endif
#endif
#endif
#define CUSTOM_FRAGMENT_BEFORE_FOG

finalColor=max(finalColor,0.0);
`;
ShaderStore.IncludesShadersStore[name$$] = shader$$;
var name$_ = "pbrBlockImageProcessing"
  , shader$_ = `#if defined(IMAGEPROCESSINGPOSTPROCESS) || defined(SS_SCATTERING)




#if !defined(SKIPFINALCOLORCLAMP)
finalColor.rgb=clamp(finalColor.rgb,0.,30.0);
#endif
#else

finalColor=applyImageProcessing(finalColor);
#endif
finalColor.a*=visibility;
#ifdef PREMULTIPLYALPHA

finalColor.rgb*=finalColor.a;
#endif
`;
ShaderStore.IncludesShadersStore[name$_] = shader$_;
var name$Z = "pbrDebug"
  , shader$Z = `#if DEBUGMODE>0
if (vClipSpacePosition.x/vClipSpacePosition.w>=vDebugMode.x) {

#if DEBUGMODE == 1
gl_FragColor.rgb=vPositionW.rgb;
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE == 2 && defined(NORMAL)
gl_FragColor.rgb=vNormalW.rgb;
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE == 3 && defined(BUMP) || DEBUGMODE == 3 && defined(PARALLAX) || DEBUGMODE == 3 && defined(ANISOTROPIC)

gl_FragColor.rgb=TBN[0];
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE == 4 && defined(BUMP) || DEBUGMODE == 4 && defined(PARALLAX) || DEBUGMODE == 4 && defined(ANISOTROPIC)

gl_FragColor.rgb=TBN[1];
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE == 5

gl_FragColor.rgb=normalW;
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE == 6 && defined(MAINUV1)
gl_FragColor.rgb=vec3(vMainUV1,0.0);
#elif DEBUGMODE == 7 && defined(MAINUV2)
gl_FragColor.rgb=vec3(vMainUV2,0.0);
#elif DEBUGMODE == 8 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP)

gl_FragColor.rgb=clearcoatOut.TBNClearCoat[0];
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE == 9 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP)

gl_FragColor.rgb=clearcoatOut.TBNClearCoat[1];
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE == 10 && defined(CLEARCOAT)

gl_FragColor.rgb=clearcoatOut.clearCoatNormalW;
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE == 11 && defined(ANISOTROPIC)
gl_FragColor.rgb=anisotropicOut.anisotropicNormal;
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE == 12 && defined(ANISOTROPIC)
gl_FragColor.rgb=anisotropicOut.anisotropicTangent;
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE == 13 && defined(ANISOTROPIC)
gl_FragColor.rgb=anisotropicOut.anisotropicBitangent;
#define DEBUGMODE_NORMALIZE

#elif DEBUGMODE == 20 && defined(ALBEDO)
gl_FragColor.rgb=albedoTexture.rgb;
#elif DEBUGMODE == 21 && defined(AMBIENT)
gl_FragColor.rgb=aoOut.ambientOcclusionColorMap.rgb;
#elif DEBUGMODE == 22 && defined(OPACITY)
gl_FragColor.rgb=opacityMap.rgb;
#elif DEBUGMODE == 23 && defined(EMISSIVE)
gl_FragColor.rgb=emissiveColorTex.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE == 24 && defined(LIGHTMAP)
gl_FragColor.rgb=lightmapColor.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE == 25 && defined(REFLECTIVITY) && defined(METALLICWORKFLOW)
gl_FragColor.rgb=reflectivityOut.surfaceMetallicColorMap.rgb;
#elif DEBUGMODE == 26 && defined(REFLECTIVITY) && !defined(METALLICWORKFLOW)
gl_FragColor.rgb=reflectivityOut.surfaceReflectivityColorMap.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE == 27 && defined(CLEARCOAT) && defined(CLEARCOAT_TEXTURE)
gl_FragColor.rgb=vec3(clearcoatOut.clearCoatMapData.rg,0.0);
#elif DEBUGMODE == 28 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE)
gl_FragColor.rgb=clearcoatOut.clearCoatTintMapData.rgb;
#elif DEBUGMODE == 29 && defined(SHEEN) && defined(SHEEN_TEXTURE)
gl_FragColor.rgb=sheenOut.sheenMapData.rgb;
#elif DEBUGMODE == 30 && defined(ANISOTROPIC) && defined(ANISOTROPIC_TEXTURE)
gl_FragColor.rgb=anisotropicOut.anisotropyMapData.rgb;
#elif DEBUGMODE == 31 && defined(SUBSURFACE) && defined(SS_THICKNESSANDMASK_TEXTURE)
gl_FragColor.rgb=subSurfaceOut.thicknessMap.rgb;

#elif DEBUGMODE == 40 && defined(SS_REFRACTION)

gl_FragColor.rgb=subSurfaceOut.environmentRefraction.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE == 41 && defined(REFLECTION)
gl_FragColor.rgb=reflectionOut.environmentRadiance.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE == 42 && defined(CLEARCOAT) && defined(REFLECTION)
gl_FragColor.rgb=clearcoatOut.environmentClearCoatRadiance.rgb;
#define DEBUGMODE_GAMMA

#elif DEBUGMODE == 50
gl_FragColor.rgb=diffuseBase.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE == 51 && defined(SPECULARTERM)
gl_FragColor.rgb=specularBase.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE == 52 && defined(CLEARCOAT)
gl_FragColor.rgb=clearCoatBase.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE == 53 && defined(SHEEN)
gl_FragColor.rgb=sheenBase.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE == 54 && defined(REFLECTION)
gl_FragColor.rgb=reflectionOut.environmentIrradiance.rgb;
#define DEBUGMODE_GAMMA

#elif DEBUGMODE == 60
gl_FragColor.rgb=surfaceAlbedo.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE == 61
gl_FragColor.rgb=clearcoatOut.specularEnvironmentR0;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE == 62 && defined(METALLICWORKFLOW)
gl_FragColor.rgb=vec3(reflectivityOut.metallicRoughness.r);
#elif DEBUGMODE == 71 && defined(METALLICWORKFLOW)
gl_FragColor.rgb=reflectivityOut.metallicF0;
#elif DEBUGMODE == 63
gl_FragColor.rgb=vec3(roughness);
#elif DEBUGMODE == 64
gl_FragColor.rgb=vec3(alphaG);
#elif DEBUGMODE == 65
gl_FragColor.rgb=vec3(NdotV);
#elif DEBUGMODE == 66 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT)
gl_FragColor.rgb=clearcoatOut.clearCoatColor.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE == 67 && defined(CLEARCOAT)
gl_FragColor.rgb=vec3(clearcoatOut.clearCoatRoughness);
#elif DEBUGMODE == 68 && defined(CLEARCOAT)
gl_FragColor.rgb=vec3(clearcoatOut.clearCoatNdotV);
#elif DEBUGMODE == 69 && defined(SUBSURFACE) && defined(SS_TRANSLUCENCY)
gl_FragColor.rgb=subSurfaceOut.transmittance;
#elif DEBUGMODE == 70 && defined(SUBSURFACE) && defined(SS_REFRACTION)
gl_FragColor.rgb=subSurfaceOut.refractionTransmittance;

#elif DEBUGMODE == 80 && defined(RADIANCEOCCLUSION)
gl_FragColor.rgb=vec3(seo);
#elif DEBUGMODE == 81 && defined(HORIZONOCCLUSION)
gl_FragColor.rgb=vec3(eho);
#elif DEBUGMODE == 82 && defined(MS_BRDF_ENERGY_CONSERVATION)
gl_FragColor.rgb=vec3(energyConservationFactor);
#elif DEBUGMODE == 83 && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)
gl_FragColor.rgb=specularEnvironmentReflectance;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE == 84 && defined(CLEARCOAT) && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)
gl_FragColor.rgb=clearcoatOut.clearCoatEnvironmentReflectance;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE == 85 && defined(SHEEN) && defined(REFLECTION)
gl_FragColor.rgb=sheenOut.sheenEnvironmentReflectance;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE == 86 && defined(ALPHABLEND)
gl_FragColor.rgb=vec3(luminanceOverAlpha);
#elif DEBUGMODE == 87
gl_FragColor.rgb=vec3(alpha);
#endif
gl_FragColor.rgb*=vDebugMode.y;
#ifdef DEBUGMODE_NORMALIZE
gl_FragColor.rgb=normalize(gl_FragColor.rgb)*0.5+0.5;
#endif
#ifdef DEBUGMODE_GAMMA
gl_FragColor.rgb=toGammaSpace(gl_FragColor.rgb);
#endif
gl_FragColor.a=1.0;
#ifdef PREPASS
gl_FragData[0]=toLinearSpace(gl_FragColor);
gl_FragData[1]=vec4(0.,0.,0.,0.);
#endif
return;
}
#endif`;
ShaderStore.IncludesShadersStore[name$Z] = shader$Z;
var name$Y = "pbrPixelShader"
  , shader$Y = `#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC)
#extension GL_OES_standard_derivatives : enable
#endif
#ifdef LODBASEDMICROSFURACE
#extension GL_EXT_shader_texture_lod : enable
#endif
#define CUSTOM_FRAGMENT_BEGIN
#ifdef LOGARITHMICDEPTH
#extension GL_EXT_frag_depth : enable
#endif
#include<prePassDeclaration>[SCENE_MRT_COUNT]
precision highp float;
#include<oitDeclaration>

#ifndef FROMLINEARSPACE
#define FROMLINEARSPACE
#endif

#include<__decl__pbrFragment>
#include<pbrFragmentExtraDeclaration>
#include<__decl__lightFragment>[0..maxSimultaneousLights]
#include<pbrFragmentSamplersDeclaration>
#include<imageProcessingDeclaration>
#include<clipPlaneFragmentDeclaration>
#include<logDepthDeclaration>
#include<fogFragmentDeclaration>

#include<helperFunctions>
#include<subSurfaceScatteringFunctions>
#include<importanceSampling>
#include<pbrHelperFunctions>
#include<imageProcessingFunctions>
#include<shadowsFragmentFunctions>
#include<harmonicsFunctions>
#include<pbrDirectLightingSetupFunctions>
#include<pbrDirectLightingFalloffFunctions>
#include<pbrBRDFFunctions>
#include<hdrFilteringFunctions>
#include<pbrDirectLightingFunctions>
#include<pbrIBLFunctions>
#include<bumpFragmentMainFunctions>
#include<bumpFragmentFunctions>
#ifdef REFLECTION
#include<reflectionFunction>
#endif
#define CUSTOM_FRAGMENT_DEFINITIONS
#include<pbrBlockAlbedoOpacity>
#include<pbrBlockReflectivity>
#include<pbrBlockAmbientOcclusion>
#include<pbrBlockAlphaFresnel>
#include<pbrBlockAnisotropic>
#include<pbrBlockReflection>
#include<pbrBlockSheen>
#include<pbrBlockClearcoat>
#include<pbrBlockSubSurface>

void main(void) {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
#include<oitFragment>
#include<clipPlaneFragment>

#include<pbrBlockNormalGeometric>
#include<bumpFragment>
#include<pbrBlockNormalFinal>

albedoOpacityOutParams albedoOpacityOut;
#ifdef ALBEDO
vec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);
#endif
#ifdef OPACITY
vec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);
#endif
albedoOpacityBlock(
vAlbedoColor,
#ifdef ALBEDO
albedoTexture,
vAlbedoInfos,
#endif
#ifdef OPACITY
opacityMap,
vOpacityInfos,
#endif
#ifdef DETAIL
detailColor,
vDetailInfos,
#endif
albedoOpacityOut
);
vec3 surfaceAlbedo=albedoOpacityOut.surfaceAlbedo;
float alpha=albedoOpacityOut.alpha;
#define CUSTOM_FRAGMENT_UPDATE_ALPHA
#include<depthPrePass>
#define CUSTOM_FRAGMENT_BEFORE_LIGHTS

ambientOcclusionOutParams aoOut;
#ifdef AMBIENT
vec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb;
#endif
ambientOcclusionBlock(
#ifdef AMBIENT
ambientOcclusionColorMap,
vAmbientInfos,
#endif
aoOut
);
#include<pbrBlockLightmapInit>
#ifdef UNLIT
vec3 diffuseBase=vec3(1.,1.,1.);
#else

vec3 baseColor=surfaceAlbedo;
reflectivityOutParams reflectivityOut;
#if defined(REFLECTIVITY)
vec4 surfaceMetallicOrReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);
vec4 baseReflectivity=surfaceMetallicOrReflectivityColorMap;
#ifndef METALLICWORKFLOW
#ifdef REFLECTIVITY_GAMMA
surfaceMetallicOrReflectivityColorMap=toLinearSpace(surfaceMetallicOrReflectivityColorMap);
#endif
surfaceMetallicOrReflectivityColorMap.rgb*=vReflectivityInfos.y;
#endif
#endif
#if defined(MICROSURFACEMAP)
vec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;
#endif
#ifdef METALLICWORKFLOW
vec4 metallicReflectanceFactors=vMetallicReflectanceFactors;
#ifdef REFLECTANCE
vec4 reflectanceFactorsMap=texture2D(reflectanceSampler,vReflectanceUV+uvOffset);
#ifdef REFLECTANCE_GAMMA
reflectanceFactorsMap=toLinearSpace(reflectanceFactorsMap);
#endif
metallicReflectanceFactors.rgb*=reflectanceFactorsMap.rgb;
#endif
#ifdef METALLIC_REFLECTANCE
vec4 metallicReflectanceFactorsMap=texture2D(metallicReflectanceSampler,vMetallicReflectanceUV+uvOffset);
#ifdef METALLIC_REFLECTANCE_GAMMA
metallicReflectanceFactorsMap=toLinearSpace(metallicReflectanceFactorsMap);
#endif
#ifndef METALLIC_REFLECTANCE_USE_ALPHA_ONLY
metallicReflectanceFactors.rgb*=metallicReflectanceFactorsMap.rgb;
#endif
metallicReflectanceFactors*=metallicReflectanceFactorsMap.a;
#endif
#endif
reflectivityBlock(
vReflectivityColor,
#ifdef METALLICWORKFLOW
surfaceAlbedo,
metallicReflectanceFactors,
#endif
#ifdef REFLECTIVITY
vReflectivityInfos,
surfaceMetallicOrReflectivityColorMap,
#endif
#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)
aoOut.ambientOcclusionColor,
#endif
#ifdef MICROSURFACEMAP
microSurfaceTexel,
#endif
#ifdef DETAIL
detailColor,
vDetailInfos,
#endif
reflectivityOut
);
float microSurface=reflectivityOut.microSurface;
float roughness=reflectivityOut.roughness;
#ifdef METALLICWORKFLOW
surfaceAlbedo=reflectivityOut.surfaceAlbedo;
#endif
#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)
aoOut.ambientOcclusionColor=reflectivityOut.ambientOcclusionColor;
#endif

#ifdef ALPHAFRESNEL
#if defined(ALPHATEST) || defined(ALPHABLEND)
alphaFresnelOutParams alphaFresnelOut;
alphaFresnelBlock(
normalW,
viewDirectionW,
alpha,
microSurface,
alphaFresnelOut
);
alpha=alphaFresnelOut.alpha;
#endif
#endif

#include<pbrBlockGeometryInfo>

#ifdef ANISOTROPIC
anisotropicOutParams anisotropicOut;
#ifdef ANISOTROPIC_TEXTURE
vec3 anisotropyMapData=texture2D(anisotropySampler,vAnisotropyUV+uvOffset).rgb*vAnisotropyInfos.y;
#endif
anisotropicBlock(
vAnisotropy,
#ifdef ANISOTROPIC_TEXTURE
anisotropyMapData,
#endif
TBN,
normalW,
viewDirectionW,
anisotropicOut
);
#endif

#ifdef REFLECTION
reflectionOutParams reflectionOut;
reflectionBlock(
vPositionW,
normalW,
alphaG,
vReflectionMicrosurfaceInfos,
vReflectionInfos,
vReflectionColor,
#ifdef ANISOTROPIC
anisotropicOut,
#endif
#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
NdotVUnclamped,
#endif
#ifdef LINEARSPECULARREFLECTION
roughness,
#endif
reflectionSampler,
#if defined(NORMAL) && defined(USESPHERICALINVERTEX)
vEnvironmentIrradiance,
#endif
#ifdef USESPHERICALFROMREFLECTIONMAP
#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)
reflectionMatrix,
#endif
#endif
#ifdef USEIRRADIANCEMAP
irradianceSampler,
#endif
#ifndef LODBASEDMICROSFURACE
reflectionSamplerLow,
reflectionSamplerHigh,
#endif
#ifdef REALTIME_FILTERING
vReflectionFilteringInfo,
#endif
reflectionOut
);
#endif

#include<pbrBlockReflectance0>

#ifdef SHEEN
sheenOutParams sheenOut;
#ifdef SHEEN_TEXTURE
vec4 sheenMapData=texture2D(sheenSampler,vSheenUV+uvOffset);
#endif
#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE)
vec4 sheenMapRoughnessData=texture2D(sheenRoughnessSampler,vSheenRoughnessUV+uvOffset)*vSheenInfos.w;
#endif
sheenBlock(
vSheenColor,
#ifdef SHEEN_ROUGHNESS
vSheenRoughness,
#if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE)
sheenMapRoughnessData,
#endif
#endif
roughness,
#ifdef SHEEN_TEXTURE
sheenMapData,
vSheenInfos.y,
#endif
reflectance,
#ifdef SHEEN_LINKWITHALBEDO
baseColor,
surfaceAlbedo,
#endif
#ifdef ENVIRONMENTBRDF
NdotV,
environmentBrdf,
#endif
#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)
AARoughnessFactors,
vReflectionMicrosurfaceInfos,
vReflectionInfos,
vReflectionColor,
vLightingIntensity,
reflectionSampler,
reflectionOut.reflectionCoords,
NdotVUnclamped,
#ifndef LODBASEDMICROSFURACE
reflectionSamplerLow,
reflectionSamplerHigh,
#endif
#ifdef REALTIME_FILTERING
vReflectionFilteringInfo,
#endif
#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION)
seo,
#endif
#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)
eho,
#endif
#endif
sheenOut
);
#ifdef SHEEN_LINKWITHALBEDO
surfaceAlbedo=sheenOut.surfaceAlbedo;
#endif
#endif

clearcoatOutParams clearcoatOut;
#ifdef CLEARCOAT
#ifdef CLEARCOAT_TEXTURE
vec2 clearCoatMapData=texture2D(clearCoatSampler,vClearCoatUV+uvOffset).rg*vClearCoatInfos.y;
#endif
#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)
vec4 clearCoatMapRoughnessData=texture2D(clearCoatRoughnessSampler,vClearCoatRoughnessUV+uvOffset)*vClearCoatInfos.w;
#endif
#if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE)
vec4 clearCoatTintMapData=texture2D(clearCoatTintSampler,vClearCoatTintUV+uvOffset);
#endif
#ifdef CLEARCOAT_BUMP
vec4 clearCoatBumpMapData=texture2D(clearCoatBumpSampler,vClearCoatBumpUV+uvOffset);
#endif
clearcoatBlock(
vPositionW,
geometricNormalW,
viewDirectionW,
vClearCoatParams,
#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)
clearCoatMapRoughnessData,
#endif
specularEnvironmentR0,
#ifdef CLEARCOAT_TEXTURE
clearCoatMapData,
#endif
#ifdef CLEARCOAT_TINT
vClearCoatTintParams,
clearCoatColorAtDistance,
vClearCoatRefractionParams,
#ifdef CLEARCOAT_TINT_TEXTURE
clearCoatTintMapData,
#endif
#endif
#ifdef CLEARCOAT_BUMP
vClearCoatBumpInfos,
clearCoatBumpMapData,
vClearCoatBumpUV,
#if defined(TANGENT) && defined(NORMAL)
vTBN,
#else
vClearCoatTangentSpaceParams,
#endif
#ifdef OBJECTSPACE_NORMALMAP
normalMatrix,
#endif
#endif
#if defined(FORCENORMALFORWARD) && defined(NORMAL)
faceNormal,
#endif
#ifdef REFLECTION
vReflectionMicrosurfaceInfos,
vReflectionInfos,
vReflectionColor,
vLightingIntensity,
reflectionSampler,
#ifndef LODBASEDMICROSFURACE
reflectionSamplerLow,
reflectionSamplerHigh,
#endif
#ifdef REALTIME_FILTERING
vReflectionFilteringInfo,
#endif
#endif
#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)
#ifdef RADIANCEOCCLUSION
ambientMonochrome,
#endif
#endif
#if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING)
(gl_FrontFacing ? 1. : -1.),
#endif
clearcoatOut
);
#else
clearcoatOut.specularEnvironmentR0=specularEnvironmentR0;
#endif

#include<pbrBlockReflectance>

subSurfaceOutParams subSurfaceOut;
#ifdef SUBSURFACE
#ifdef SS_THICKNESSANDMASK_TEXTURE
vec4 thicknessMap=texture2D(thicknessSampler,vThicknessUV+uvOffset);
#endif
#ifdef SS_REFRACTIONINTENSITY_TEXTURE
vec4 refractionIntensityMap=texture2D(refractionIntensitySampler,vRefractionIntensityUV+uvOffset);
#endif
#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE
vec4 translucencyIntensityMap=texture2D(translucencyIntensitySampler,vTranslucencyIntensityUV+uvOffset);
#endif
subSurfaceBlock(
vSubSurfaceIntensity,
vThicknessParam,
vTintColor,
normalW,
specularEnvironmentReflectance,
#ifdef SS_THICKNESSANDMASK_TEXTURE
thicknessMap,
#endif
#ifdef SS_REFRACTIONINTENSITY_TEXTURE
refractionIntensityMap,
#endif
#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE
translucencyIntensityMap,
#endif
#ifdef REFLECTION
#ifdef SS_TRANSLUCENCY
reflectionMatrix,
#ifdef USESPHERICALFROMREFLECTIONMAP
#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)
reflectionOut.irradianceVector,
#endif
#if defined(REALTIME_FILTERING)
reflectionSampler,
vReflectionFilteringInfo,
#endif
#endif
#ifdef USEIRRADIANCEMAP
irradianceSampler,
#endif
#endif
#endif
#if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY)
surfaceAlbedo,
#endif
#ifdef SS_REFRACTION
vPositionW,
viewDirectionW,
view,
vRefractionInfos,
refractionMatrix,
vRefractionMicrosurfaceInfos,
vLightingIntensity,
#ifdef SS_LINKREFRACTIONTOTRANSPARENCY
alpha,
#endif
#ifdef SS_LODINREFRACTIONALPHA
NdotVUnclamped,
#endif
#ifdef SS_LINEARSPECULARREFRACTION
roughness,
#endif
alphaG,
refractionSampler,
#ifndef LODBASEDMICROSFURACE
refractionSamplerLow,
refractionSamplerHigh,
#endif
#ifdef ANISOTROPIC
anisotropicOut,
#endif
#ifdef REALTIME_FILTERING
vRefractionFilteringInfo,
#endif
#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC
vRefractionPosition,
vRefractionSize,
#endif
#endif
#ifdef SS_TRANSLUCENCY
vDiffusionDistance,
#endif
subSurfaceOut
);
#ifdef SS_REFRACTION
surfaceAlbedo=subSurfaceOut.surfaceAlbedo;
#ifdef SS_LINKREFRACTIONTOTRANSPARENCY
alpha=subSurfaceOut.alpha;
#endif
#endif
#else
subSurfaceOut.specularEnvironmentReflectance=specularEnvironmentReflectance;
#endif

#include<pbrBlockDirectLighting>
#include<lightFragment>[0..maxSimultaneousLights]

#include<pbrBlockFinalLitComponents>
#endif
#include<pbrBlockFinalUnlitComponents>
#define CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION
#include<pbrBlockFinalColorComposition>
#include<logDepthFragment>
#include<fogFragment>(color,finalColor)
#include<pbrBlockImageProcessing>
#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR
#ifdef PREPASS
float writeGeometryInfo=finalColor.a>0.4 ? 1.0 : 0.0;
#ifdef PREPASS_POSITION
gl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo);
#endif
#ifdef PREPASS_VELOCITY
vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;
vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;
vec2 velocity=abs(a-b);
velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;
gl_FragData[PREPASS_VELOCITY_INDEX]=vec4(velocity,0.0,writeGeometryInfo);
#endif
#ifdef PREPASS_ALBEDO_SQRT
vec3 sqAlbedo=sqrt(surfaceAlbedo);
#endif
#ifdef PREPASS_IRRADIANCE
vec3 irradiance=finalDiffuse;
#ifndef UNLIT
#ifdef REFLECTION
irradiance+=finalIrradiance;
#endif
#endif
#ifdef SS_SCATTERING
gl_FragData[0]=vec4(finalColor.rgb-irradiance,finalColor.a);
irradiance/=sqAlbedo;
#else
gl_FragData[0]=finalColor;
float scatteringDiffusionProfile=255.;
#endif
gl_FragData[PREPASS_IRRADIANCE_INDEX]=vec4(clamp(irradiance,vec3(0.),vec3(1.)),writeGeometryInfo*scatteringDiffusionProfile/255.);
#else
gl_FragData[0]=vec4(finalColor.rgb,finalColor.a);
#endif
#ifdef PREPASS_DEPTH
gl_FragData[PREPASS_DEPTH_INDEX]=vec4(vViewPos.z,0.0,0.0,writeGeometryInfo);
#endif
#ifdef PREPASS_NORMAL
gl_FragData[PREPASS_NORMAL_INDEX]=vec4((view*vec4(normalW,0.0)).rgb,writeGeometryInfo);
#endif
#ifdef PREPASS_ALBEDO_SQRT
gl_FragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4(sqAlbedo,writeGeometryInfo);
#endif
#ifdef PREPASS_REFLECTIVITY
#if defined(REFLECTIVITY)
gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(baseReflectivity.rgb,baseReflectivity.a*writeGeometryInfo);
#else
gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(0.0,0.0,0.0,writeGeometryInfo);
#endif
#endif
#endif
#if !defined(PREPASS) || defined(WEBGL2)
gl_FragColor=finalColor;
#endif
#if ORDER_INDEPENDENT_TRANSPARENCY
if (fragDepth == nearestDepth) {
frontColor.rgb+=finalColor.rgb*finalColor.a*alphaMultiplier;

frontColor.a=1.0-alphaMultiplier*(1.0-finalColor.a);
} else {
backColor+=finalColor;
}
#endif
#include<pbrDebug>
}
`;
ShaderStore.ShadersStore[name$Y] = shader$Y;
var name$X = "pbrVertexDeclaration"
  , shader$X = `uniform mat4 view;
uniform mat4 viewProjection;
#ifdef ALBEDO
uniform mat4 albedoMatrix;
uniform vec2 vAlbedoInfos;
#endif
#ifdef AMBIENT
uniform mat4 ambientMatrix;
uniform vec4 vAmbientInfos;
#endif
#ifdef OPACITY
uniform mat4 opacityMatrix;
uniform vec2 vOpacityInfos;
#endif
#ifdef EMISSIVE
uniform vec2 vEmissiveInfos;
uniform mat4 emissiveMatrix;
#endif
#ifdef LIGHTMAP
uniform vec2 vLightmapInfos;
uniform mat4 lightmapMatrix;
#endif
#ifdef REFLECTIVITY
uniform vec3 vReflectivityInfos;
uniform mat4 reflectivityMatrix;
#endif
#ifdef METALLIC_REFLECTANCE
uniform vec2 vMetallicReflectanceInfos;
uniform mat4 metallicReflectanceMatrix;
#endif
#ifdef REFLECTANCE
uniform vec2 vReflectanceInfos;
uniform mat4 reflectanceMatrix;
#endif
#ifdef MICROSURFACEMAP
uniform vec2 vMicroSurfaceSamplerInfos;
uniform mat4 microSurfaceSamplerMatrix;
#endif
#ifdef BUMP
uniform vec3 vBumpInfos;
uniform mat4 bumpMatrix;
#endif
#ifdef POINTSIZE
uniform float pointSize;
#endif

#ifdef REFLECTION
uniform vec2 vReflectionInfos;
uniform mat4 reflectionMatrix;
#endif

#ifdef CLEARCOAT
#if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS)
uniform vec4 vClearCoatInfos;
#endif
#ifdef CLEARCOAT_TEXTURE
uniform mat4 clearCoatMatrix;
#endif
#ifdef CLEARCOAT_TEXTURE_ROUGHNESS
uniform mat4 clearCoatRoughnessMatrix;
#endif
#ifdef CLEARCOAT_BUMP
uniform vec2 vClearCoatBumpInfos;
uniform mat4 clearCoatBumpMatrix;
#endif
#ifdef CLEARCOAT_TINT_TEXTURE
uniform vec2 vClearCoatTintInfos;
uniform mat4 clearCoatTintMatrix;
#endif
#endif

#ifdef ANISOTROPIC
#ifdef ANISOTROPIC_TEXTURE
uniform vec2 vAnisotropyInfos;
uniform mat4 anisotropyMatrix;
#endif
#endif

#ifdef SHEEN
#if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS)
uniform vec4 vSheenInfos;
#endif
#ifdef SHEEN_TEXTURE
uniform mat4 sheenMatrix;
#endif
#ifdef SHEEN_TEXTURE_ROUGHNESS
uniform mat4 sheenRoughnessMatrix;
#endif
#endif

#ifdef SUBSURFACE
#ifdef SS_REFRACTION
uniform vec4 vRefractionInfos;
uniform mat4 refractionMatrix;
#endif
#ifdef SS_THICKNESSANDMASK_TEXTURE
uniform vec2 vThicknessInfos;
uniform mat4 thicknessMatrix;
#endif
#ifdef SS_REFRACTIONINTENSITY_TEXTURE
uniform vec2 vRefractionIntensityInfos;
uniform mat4 refractionIntensityMatrix;
#endif
#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE
uniform vec2 vTranslucencyIntensityInfos;
uniform mat4 translucencyIntensityMatrix;
#endif
#endif
#ifdef NORMAL
#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)
#ifdef USESPHERICALFROMREFLECTIONMAP
#ifdef SPHERICAL_HARMONICS
uniform vec3 vSphericalL00;
uniform vec3 vSphericalL1_1;
uniform vec3 vSphericalL10;
uniform vec3 vSphericalL11;
uniform vec3 vSphericalL2_2;
uniform vec3 vSphericalL2_1;
uniform vec3 vSphericalL20;
uniform vec3 vSphericalL21;
uniform vec3 vSphericalL22;
#else
uniform vec3 vSphericalX;
uniform vec3 vSphericalY;
uniform vec3 vSphericalZ;
uniform vec3 vSphericalXX_ZZ;
uniform vec3 vSphericalYY_ZZ;
uniform vec3 vSphericalZZ;
uniform vec3 vSphericalXY;
uniform vec3 vSphericalYZ;
uniform vec3 vSphericalZX;
#endif
#endif
#endif
#endif
#ifdef DETAIL
uniform vec4 vDetailInfos;
uniform mat4 detailMatrix;
#endif`;
ShaderStore.IncludesShadersStore[name$X] = shader$X;
var name$W = "pbrVertexShader"
  , shader$W = `precision highp float;
#include<__decl__pbrVertex>
#define CUSTOM_VERTEX_BEGIN

attribute vec3 position;
#ifdef NORMAL
attribute vec3 normal;
#endif
#ifdef TANGENT
attribute vec4 tangent;
#endif
#ifdef UV1
attribute vec2 uv;
#endif
#include<uvAttributeDeclaration>[2..7]
#include<mainUVVaryingDeclaration>[1..7]
#ifdef VERTEXCOLOR
attribute vec4 color;
#endif
#include<helperFunctions>
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<instancesDeclaration>
#include<prePassVertexDeclaration>
#include<samplerVertexDeclaration>(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo)
#include<samplerVertexDeclaration>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail)
#include<samplerVertexDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient)
#include<samplerVertexDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity)
#include<samplerVertexDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive)
#include<samplerVertexDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap)
#include<samplerVertexDeclaration>(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity)
#include<samplerVertexDeclaration>(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler)
#include<samplerVertexDeclaration>(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance)
#include<samplerVertexDeclaration>(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance)
#include<samplerVertexDeclaration>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump)
#ifdef CLEARCOAT
#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat)
#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness)
#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump)
#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint)
#endif
#ifdef SHEEN
#include<samplerVertexDeclaration>(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen)
#include<samplerVertexDeclaration>(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness)
#endif
#ifdef ANISOTROPIC
#include<samplerVertexDeclaration>(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy)
#endif
#ifdef SUBSURFACE
#include<samplerVertexDeclaration>(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness)
#include<samplerVertexDeclaration>(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity)
#include<samplerVertexDeclaration>(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity)
#endif

varying vec3 vPositionW;
#if DEBUGMODE>0
varying vec4 vClipSpacePosition;
#endif
#ifdef NORMAL
varying vec3 vNormalW;
#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)
varying vec3 vEnvironmentIrradiance;
#include<harmonicsFunctions>
#endif
#endif
#ifdef VERTEXCOLOR
varying vec4 vColor;
#endif
#include<bumpVertexDeclaration>
#include<clipPlaneVertexDeclaration>
#include<fogVertexDeclaration>
#include<__decl__lightVxFragment>[0..maxSimultaneousLights]
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
#ifdef REFLECTIONMAP_SKYBOX
varying vec3 vPositionUVW;
#endif
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
varying vec3 vDirectionW;
#endif
#include<logDepthDeclaration>
#define CUSTOM_VERTEX_DEFINITIONS
void main(void) {
#define CUSTOM_VERTEX_MAIN_BEGIN
vec3 positionUpdated=position;
#ifdef NORMAL
vec3 normalUpdated=normal;
#endif
#ifdef TANGENT
vec4 tangentUpdated=tangent;
#endif
#ifdef UV1
vec2 uvUpdated=uv;
#endif
#include<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
#ifdef REFLECTIONMAP_SKYBOX
vPositionUVW=positionUpdated;
#endif
#define CUSTOM_VERTEX_UPDATE_POSITION
#define CUSTOM_VERTEX_UPDATE_NORMAL
#include<instancesVertex>
#if defined(PREPASS) && defined(PREPASS_VELOCITY) && !defined(BONES_VELOCITY_ENABLED)

vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);
vPreviousPosition=previousViewProjection*previousWorld*vec4(positionUpdated,1.0);
#endif
#include<bonesVertex>
#include<bakedVertexAnimation>
vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);
vPositionW=vec3(worldPos);
#include<prePassVertex>
#ifdef NORMAL
mat3 normalWorld=mat3(finalWorld);
#if defined(INSTANCES) && defined(THIN_INSTANCES)
vNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));
vNormalW=normalize(normalWorld*vNormalW);
#else
#ifdef NONUNIFORMSCALING
normalWorld=transposeMat3(inverseMat3(normalWorld));
#endif
vNormalW=normalize(normalWorld*normalUpdated);
#endif
#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)
vec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;
#ifdef REFLECTIONMAP_OPPOSITEZ
reflectionVector.z*=-1.0;
#endif
vEnvironmentIrradiance=computeEnvironmentIrradiance(reflectionVector);
#endif
#endif
#define CUSTOM_VERTEX_UPDATE_WORLDPOS
#ifdef MULTIVIEW
if (gl_ViewID_OVR == 0u) {
gl_Position=viewProjection*worldPos;
} else {
gl_Position=viewProjectionR*worldPos;
}
#else
gl_Position=viewProjection*worldPos;
#endif
#if DEBUGMODE>0
vClipSpacePosition=gl_Position;
#endif
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
vDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));
#endif

#ifndef UV1
vec2 uvUpdated=vec2(0.,0.);
#endif
#ifdef MAINUV1
vMainUV1=uvUpdated;
#endif
#include<uvVariableDeclaration>[2..7]
#include<samplerVertexImplementation>(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_MATRIXNAME_,albedo,_INFONAME_,AlbedoInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_MATRIXNAME_,reflectivity,_INFONAME_,ReflectivityInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_MATRIXNAME_,microSurfaceSampler,_INFONAME_,MicroSurfaceSamplerInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_MATRIXNAME_,metallicReflectance,_INFONAME_,MetallicReflectanceInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_MATRIXNAME_,reflectance,_INFONAME_,ReflectanceInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x)
#ifdef CLEARCOAT
#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_MATRIXNAME_,clearCoat,_INFONAME_,ClearCoatInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness,_MATRIXNAME_,clearCoatRoughness,_INFONAME_,ClearCoatInfos.z)
#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_MATRIXNAME_,clearCoatBump,_INFONAME_,ClearCoatBumpInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_MATRIXNAME_,clearCoatTint,_INFONAME_,ClearCoatTintInfos.x)
#endif
#ifdef SHEEN
#include<samplerVertexImplementation>(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_MATRIXNAME_,sheen,_INFONAME_,SheenInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness,_MATRIXNAME_,sheen,_INFONAME_,SheenInfos.z)
#endif
#ifdef ANISOTROPIC
#include<samplerVertexImplementation>(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_MATRIXNAME_,anisotropy,_INFONAME_,AnisotropyInfos.x)
#endif
#ifdef SUBSURFACE
#include<samplerVertexImplementation>(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_MATRIXNAME_,thickness,_INFONAME_,ThicknessInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_MATRIXNAME_,refractionIntensity,_INFONAME_,RefractionIntensityInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_MATRIXNAME_,translucencyIntensity,_INFONAME_,TranslucencyIntensityInfos.x)
#endif

#include<bumpVertex>

#include<clipPlaneVertex>

#include<fogVertex>

#include<shadowsVertex>[0..maxSimultaneousLights]

#ifdef VERTEXCOLOR
vColor=color;
#endif

#ifdef POINTSIZE
gl_PointSize=pointSize;
#endif

#include<logDepthVertex>
#define CUSTOM_VERTEX_MAIN_END
}`;
ShaderStore.ShadersStore[name$W] = shader$W;
var onCreatedEffectParameters = {
    effect: null,
    subMesh: null
}
  , PBRMaterialDefines = function(i) {
    __extends(e, i);
    function e() {
        var t = i.call(this) || this;
        return t.PBR = !0,
        t.NUM_SAMPLES = "0",
        t.REALTIME_FILTERING = !1,
        t.MAINUV1 = !1,
        t.MAINUV2 = !1,
        t.MAINUV3 = !1,
        t.MAINUV4 = !1,
        t.MAINUV5 = !1,
        t.MAINUV6 = !1,
        t.UV1 = !1,
        t.UV2 = !1,
        t.UV3 = !1,
        t.UV4 = !1,
        t.UV5 = !1,
        t.UV6 = !1,
        t.ALBEDO = !1,
        t.GAMMAALBEDO = !1,
        t.ALBEDODIRECTUV = 0,
        t.VERTEXCOLOR = !1,
        t.DETAIL = !1,
        t.DETAILDIRECTUV = 0,
        t.DETAIL_NORMALBLENDMETHOD = 0,
        t.BAKED_VERTEX_ANIMATION_TEXTURE = !1,
        t.AMBIENT = !1,
        t.AMBIENTDIRECTUV = 0,
        t.AMBIENTINGRAYSCALE = !1,
        t.OPACITY = !1,
        t.VERTEXALPHA = !1,
        t.OPACITYDIRECTUV = 0,
        t.OPACITYRGB = !1,
        t.ALPHATEST = !1,
        t.DEPTHPREPASS = !1,
        t.ALPHABLEND = !1,
        t.ALPHAFROMALBEDO = !1,
        t.ALPHATESTVALUE = "0.5",
        t.SPECULAROVERALPHA = !1,
        t.RADIANCEOVERALPHA = !1,
        t.ALPHAFRESNEL = !1,
        t.LINEARALPHAFRESNEL = !1,
        t.PREMULTIPLYALPHA = !1,
        t.EMISSIVE = !1,
        t.EMISSIVEDIRECTUV = 0,
        t.GAMMAEMISSIVE = !1,
        t.REFLECTIVITY = !1,
        t.REFLECTIVITY_GAMMA = !1,
        t.REFLECTIVITYDIRECTUV = 0,
        t.SPECULARTERM = !1,
        t.MICROSURFACEFROMREFLECTIVITYMAP = !1,
        t.MICROSURFACEAUTOMATIC = !1,
        t.LODBASEDMICROSFURACE = !1,
        t.MICROSURFACEMAP = !1,
        t.MICROSURFACEMAPDIRECTUV = 0,
        t.METALLICWORKFLOW = !1,
        t.ROUGHNESSSTOREINMETALMAPALPHA = !1,
        t.ROUGHNESSSTOREINMETALMAPGREEN = !1,
        t.METALLNESSSTOREINMETALMAPBLUE = !1,
        t.AOSTOREINMETALMAPRED = !1,
        t.METALLIC_REFLECTANCE = !1,
        t.METALLIC_REFLECTANCE_GAMMA = !1,
        t.METALLIC_REFLECTANCEDIRECTUV = 0,
        t.METALLIC_REFLECTANCE_USE_ALPHA_ONLY = !1,
        t.REFLECTANCE = !1,
        t.REFLECTANCE_GAMMA = !1,
        t.REFLECTANCEDIRECTUV = 0,
        t.ENVIRONMENTBRDF = !1,
        t.ENVIRONMENTBRDF_RGBD = !1,
        t.NORMAL = !1,
        t.TANGENT = !1,
        t.BUMP = !1,
        t.BUMPDIRECTUV = 0,
        t.OBJECTSPACE_NORMALMAP = !1,
        t.PARALLAX = !1,
        t.PARALLAXOCCLUSION = !1,
        t.NORMALXYSCALE = !0,
        t.LIGHTMAP = !1,
        t.LIGHTMAPDIRECTUV = 0,
        t.USELIGHTMAPASSHADOWMAP = !1,
        t.GAMMALIGHTMAP = !1,
        t.RGBDLIGHTMAP = !1,
        t.REFLECTION = !1,
        t.REFLECTIONMAP_3D = !1,
        t.REFLECTIONMAP_SPHERICAL = !1,
        t.REFLECTIONMAP_PLANAR = !1,
        t.REFLECTIONMAP_CUBIC = !1,
        t.USE_LOCAL_REFLECTIONMAP_CUBIC = !1,
        t.REFLECTIONMAP_PROJECTION = !1,
        t.REFLECTIONMAP_SKYBOX = !1,
        t.REFLECTIONMAP_EXPLICIT = !1,
        t.REFLECTIONMAP_EQUIRECTANGULAR = !1,
        t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = !1,
        t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = !1,
        t.INVERTCUBICMAP = !1,
        t.USESPHERICALFROMREFLECTIONMAP = !1,
        t.USEIRRADIANCEMAP = !1,
        t.SPHERICAL_HARMONICS = !1,
        t.USESPHERICALINVERTEX = !1,
        t.REFLECTIONMAP_OPPOSITEZ = !1,
        t.LODINREFLECTIONALPHA = !1,
        t.GAMMAREFLECTION = !1,
        t.RGBDREFLECTION = !1,
        t.LINEARSPECULARREFLECTION = !1,
        t.RADIANCEOCCLUSION = !1,
        t.HORIZONOCCLUSION = !1,
        t.INSTANCES = !1,
        t.THIN_INSTANCES = !1,
        t.PREPASS = !1,
        t.PREPASS_IRRADIANCE = !1,
        t.PREPASS_IRRADIANCE_INDEX = -1,
        t.PREPASS_ALBEDO_SQRT = !1,
        t.PREPASS_ALBEDO_SQRT_INDEX = -1,
        t.PREPASS_DEPTH = !1,
        t.PREPASS_DEPTH_INDEX = -1,
        t.PREPASS_NORMAL = !1,
        t.PREPASS_NORMAL_INDEX = -1,
        t.PREPASS_POSITION = !1,
        t.PREPASS_POSITION_INDEX = -1,
        t.PREPASS_VELOCITY = !1,
        t.PREPASS_VELOCITY_INDEX = -1,
        t.PREPASS_REFLECTIVITY = !1,
        t.PREPASS_REFLECTIVITY_INDEX = -1,
        t.SCENE_MRT_COUNT = 0,
        t.NUM_BONE_INFLUENCERS = 0,
        t.BonesPerMesh = 0,
        t.BONETEXTURE = !1,
        t.BONES_VELOCITY_ENABLED = !1,
        t.NONUNIFORMSCALING = !1,
        t.MORPHTARGETS = !1,
        t.MORPHTARGETS_NORMAL = !1,
        t.MORPHTARGETS_TANGENT = !1,
        t.MORPHTARGETS_UV = !1,
        t.NUM_MORPH_INFLUENCERS = 0,
        t.MORPHTARGETS_TEXTURE = !1,
        t.IMAGEPROCESSING = !1,
        t.VIGNETTE = !1,
        t.VIGNETTEBLENDMODEMULTIPLY = !1,
        t.VIGNETTEBLENDMODEOPAQUE = !1,
        t.TONEMAPPING = !1,
        t.TONEMAPPING_ACES = !1,
        t.CONTRAST = !1,
        t.COLORCURVES = !1,
        t.COLORGRADING = !1,
        t.COLORGRADING3D = !1,
        t.SAMPLER3DGREENDEPTH = !1,
        t.SAMPLER3DBGRMAP = !1,
        t.IMAGEPROCESSINGPOSTPROCESS = !1,
        t.SKIPFINALCOLORCLAMP = !1,
        t.EXPOSURE = !1,
        t.MULTIVIEW = !1,
        t.ORDER_INDEPENDENT_TRANSPARENCY = !1,
        t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS = !1,
        t.USEPHYSICALLIGHTFALLOFF = !1,
        t.USEGLTFLIGHTFALLOFF = !1,
        t.TWOSIDEDLIGHTING = !1,
        t.SHADOWFLOAT = !1,
        t.CLIPPLANE = !1,
        t.CLIPPLANE2 = !1,
        t.CLIPPLANE3 = !1,
        t.CLIPPLANE4 = !1,
        t.CLIPPLANE5 = !1,
        t.CLIPPLANE6 = !1,
        t.POINTSIZE = !1,
        t.FOG = !1,
        t.LOGARITHMICDEPTH = !1,
        t.FORCENORMALFORWARD = !1,
        t.SPECULARAA = !1,
        t.CLEARCOAT = !1,
        t.CLEARCOAT_DEFAULTIOR = !1,
        t.CLEARCOAT_TEXTURE = !1,
        t.CLEARCOAT_TEXTURE_ROUGHNESS = !1,
        t.CLEARCOAT_TEXTUREDIRECTUV = 0,
        t.CLEARCOAT_TEXTURE_ROUGHNESSDIRECTUV = 0,
        t.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE = !1,
        t.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL = !1,
        t.CLEARCOAT_BUMP = !1,
        t.CLEARCOAT_BUMPDIRECTUV = 0,
        t.CLEARCOAT_REMAP_F0 = !0,
        t.CLEARCOAT_TINT = !1,
        t.CLEARCOAT_TINT_TEXTURE = !1,
        t.CLEARCOAT_TINT_GAMMATEXTURE = !1,
        t.CLEARCOAT_TINT_TEXTUREDIRECTUV = 0,
        t.ANISOTROPIC = !1,
        t.ANISOTROPIC_TEXTURE = !1,
        t.ANISOTROPIC_TEXTUREDIRECTUV = 0,
        t.BRDF_V_HEIGHT_CORRELATED = !1,
        t.MS_BRDF_ENERGY_CONSERVATION = !1,
        t.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION = !1,
        t.SHEEN = !1,
        t.SHEEN_TEXTURE = !1,
        t.SHEEN_GAMMATEXTURE = !1,
        t.SHEEN_TEXTURE_ROUGHNESS = !1,
        t.SHEEN_TEXTUREDIRECTUV = 0,
        t.SHEEN_TEXTURE_ROUGHNESSDIRECTUV = 0,
        t.SHEEN_LINKWITHALBEDO = !1,
        t.SHEEN_ROUGHNESS = !1,
        t.SHEEN_ALBEDOSCALING = !1,
        t.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE = !1,
        t.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL = !1,
        t.SUBSURFACE = !1,
        t.SS_REFRACTION = !1,
        t.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE = !1,
        t.SS_TRANSLUCENCY = !1,
        t.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE = !1,
        t.SS_SCATTERING = !1,
        t.SS_THICKNESSANDMASK_TEXTURE = !1,
        t.SS_THICKNESSANDMASK_TEXTUREDIRECTUV = 0,
        t.SS_HAS_THICKNESS = !1,
        t.SS_REFRACTIONINTENSITY_TEXTURE = !1,
        t.SS_REFRACTIONINTENSITY_TEXTUREDIRECTUV = 0,
        t.SS_TRANSLUCENCYINTENSITY_TEXTURE = !1,
        t.SS_TRANSLUCENCYINTENSITY_TEXTUREDIRECTUV = 0,
        t.SS_REFRACTIONMAP_3D = !1,
        t.SS_REFRACTIONMAP_OPPOSITEZ = !1,
        t.SS_LODINREFRACTIONALPHA = !1,
        t.SS_GAMMAREFRACTION = !1,
        t.SS_RGBDREFRACTION = !1,
        t.SS_LINEARSPECULARREFRACTION = !1,
        t.SS_LINKREFRACTIONTOTRANSPARENCY = !1,
        t.SS_ALBEDOFORREFRACTIONTINT = !1,
        t.SS_ALBEDOFORTRANSLUCENCYTINT = !1,
        t.SS_USE_LOCAL_REFRACTIONMAP_CUBIC = !1,
        t.SS_USE_THICKNESS_AS_DEPTH = !1,
        t.SS_MASK_FROM_THICKNESS_TEXTURE = !1,
        t.SS_USE_GLTF_TEXTURES = !1,
        t.UNLIT = !1,
        t.DEBUGMODE = 0,
        t.rebuild(),
        t
    }
    return e.prototype.reset = function() {
        i.prototype.reset.call(this),
        this.ALPHATESTVALUE = "0.5",
        this.PBR = !0,
        this.NORMALXYSCALE = !0
    }
    ,
    e
}(MaterialDefines)
  , PBRBaseMaterial = function(i) {
    __extends(e, i);
    function e(t, r) {
        var n = i.call(this, t, r) || this;
        return n._directIntensity = 1,
        n._emissiveIntensity = 1,
        n._environmentIntensity = 1,
        n._specularIntensity = 1,
        n._lightingInfos = new Vector4(n._directIntensity,n._emissiveIntensity,n._environmentIntensity,n._specularIntensity),
        n._disableBumpMap = !1,
        n._albedoTexture = null,
        n._ambientTexture = null,
        n._ambientTextureStrength = 1,
        n._ambientTextureImpactOnAnalyticalLights = e.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,
        n._opacityTexture = null,
        n._reflectionTexture = null,
        n._emissiveTexture = null,
        n._reflectivityTexture = null,
        n._metallicTexture = null,
        n._metallic = null,
        n._roughness = null,
        n._metallicF0Factor = 1,
        n._metallicReflectanceColor = Color3.White(),
        n._useOnlyMetallicFromMetallicReflectanceTexture = !1,
        n._metallicReflectanceTexture = null,
        n._reflectanceTexture = null,
        n._microSurfaceTexture = null,
        n._bumpTexture = null,
        n._lightmapTexture = null,
        n._ambientColor = new Color3(0,0,0),
        n._albedoColor = new Color3(1,1,1),
        n._reflectivityColor = new Color3(1,1,1),
        n._reflectionColor = new Color3(1,1,1),
        n._emissiveColor = new Color3(0,0,0),
        n._microSurface = .9,
        n._useLightmapAsShadowmap = !1,
        n._useHorizonOcclusion = !0,
        n._useRadianceOcclusion = !0,
        n._useAlphaFromAlbedoTexture = !1,
        n._useSpecularOverAlpha = !0,
        n._useMicroSurfaceFromReflectivityMapAlpha = !1,
        n._useRoughnessFromMetallicTextureAlpha = !0,
        n._useRoughnessFromMetallicTextureGreen = !1,
        n._useMetallnessFromMetallicTextureBlue = !1,
        n._useAmbientOcclusionFromMetallicTextureRed = !1,
        n._useAmbientInGrayScale = !1,
        n._useAutoMicroSurfaceFromReflectivityMap = !1,
        n._lightFalloff = e.LIGHTFALLOFF_PHYSICAL,
        n._useRadianceOverAlpha = !0,
        n._useObjectSpaceNormalMap = !1,
        n._useParallax = !1,
        n._useParallaxOcclusion = !1,
        n._parallaxScaleBias = .05,
        n._disableLighting = !1,
        n._maxSimultaneousLights = 4,
        n._invertNormalMapX = !1,
        n._invertNormalMapY = !1,
        n._twoSidedLighting = !1,
        n._alphaCutOff = .4,
        n._forceAlphaTest = !1,
        n._useAlphaFresnel = !1,
        n._useLinearAlphaFresnel = !1,
        n._environmentBRDFTexture = null,
        n._forceIrradianceInFragment = !1,
        n._realTimeFiltering = !1,
        n._realTimeFilteringQuality = 8,
        n._forceNormalForward = !1,
        n._enableSpecularAntiAliasing = !1,
        n._imageProcessingObserver = null,
        n._renderTargets = new SmartArray(16),
        n._globalAmbientColor = new Color3(0,0,0),
        n._useLogarithmicDepth = !1,
        n._unlit = !1,
        n._debugMode = 0,
        n.debugMode = 0,
        n.debugLimit = -1,
        n.debugFactor = 1,
        n.clearCoat = new PBRClearCoatConfiguration(n._markAllSubMeshesAsTexturesDirty.bind(n)),
        n.anisotropy = new PBRAnisotropicConfiguration(n._markAllSubMeshesAsTexturesDirty.bind(n)),
        n.brdf = new PBRBRDFConfiguration(n._markAllSubMeshesAsMiscDirty.bind(n)),
        n.sheen = new PBRSheenConfiguration(n._markAllSubMeshesAsTexturesDirty.bind(n)),
        n.detailMap = new DetailMapConfiguration(n._markAllSubMeshesAsTexturesDirty.bind(n)),
        n.buildUniformLayout(),
        n._attachImageProcessingConfiguration(null),
        n.getRenderTargetTextures = function() {
            return n._renderTargets.reset(),
            MaterialFlags.ReflectionTextureEnabled && n._reflectionTexture && n._reflectionTexture.isRenderTarget && n._renderTargets.push(n._reflectionTexture),
            n.subSurface.fillRenderTargetTextures(n._renderTargets),
            n._renderTargets
        }
        ,
        n._environmentBRDFTexture = GetEnvironmentBRDFTexture(r),
        n.subSurface = new PBRSubSurfaceConfiguration(n._markAllSubMeshesAsTexturesDirty.bind(n),n._markScenePrePassDirty.bind(n),r),
        n.prePassConfiguration = new PrePassConfiguration,
        n
    }
    return Object.defineProperty(e.prototype, "realTimeFiltering", {
        get: function() {
            return this._realTimeFiltering
        },
        set: function(t) {
            this._realTimeFiltering = t,
            this.markAsDirty(1)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "realTimeFilteringQuality", {
        get: function() {
            return this._realTimeFilteringQuality
        },
        set: function(t) {
            this._realTimeFilteringQuality = t,
            this.markAsDirty(1)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "canRenderToMRT", {
        get: function() {
            return !0
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._attachImageProcessingConfiguration = function(t) {
        var r = this;
        t !== this._imageProcessingConfiguration && (this._imageProcessingConfiguration && this._imageProcessingObserver && this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),
        t ? this._imageProcessingConfiguration = t : this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration,
        this._imageProcessingConfiguration && (this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function() {
            r._markAllSubMeshesAsImageProcessingDirty()
        })))
    }
    ,
    Object.defineProperty(e.prototype, "hasRenderTargetTextures", {
        get: function() {
            return MaterialFlags.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget ? !0 : this.subSurface.hasRenderTargetTextures()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "isPrePassCapable", {
        get: function() {
            return !this.disableDepthWrite
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getClassName = function() {
        return "PBRBaseMaterial"
    }
    ,
    Object.defineProperty(e.prototype, "useLogarithmicDepth", {
        get: function() {
            return this._useLogarithmicDepth
        },
        set: function(t) {
            this._useLogarithmicDepth = t && this.getScene().getEngine().getCaps().fragmentDepthSupported
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "_disableAlphaBlending", {
        get: function() {
            return this.subSurface.disableAlphaBlending || this._transparencyMode === e.PBRMATERIAL_OPAQUE || this._transparencyMode === e.PBRMATERIAL_ALPHATEST
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.needAlphaBlending = function() {
        return this._disableAlphaBlending ? !1 : this.alpha < 1 || this._opacityTexture != null || this._shouldUseAlphaFromAlbedoTexture()
    }
    ,
    e.prototype.needAlphaTesting = function() {
        return this._forceAlphaTest ? !0 : this.subSurface.disableAlphaBlending ? !1 : this._hasAlphaChannel() && (this._transparencyMode == null || this._transparencyMode === e.PBRMATERIAL_ALPHATEST)
    }
    ,
    e.prototype._shouldUseAlphaFromAlbedoTexture = function() {
        return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== e.PBRMATERIAL_OPAQUE
    }
    ,
    e.prototype._hasAlphaChannel = function() {
        return this._albedoTexture != null && this._albedoTexture.hasAlpha || this._opacityTexture != null
    }
    ,
    e.prototype.getAlphaTestTexture = function() {
        return this._albedoTexture
    }
    ,
    e.prototype.isReadyForSubMesh = function(t, r, n) {
        if (r.effect && this.isFrozen && r.effect._wasPreviouslyReady)
            return !0;
        r.materialDefines || (r.materialDefines = new PBRMaterialDefines);
        var o = r.materialDefines;
        if (this._isReadyForSubMesh(r))
            return !0;
        var a = this.getScene()
          , s = a.getEngine();
        if (o._areTexturesDirty && a.texturesEnabled) {
            if (this._albedoTexture && MaterialFlags.DiffuseTextureEnabled && !this._albedoTexture.isReadyOrNotBlocking() || this._ambientTexture && MaterialFlags.AmbientTextureEnabled && !this._ambientTexture.isReadyOrNotBlocking() || this._opacityTexture && MaterialFlags.OpacityTextureEnabled && !this._opacityTexture.isReadyOrNotBlocking())
                return !1;
            var l = this._getReflectionTexture();
            if (l && MaterialFlags.ReflectionTextureEnabled && (!l.isReadyOrNotBlocking() || l.irradianceTexture && !l.irradianceTexture.isReadyOrNotBlocking()) || this._lightmapTexture && MaterialFlags.LightmapTextureEnabled && !this._lightmapTexture.isReadyOrNotBlocking() || this._emissiveTexture && MaterialFlags.EmissiveTextureEnabled && !this._emissiveTexture.isReadyOrNotBlocking())
                return !1;
            if (MaterialFlags.SpecularTextureEnabled) {
                if (this._metallicTexture) {
                    if (!this._metallicTexture.isReadyOrNotBlocking())
                        return !1
                } else if (this._reflectivityTexture && !this._reflectivityTexture.isReadyOrNotBlocking())
                    return !1;
                if (this._metallicReflectanceTexture && !this._metallicReflectanceTexture.isReadyOrNotBlocking() || this._reflectanceTexture && !this._reflectanceTexture.isReadyOrNotBlocking() || this._microSurfaceTexture && !this._microSurfaceTexture.isReadyOrNotBlocking())
                    return !1
            }
            if (s.getCaps().standardDerivatives && this._bumpTexture && MaterialFlags.BumpTextureEnabled && !this._disableBumpMap && !this._bumpTexture.isReady() || this._environmentBRDFTexture && MaterialFlags.ReflectionTextureEnabled && !this._environmentBRDFTexture.isReady())
                return !1
        }
        if (!this.subSurface.isReadyForSubMesh(o, a) || !this.clearCoat.isReadyForSubMesh(o, a, s, this._disableBumpMap) || !this.sheen.isReadyForSubMesh(o, a) || !this.anisotropy.isReadyForSubMesh(o, a) || !this.detailMap.isReadyForSubMesh(o, a) || o._areImageProcessingDirty && this._imageProcessingConfiguration && !this._imageProcessingConfiguration.isReady())
            return !1;
        !s.getCaps().standardDerivatives && !t.isVerticesDataPresent(VertexBuffer.NormalKind) && (t.createNormals(!0),
        Logger$2.Warn("PBRMaterial: Normals have been created for the mesh: " + t.name));
        var u = r.effect
          , c = o._areLightsDisposed
          , h = this._prepareEffect(t, o, this.onCompiled, this.onError, n, null, r.getRenderingMesh().hasThinInstances);
        if (h)
            if (this._onEffectCreatedObservable && (onCreatedEffectParameters.effect = h,
            onCreatedEffectParameters.subMesh = r,
            this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters)),
            this.allowShaderHotSwapping && u && !h.isReady()) {
                if (h = u,
                o.markAsUnprocessed(),
                c)
                    return o._areLightsDisposed = !0,
                    !1
            } else
                a.resetCachedMaterial(),
                r.setEffect(h, o, this._materialContext);
        return !r.effect || !r.effect.isReady() ? !1 : (o._renderId = a.getRenderId(),
        r.effect._wasPreviouslyReady = !0,
        !0)
    }
    ,
    e.prototype.isMetallicWorkflow = function() {
        return !!(this._metallic != null || this._roughness != null || this._metallicTexture)
    }
    ,
    e.prototype._prepareEffect = function(t, r, n, o, a, s, l) {
        if (n === void 0 && (n = null),
        o === void 0 && (o = null),
        a === void 0 && (a = null),
        s === void 0 && (s = null),
        this._prepareDefines(t, r, a, s, l),
        !r.isDirty)
            return null;
        r.markAsProcessed();
        var u = this.getScene()
          , c = u.getEngine()
          , h = new EffectFallbacks
          , f = 0;
        r.USESPHERICALINVERTEX && h.addFallback(f++, "USESPHERICALINVERTEX"),
        r.FOG && h.addFallback(f, "FOG"),
        r.SPECULARAA && h.addFallback(f, "SPECULARAA"),
        r.POINTSIZE && h.addFallback(f, "POINTSIZE"),
        r.LOGARITHMICDEPTH && h.addFallback(f, "LOGARITHMICDEPTH"),
        r.PARALLAX && h.addFallback(f, "PARALLAX"),
        r.PARALLAXOCCLUSION && h.addFallback(f++, "PARALLAXOCCLUSION"),
        f = PBRClearCoatConfiguration.AddFallbacks(r, h, f),
        f = PBRAnisotropicConfiguration.AddFallbacks(r, h, f),
        f = PBRSubSurfaceConfiguration.AddFallbacks(r, h, f),
        f = PBRSheenConfiguration.AddFallbacks(r, h, f),
        r.ENVIRONMENTBRDF && h.addFallback(f++, "ENVIRONMENTBRDF"),
        r.TANGENT && h.addFallback(f++, "TANGENT"),
        r.BUMP && h.addFallback(f++, "BUMP"),
        f = MaterialHelper.HandleFallbacksForShadows(r, h, this._maxSimultaneousLights, f++),
        r.SPECULARTERM && h.addFallback(f++, "SPECULARTERM"),
        r.USESPHERICALFROMREFLECTIONMAP && h.addFallback(f++, "USESPHERICALFROMREFLECTIONMAP"),
        r.USEIRRADIANCEMAP && h.addFallback(f++, "USEIRRADIANCEMAP"),
        r.LIGHTMAP && h.addFallback(f++, "LIGHTMAP"),
        r.NORMAL && h.addFallback(f++, "NORMAL"),
        r.AMBIENT && h.addFallback(f++, "AMBIENT"),
        r.EMISSIVE && h.addFallback(f++, "EMISSIVE"),
        r.VERTEXCOLOR && h.addFallback(f++, "VERTEXCOLOR"),
        r.MORPHTARGETS && h.addFallback(f++, "MORPHTARGETS"),
        r.MULTIVIEW && h.addFallback(0, "MULTIVIEW");
        var d = [VertexBuffer.PositionKind];
        r.NORMAL && d.push(VertexBuffer.NormalKind),
        r.TANGENT && d.push(VertexBuffer.TangentKind);
        for (var _ = 1; _ <= 6; ++_)
            r["UV" + _] && d.push("uv" + (_ === 1 ? "" : _));
        r.VERTEXCOLOR && d.push(VertexBuffer.ColorKind),
        MaterialHelper.PrepareAttributesForBones(d, t, r, h),
        MaterialHelper.PrepareAttributesForInstances(d, r),
        MaterialHelper.PrepareAttributesForMorphTargets(d, t, r),
        MaterialHelper.PrepareAttributesForBakedVertexAnimation(d, t, r);
        var g = "pbr"
          , m = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vMetallicReflectanceFactors", "vEmissiveColor", "visibility", "vReflectionColor", "vFogInfos", "vFogColor", "pointSize", "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos", "vReflectionFilteringInfo", "vMetallicReflectanceInfos", "vReflectanceInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "mBones", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "vClipPlane5", "vClipPlane6", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "metallicReflectanceMatrix", "reflectanceMatrix", "vLightingIntensity", "logarithmicDepthConstant", "vSphericalX", "vSphericalY", "vSphericalZ", "vSphericalXX_ZZ", "vSphericalYY_ZZ", "vSphericalZZ", "vSphericalXY", "vSphericalYZ", "vSphericalZX", "vSphericalL00", "vSphericalL1_1", "vSphericalL10", "vSphericalL11", "vSphericalL2_2", "vSphericalL2_1", "vSphericalL20", "vSphericalL21", "vSphericalL22", "vReflectionMicrosurfaceInfos", "vTangentSpaceParams", "boneTextureWidth", "vDebugMode", "morphTargetTextureInfo", "morphTargetTextureIndices"]
          , v = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler", "bumpSampler", "lightmapSampler", "opacitySampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh", "irradianceSampler", "microSurfaceSampler", "environmentBrdfSampler", "boneSampler", "metallicReflectanceSampler", "reflectanceSampler", "morphTargets", "oitDepthSampler", "oitFrontColorSampler"]
          , y = ["Material", "Scene", "Mesh"];
        DetailMapConfiguration.AddUniforms(m),
        DetailMapConfiguration.AddSamplers(v),
        PBRSubSurfaceConfiguration.AddUniforms(m),
        PBRSubSurfaceConfiguration.AddSamplers(v),
        PBRClearCoatConfiguration.AddUniforms(m),
        PBRClearCoatConfiguration.AddSamplers(v),
        PBRAnisotropicConfiguration.AddUniforms(m),
        PBRAnisotropicConfiguration.AddSamplers(v),
        PBRSheenConfiguration.AddUniforms(m),
        PBRSheenConfiguration.AddSamplers(v),
        PrePassConfiguration.AddUniforms(m),
        PrePassConfiguration.AddSamplers(v),
        ImageProcessingConfiguration && (ImageProcessingConfiguration.PrepareUniforms(m, r),
        ImageProcessingConfiguration.PrepareSamplers(v, r)),
        MaterialHelper.PrepareUniformsAndSamplersList({
            uniformsNames: m,
            uniformBuffersNames: y,
            samplers: v,
            defines: r,
            maxSimultaneousLights: this._maxSimultaneousLights
        });
        var b = {};
        this.customShaderNameResolve && (g = this.customShaderNameResolve(g, m, y, v, r, d, b));
        var T = r.toString();
        return c.createEffect(g, {
            attributes: d,
            uniformsNames: m,
            uniformBuffersNames: y,
            samplers: v,
            defines: T,
            fallbacks: h,
            onCompiled: n,
            onError: o,
            indexParameters: {
                maxSimultaneousLights: this._maxSimultaneousLights,
                maxSimultaneousMorphTargets: r.NUM_MORPH_INFLUENCERS
            },
            processFinalCode: b.processFinalCode,
            multiTarget: r.PREPASS
        }, c)
    }
    ,
    e.prototype._prepareDefines = function(t, r, n, o, a) {
        var s;
        n === void 0 && (n = null),
        o === void 0 && (o = null),
        a === void 0 && (a = !1);
        var l = this.getScene()
          , u = l.getEngine();
        MaterialHelper.PrepareDefinesForLights(l, t, r, !0, this._maxSimultaneousLights, this._disableLighting),
        r._needNormals = !0,
        MaterialHelper.PrepareDefinesForMultiview(l, r);
        var c = this.needAlphaBlendingForMesh(t) && this.getScene().useOrderIndependentTransparency;
        if (MaterialHelper.PrepareDefinesForPrePass(l, r, this.canRenderToMRT && !c),
        MaterialHelper.PrepareDefinesForOIT(l, r, c),
        r.METALLICWORKFLOW = this.isMetallicWorkflow(),
        r._areTexturesDirty) {
            if (r._needUVs = !1,
            l.texturesEnabled) {
                l.getEngine().getCaps().textureLOD && (r.LODBASEDMICROSFURACE = !0),
                this._albedoTexture && MaterialFlags.DiffuseTextureEnabled ? (MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, r, "ALBEDO"),
                r.GAMMAALBEDO = this._albedoTexture.gammaSpace) : r.ALBEDO = !1,
                this._ambientTexture && MaterialFlags.AmbientTextureEnabled ? (MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, r, "AMBIENT"),
                r.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale) : r.AMBIENT = !1,
                this._opacityTexture && MaterialFlags.OpacityTextureEnabled ? (MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, r, "OPACITY"),
                r.OPACITYRGB = this._opacityTexture.getAlphaFromRGB) : r.OPACITY = !1;
                var h = this._getReflectionTexture();
                if (h && MaterialFlags.ReflectionTextureEnabled) {
                    switch (r.REFLECTION = !0,
                    r.GAMMAREFLECTION = h.gammaSpace,
                    r.RGBDREFLECTION = h.isRGBD,
                    r.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !h.invertZ : h.invertZ,
                    r.LODINREFLECTIONALPHA = h.lodLevelInAlpha,
                    r.LINEARSPECULARREFLECTION = h.linearSpecularLOD,
                    this.realTimeFiltering && this.realTimeFilteringQuality > 0 ? (r.NUM_SAMPLES = "" + this.realTimeFilteringQuality,
                    u._features.needTypeSuffixInShaderConstants && (r.NUM_SAMPLES = r.NUM_SAMPLES + "u"),
                    r.REALTIME_FILTERING = !0) : r.REALTIME_FILTERING = !1,
                    h.coordinatesMode === Texture.INVCUBIC_MODE && (r.INVERTCUBICMAP = !0),
                    r.REFLECTIONMAP_3D = h.isCube,
                    r.REFLECTIONMAP_CUBIC = !1,
                    r.REFLECTIONMAP_EXPLICIT = !1,
                    r.REFLECTIONMAP_PLANAR = !1,
                    r.REFLECTIONMAP_PROJECTION = !1,
                    r.REFLECTIONMAP_SKYBOX = !1,
                    r.REFLECTIONMAP_SPHERICAL = !1,
                    r.REFLECTIONMAP_EQUIRECTANGULAR = !1,
                    r.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = !1,
                    r.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = !1,
                    h.coordinatesMode) {
                    case Texture.EXPLICIT_MODE:
                        r.REFLECTIONMAP_EXPLICIT = !0;
                        break;
                    case Texture.PLANAR_MODE:
                        r.REFLECTIONMAP_PLANAR = !0;
                        break;
                    case Texture.PROJECTION_MODE:
                        r.REFLECTIONMAP_PROJECTION = !0;
                        break;
                    case Texture.SKYBOX_MODE:
                        r.REFLECTIONMAP_SKYBOX = !0;
                        break;
                    case Texture.SPHERICAL_MODE:
                        r.REFLECTIONMAP_SPHERICAL = !0;
                        break;
                    case Texture.EQUIRECTANGULAR_MODE:
                        r.REFLECTIONMAP_EQUIRECTANGULAR = !0;
                        break;
                    case Texture.FIXED_EQUIRECTANGULAR_MODE:
                        r.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = !0;
                        break;
                    case Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
                        r.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = !0;
                        break;
                    case Texture.CUBIC_MODE:
                    case Texture.INVCUBIC_MODE:
                    default:
                        r.REFLECTIONMAP_CUBIC = !0,
                        r.USE_LOCAL_REFLECTIONMAP_CUBIC = !!h.boundingBoxSize;
                        break
                    }
                    h.coordinatesMode !== Texture.SKYBOX_MODE && (h.irradianceTexture ? (r.USEIRRADIANCEMAP = !0,
                    r.USESPHERICALFROMREFLECTIONMAP = !1) : h.isCube && (r.USESPHERICALFROMREFLECTIONMAP = !0,
                    r.USEIRRADIANCEMAP = !1,
                    this._forceIrradianceInFragment || this.realTimeFiltering || l.getEngine().getCaps().maxVaryingVectors <= 8 ? r.USESPHERICALINVERTEX = !1 : r.USESPHERICALINVERTEX = !0))
                } else
                    r.REFLECTION = !1,
                    r.REFLECTIONMAP_3D = !1,
                    r.REFLECTIONMAP_SPHERICAL = !1,
                    r.REFLECTIONMAP_PLANAR = !1,
                    r.REFLECTIONMAP_CUBIC = !1,
                    r.USE_LOCAL_REFLECTIONMAP_CUBIC = !1,
                    r.REFLECTIONMAP_PROJECTION = !1,
                    r.REFLECTIONMAP_SKYBOX = !1,
                    r.REFLECTIONMAP_EXPLICIT = !1,
                    r.REFLECTIONMAP_EQUIRECTANGULAR = !1,
                    r.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = !1,
                    r.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = !1,
                    r.INVERTCUBICMAP = !1,
                    r.USESPHERICALFROMREFLECTIONMAP = !1,
                    r.USEIRRADIANCEMAP = !1,
                    r.USESPHERICALINVERTEX = !1,
                    r.REFLECTIONMAP_OPPOSITEZ = !1,
                    r.LODINREFLECTIONALPHA = !1,
                    r.GAMMAREFLECTION = !1,
                    r.RGBDREFLECTION = !1,
                    r.LINEARSPECULARREFLECTION = !1;
                if (this._lightmapTexture && MaterialFlags.LightmapTextureEnabled ? (MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, r, "LIGHTMAP"),
                r.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap,
                r.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace,
                r.RGBDLIGHTMAP = this._lightmapTexture.isRGBD) : r.LIGHTMAP = !1,
                this._emissiveTexture && MaterialFlags.EmissiveTextureEnabled ? (MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, r, "EMISSIVE"),
                r.GAMMAEMISSIVE = this._emissiveTexture.gammaSpace) : r.EMISSIVE = !1,
                MaterialFlags.SpecularTextureEnabled) {
                    if (this._metallicTexture ? (MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, r, "REFLECTIVITY"),
                    r.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha,
                    r.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen,
                    r.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue,
                    r.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed,
                    r.REFLECTIVITY_GAMMA = !1) : this._reflectivityTexture ? (MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, r, "REFLECTIVITY"),
                    r.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha,
                    r.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap,
                    r.REFLECTIVITY_GAMMA = this._reflectivityTexture.gammaSpace) : r.REFLECTIVITY = !1,
                    this._metallicReflectanceTexture || this._reflectanceTexture) {
                        var f = this._metallicReflectanceTexture !== null && this._metallicReflectanceTexture._texture === ((s = this._reflectanceTexture) === null || s === void 0 ? void 0 : s._texture) && this._metallicReflectanceTexture.checkTransformsAreIdentical(this._reflectanceTexture);
                        r.METALLIC_REFLECTANCE_USE_ALPHA_ONLY = this._useOnlyMetallicFromMetallicReflectanceTexture && !f,
                        this._metallicReflectanceTexture ? (MaterialHelper.PrepareDefinesForMergedUV(this._metallicReflectanceTexture, r, "METALLIC_REFLECTANCE"),
                        r.METALLIC_REFLECTANCE_GAMMA = this._metallicReflectanceTexture.gammaSpace) : r.METALLIC_REFLECTANCE = !1,
                        this._reflectanceTexture && !f && (!this._metallicReflectanceTexture || this._metallicReflectanceTexture && this._useOnlyMetallicFromMetallicReflectanceTexture) ? (MaterialHelper.PrepareDefinesForMergedUV(this._reflectanceTexture, r, "REFLECTANCE"),
                        r.REFLECTANCE_GAMMA = this._reflectanceTexture.gammaSpace) : r.REFLECTANCE = !1
                    } else
                        r.METALLIC_REFLECTANCE = !1,
                        r.REFLECTANCE = !1;
                    this._microSurfaceTexture ? MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, r, "MICROSURFACEMAP") : r.MICROSURFACEMAP = !1
                } else
                    r.REFLECTIVITY = !1,
                    r.MICROSURFACEMAP = !1;
                l.getEngine().getCaps().standardDerivatives && this._bumpTexture && MaterialFlags.BumpTextureEnabled && !this._disableBumpMap ? (MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, r, "BUMP"),
                this._useParallax && this._albedoTexture && MaterialFlags.DiffuseTextureEnabled ? (r.PARALLAX = !0,
                r.PARALLAXOCCLUSION = !!this._useParallaxOcclusion) : r.PARALLAX = !1,
                r.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap) : r.BUMP = !1,
                this._environmentBRDFTexture && MaterialFlags.ReflectionTextureEnabled ? (r.ENVIRONMENTBRDF = !0,
                r.ENVIRONMENTBRDF_RGBD = this._environmentBRDFTexture.isRGBD) : (r.ENVIRONMENTBRDF = !1,
                r.ENVIRONMENTBRDF_RGBD = !1),
                this._shouldUseAlphaFromAlbedoTexture() ? r.ALPHAFROMALBEDO = !0 : r.ALPHAFROMALBEDO = !1
            }
            r.SPECULAROVERALPHA = this._useSpecularOverAlpha,
            this._lightFalloff === e.LIGHTFALLOFF_STANDARD ? (r.USEPHYSICALLIGHTFALLOFF = !1,
            r.USEGLTFLIGHTFALLOFF = !1) : this._lightFalloff === e.LIGHTFALLOFF_GLTF ? (r.USEPHYSICALLIGHTFALLOFF = !1,
            r.USEGLTFLIGHTFALLOFF = !0) : (r.USEPHYSICALLIGHTFALLOFF = !0,
            r.USEGLTFLIGHTFALLOFF = !1),
            r.RADIANCEOVERALPHA = this._useRadianceOverAlpha,
            !this.backFaceCulling && this._twoSidedLighting ? r.TWOSIDEDLIGHTING = !0 : r.TWOSIDEDLIGHTING = !1,
            r.SPECULARAA = l.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing
        }
        (r._areTexturesDirty || r._areMiscDirty) && (r.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : ""),
        r.PREMULTIPLYALPHA = this.alphaMode === 7 || this.alphaMode === 8,
        r.ALPHABLEND = this.needAlphaBlendingForMesh(t),
        r.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel,
        r.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel),
        r._areImageProcessingDirty && this._imageProcessingConfiguration && this._imageProcessingConfiguration.prepareDefines(r),
        r.FORCENORMALFORWARD = this._forceNormalForward,
        r.RADIANCEOCCLUSION = this._useRadianceOcclusion,
        r.HORIZONOCCLUSION = this._useHorizonOcclusion,
        r._areMiscDirty && (MaterialHelper.PrepareDefinesForMisc(t, l, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(t) || this._forceAlphaTest, r),
        r.UNLIT = this._unlit || (this.pointsCloud || this.wireframe) && !t.isVerticesDataPresent(VertexBuffer.NormalKind),
        r.DEBUGMODE = this._debugMode),
        this.detailMap.prepareDefines(r, l),
        this.subSurface.prepareDefines(r, l),
        this.clearCoat.prepareDefines(r, l),
        this.anisotropy.prepareDefines(r, t, l),
        this.brdf.prepareDefines(r),
        this.sheen.prepareDefines(r, l),
        MaterialHelper.PrepareDefinesForFrameBoundValues(l, u, r, !!n, o, a),
        MaterialHelper.PrepareDefinesForAttributes(t, r, !0, !0, !0, this._transparencyMode !== e.PBRMATERIAL_OPAQUE)
    }
    ,
    e.prototype.forceCompilation = function(t, r, n) {
        var o = this
          , a = __assign({
            clipPlane: !1,
            useInstances: !1
        }, n)
          , s = new PBRMaterialDefines
          , l = this._prepareEffect(t, s, void 0, void 0, a.useInstances, a.clipPlane, t.hasThinInstances);
        this._onEffectCreatedObservable && (onCreatedEffectParameters.effect = l,
        onCreatedEffectParameters.subMesh = null,
        this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters)),
        l.isReady() ? r && r(this) : l.onCompileObservable.add(function() {
            r && r(o)
        })
    }
    ,
    e.prototype.buildUniformLayout = function() {
        var t = this._uniformBuffer;
        t.addUniform("vAlbedoInfos", 2),
        t.addUniform("vAmbientInfos", 4),
        t.addUniform("vOpacityInfos", 2),
        t.addUniform("vEmissiveInfos", 2),
        t.addUniform("vLightmapInfos", 2),
        t.addUniform("vReflectivityInfos", 3),
        t.addUniform("vMicroSurfaceSamplerInfos", 2),
        t.addUniform("vReflectionInfos", 2),
        t.addUniform("vReflectionFilteringInfo", 2),
        t.addUniform("vReflectionPosition", 3),
        t.addUniform("vReflectionSize", 3),
        t.addUniform("vBumpInfos", 3),
        t.addUniform("albedoMatrix", 16),
        t.addUniform("ambientMatrix", 16),
        t.addUniform("opacityMatrix", 16),
        t.addUniform("emissiveMatrix", 16),
        t.addUniform("lightmapMatrix", 16),
        t.addUniform("reflectivityMatrix", 16),
        t.addUniform("microSurfaceSamplerMatrix", 16),
        t.addUniform("bumpMatrix", 16),
        t.addUniform("vTangentSpaceParams", 2),
        t.addUniform("reflectionMatrix", 16),
        t.addUniform("vReflectionColor", 3),
        t.addUniform("vAlbedoColor", 4),
        t.addUniform("vLightingIntensity", 4),
        t.addUniform("vReflectionMicrosurfaceInfos", 3),
        t.addUniform("pointSize", 1),
        t.addUniform("vReflectivityColor", 4),
        t.addUniform("vEmissiveColor", 3),
        t.addUniform("vAmbientColor", 3),
        t.addUniform("vDebugMode", 2),
        t.addUniform("vMetallicReflectanceFactors", 4),
        t.addUniform("vMetallicReflectanceInfos", 2),
        t.addUniform("metallicReflectanceMatrix", 16),
        t.addUniform("vReflectanceInfos", 2),
        t.addUniform("reflectanceMatrix", 16),
        PBRClearCoatConfiguration.PrepareUniformBuffer(t),
        PBRAnisotropicConfiguration.PrepareUniformBuffer(t),
        PBRSheenConfiguration.PrepareUniformBuffer(t),
        PBRSubSurfaceConfiguration.PrepareUniformBuffer(t),
        DetailMapConfiguration.PrepareUniformBuffer(t),
        t.addUniform("vSphericalL00", 3),
        t.addUniform("vSphericalL1_1", 3),
        t.addUniform("vSphericalL10", 3),
        t.addUniform("vSphericalL11", 3),
        t.addUniform("vSphericalL2_2", 3),
        t.addUniform("vSphericalL2_1", 3),
        t.addUniform("vSphericalL20", 3),
        t.addUniform("vSphericalL21", 3),
        t.addUniform("vSphericalL22", 3),
        t.addUniform("vSphericalX", 3),
        t.addUniform("vSphericalY", 3),
        t.addUniform("vSphericalZ", 3),
        t.addUniform("vSphericalXX_ZZ", 3),
        t.addUniform("vSphericalYY_ZZ", 3),
        t.addUniform("vSphericalZZ", 3),
        t.addUniform("vSphericalXY", 3),
        t.addUniform("vSphericalYZ", 3),
        t.addUniform("vSphericalZX", 3),
        t.create()
    }
    ,
    e.prototype.unbind = function() {
        if (this._activeEffect && !this.getScene().getEngine()._features.needToAlwaysBindUniformBuffers) {
            var t = !1;
            this._reflectionTexture && this._reflectionTexture.isRenderTarget && (this._activeEffect.setTexture("reflection2DSampler", null),
            t = !0),
            this.subSurface.unbind(this._activeEffect) && (t = !0),
            t && this._markAllSubMeshesAsTexturesDirty()
        }
        i.prototype.unbind.call(this)
    }
    ,
    e.prototype.bindForSubMesh = function(t, r, n) {
        var o, a = this.getScene(), s = n.materialDefines;
        if (!!s) {
            var l = n.effect;
            if (!!l) {
                this._activeEffect = l,
                r.getMeshUniformBuffer().bindToEffect(l, "Mesh"),
                r.transferToEffect(t);
                var u = a.getEngine();
                this._uniformBuffer.bindToEffect(l, "Material"),
                this.subSurface.hardBindForSubMesh(this._uniformBuffer, a, u, this.isFrozen, s.LODBASEDMICROSFURACE, this.realTimeFiltering, n),
                this.prePassConfiguration.bindForSubMesh(this._activeEffect, a, r, t, this.isFrozen),
                s.OBJECTSPACE_NORMALMAP && (t.toNormalMatrix(this._normalMatrix),
                this.bindOnlyNormalMatrix(this._normalMatrix));
                var c = this._mustRebind(a, l, r.visibility);
                MaterialHelper.BindBonesParameters(r, this._activeEffect, this.prePassConfiguration);
                var h = null
                  , f = this._uniformBuffer;
                if (c) {
                    if (this.bindViewProjection(l),
                    h = this._getReflectionTexture(),
                    !f.useUbo || !this.isFrozen || !f.isSync) {
                        if (a.texturesEnabled) {
                            if (this._albedoTexture && MaterialFlags.DiffuseTextureEnabled && (f.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level),
                            MaterialHelper.BindTextureMatrix(this._albedoTexture, f, "albedo")),
                            this._ambientTexture && MaterialFlags.AmbientTextureEnabled && (f.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights),
                            MaterialHelper.BindTextureMatrix(this._ambientTexture, f, "ambient")),
                            this._opacityTexture && MaterialFlags.OpacityTextureEnabled && (f.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level),
                            MaterialHelper.BindTextureMatrix(this._opacityTexture, f, "opacity")),
                            h && MaterialFlags.ReflectionTextureEnabled) {
                                if (f.updateMatrix("reflectionMatrix", h.getReflectionTextureMatrix()),
                                f.updateFloat2("vReflectionInfos", h.level, 0),
                                h.boundingBoxSize) {
                                    var d = h;
                                    f.updateVector3("vReflectionPosition", d.boundingBoxPosition),
                                    f.updateVector3("vReflectionSize", d.boundingBoxSize)
                                }
                                if (this.realTimeFiltering) {
                                    var _ = h.getSize().width;
                                    f.updateFloat2("vReflectionFilteringInfo", _, Scalar.Log2(_))
                                }
                                if (!s.USEIRRADIANCEMAP) {
                                    var g = h.sphericalPolynomial;
                                    if (s.USESPHERICALFROMREFLECTIONMAP && g)
                                        if (s.SPHERICAL_HARMONICS) {
                                            var m = g.preScaledHarmonics;
                                            f.updateVector3("vSphericalL00", m.l00),
                                            f.updateVector3("vSphericalL1_1", m.l1_1),
                                            f.updateVector3("vSphericalL10", m.l10),
                                            f.updateVector3("vSphericalL11", m.l11),
                                            f.updateVector3("vSphericalL2_2", m.l2_2),
                                            f.updateVector3("vSphericalL2_1", m.l2_1),
                                            f.updateVector3("vSphericalL20", m.l20),
                                            f.updateVector3("vSphericalL21", m.l21),
                                            f.updateVector3("vSphericalL22", m.l22)
                                        } else
                                            f.updateFloat3("vSphericalX", g.x.x, g.x.y, g.x.z),
                                            f.updateFloat3("vSphericalY", g.y.x, g.y.y, g.y.z),
                                            f.updateFloat3("vSphericalZ", g.z.x, g.z.y, g.z.z),
                                            f.updateFloat3("vSphericalXX_ZZ", g.xx.x - g.zz.x, g.xx.y - g.zz.y, g.xx.z - g.zz.z),
                                            f.updateFloat3("vSphericalYY_ZZ", g.yy.x - g.zz.x, g.yy.y - g.zz.y, g.yy.z - g.zz.z),
                                            f.updateFloat3("vSphericalZZ", g.zz.x, g.zz.y, g.zz.z),
                                            f.updateFloat3("vSphericalXY", g.xy.x, g.xy.y, g.xy.z),
                                            f.updateFloat3("vSphericalYZ", g.yz.x, g.yz.y, g.yz.z),
                                            f.updateFloat3("vSphericalZX", g.zx.x, g.zx.y, g.zx.z)
                                }
                                f.updateFloat3("vReflectionMicrosurfaceInfos", h.getSize().width, h.lodGenerationScale, h.lodGenerationOffset)
                            }
                            this._emissiveTexture && MaterialFlags.EmissiveTextureEnabled && (f.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level),
                            MaterialHelper.BindTextureMatrix(this._emissiveTexture, f, "emissive")),
                            this._lightmapTexture && MaterialFlags.LightmapTextureEnabled && (f.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level),
                            MaterialHelper.BindTextureMatrix(this._lightmapTexture, f, "lightmap")),
                            MaterialFlags.SpecularTextureEnabled && (this._metallicTexture ? (f.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength),
                            MaterialHelper.BindTextureMatrix(this._metallicTexture, f, "reflectivity")) : this._reflectivityTexture && (f.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1),
                            MaterialHelper.BindTextureMatrix(this._reflectivityTexture, f, "reflectivity")),
                            this._metallicReflectanceTexture && (f.updateFloat2("vMetallicReflectanceInfos", this._metallicReflectanceTexture.coordinatesIndex, this._metallicReflectanceTexture.level),
                            MaterialHelper.BindTextureMatrix(this._metallicReflectanceTexture, f, "metallicReflectance")),
                            this._reflectanceTexture && s.REFLECTANCE && (f.updateFloat2("vReflectanceInfos", this._reflectanceTexture.coordinatesIndex, this._reflectanceTexture.level),
                            MaterialHelper.BindTextureMatrix(this._reflectanceTexture, f, "reflectance")),
                            this._microSurfaceTexture && (f.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level),
                            MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, f, "microSurfaceSampler"))),
                            this._bumpTexture && u.getCaps().standardDerivatives && MaterialFlags.BumpTextureEnabled && !this._disableBumpMap && (f.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias),
                            MaterialHelper.BindTextureMatrix(this._bumpTexture, f, "bump"),
                            a._mirroredCameraPosition ? f.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1 : -1, this._invertNormalMapY ? 1 : -1) : f.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1 : 1, this._invertNormalMapY ? -1 : 1))
                        }
                        if (this.pointsCloud && f.updateFloat("pointSize", this.pointSize),
                        s.METALLICWORKFLOW) {
                            TmpColors.Color3[0].r = this._metallic === void 0 || this._metallic === null ? 1 : this._metallic,
                            TmpColors.Color3[0].g = this._roughness === void 0 || this._roughness === null ? 1 : this._roughness,
                            f.updateColor4("vReflectivityColor", TmpColors.Color3[0], 1);
                            var v = this.subSurface.indexOfRefraction
                              , y = 1
                              , b = Math.pow((v - y) / (v + y), 2);
                            this._metallicReflectanceColor.scaleToRef(b * this._metallicF0Factor, TmpColors.Color3[0]);
                            var T = this._metallicF0Factor;
                            f.updateColor4("vMetallicReflectanceFactors", TmpColors.Color3[0], T)
                        } else
                            f.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
                        f.updateColor3("vEmissiveColor", MaterialFlags.EmissiveTextureEnabled ? this._emissiveColor : Color3.BlackReadOnly),
                        f.updateColor3("vReflectionColor", this._reflectionColor),
                        !s.SS_REFRACTION && this.subSurface.linkRefractionWithTransparency ? f.updateColor4("vAlbedoColor", this._albedoColor, 1) : f.updateColor4("vAlbedoColor", this._albedoColor, this.alpha),
                        this._lightingInfos.x = this._directIntensity,
                        this._lightingInfos.y = this._emissiveIntensity,
                        this._lightingInfos.z = this._environmentIntensity * a.environmentIntensity,
                        this._lightingInfos.w = this._specularIntensity,
                        f.updateVector4("vLightingIntensity", this._lightingInfos),
                        a.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor),
                        f.updateColor3("vAmbientColor", this._globalAmbientColor),
                        f.updateFloat2("vDebugMode", this.debugLimit, this.debugFactor)
                    }
                    a.texturesEnabled && (this._albedoTexture && MaterialFlags.DiffuseTextureEnabled && f.setTexture("albedoSampler", this._albedoTexture),
                    this._ambientTexture && MaterialFlags.AmbientTextureEnabled && f.setTexture("ambientSampler", this._ambientTexture),
                    this._opacityTexture && MaterialFlags.OpacityTextureEnabled && f.setTexture("opacitySampler", this._opacityTexture),
                    h && MaterialFlags.ReflectionTextureEnabled && (s.LODBASEDMICROSFURACE ? f.setTexture("reflectionSampler", h) : (f.setTexture("reflectionSampler", h._lodTextureMid || h),
                    f.setTexture("reflectionSamplerLow", h._lodTextureLow || h),
                    f.setTexture("reflectionSamplerHigh", h._lodTextureHigh || h)),
                    s.USEIRRADIANCEMAP && f.setTexture("irradianceSampler", h.irradianceTexture)),
                    s.ENVIRONMENTBRDF && f.setTexture("environmentBrdfSampler", this._environmentBRDFTexture),
                    this._emissiveTexture && MaterialFlags.EmissiveTextureEnabled && f.setTexture("emissiveSampler", this._emissiveTexture),
                    this._lightmapTexture && MaterialFlags.LightmapTextureEnabled && f.setTexture("lightmapSampler", this._lightmapTexture),
                    MaterialFlags.SpecularTextureEnabled && (this._metallicTexture ? f.setTexture("reflectivitySampler", this._metallicTexture) : this._reflectivityTexture && f.setTexture("reflectivitySampler", this._reflectivityTexture),
                    this._metallicReflectanceTexture && f.setTexture("metallicReflectanceSampler", this._metallicReflectanceTexture),
                    this._reflectanceTexture && s.REFLECTANCE && f.setTexture("reflectanceSampler", this._reflectanceTexture),
                    this._microSurfaceTexture && f.setTexture("microSurfaceSampler", this._microSurfaceTexture)),
                    this._bumpTexture && u.getCaps().standardDerivatives && MaterialFlags.BumpTextureEnabled && !this._disableBumpMap && f.setTexture("bumpSampler", this._bumpTexture)),
                    this.getScene().useOrderIndependentTransparency && this.needAlphaBlendingForMesh(r) && this.getScene().depthPeelingRenderer.bind(l),
                    this.detailMap.bindForSubMesh(f, a, this.isFrozen),
                    this.subSurface.bindForSubMesh(f, a, u, this.isFrozen, s.LODBASEDMICROSFURACE, this.realTimeFiltering, n),
                    this.clearCoat.bindForSubMesh(f, a, u, this._disableBumpMap, this.isFrozen, this._invertNormalMapX, this._invertNormalMapY, n),
                    this.anisotropy.bindForSubMesh(f, a, this.isFrozen),
                    this.sheen.bindForSubMesh(f, a, this.isFrozen, n),
                    MaterialHelper.BindClipPlane(this._activeEffect, a),
                    this.bindEyePosition(l)
                } else
                    a.getEngine()._features.needToAlwaysBindUniformBuffers && (this._needToBindSceneUbo = !0);
                (c || !this.isFrozen) && (a.lightsEnabled && !this._disableLighting && MaterialHelper.BindLights(a, r, this._activeEffect, s, this._maxSimultaneousLights),
                (a.fogEnabled && r.applyFog && a.fogMode !== Scene.FOGMODE_NONE || h || r.receiveShadows) && this.bindView(l),
                MaterialHelper.BindFogParameters(a, r, this._activeEffect, !0),
                s.NUM_MORPH_INFLUENCERS && MaterialHelper.BindMorphTargetParameters(r, this._activeEffect),
                s.BAKED_VERTEX_ANIMATION_TEXTURE && ((o = r.bakedVertexAnimationManager) === null || o === void 0 || o.bind(l, s.INSTANCES)),
                this._imageProcessingConfiguration.bind(this._activeEffect),
                MaterialHelper.BindLogDepth(s, this._activeEffect, a)),
                this._afterBind(r, this._activeEffect),
                f.update()
            }
        }
    }
    ,
    e.prototype.getAnimatables = function() {
        var t = [];
        return this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0 && t.push(this._albedoTexture),
        this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0 && t.push(this._ambientTexture),
        this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0 && t.push(this._opacityTexture),
        this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0 && t.push(this._reflectionTexture),
        this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0 && t.push(this._emissiveTexture),
        this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0 ? t.push(this._metallicTexture) : this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0 && t.push(this._reflectivityTexture),
        this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0 && t.push(this._bumpTexture),
        this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0 && t.push(this._lightmapTexture),
        this.detailMap.getAnimatables(t),
        this.subSurface.getAnimatables(t),
        this.clearCoat.getAnimatables(t),
        this.sheen.getAnimatables(t),
        this.anisotropy.getAnimatables(t),
        t
    }
    ,
    e.prototype._getReflectionTexture = function() {
        return this._reflectionTexture ? this._reflectionTexture : this.getScene().environmentTexture
    }
    ,
    e.prototype.getActiveTextures = function() {
        var t = i.prototype.getActiveTextures.call(this);
        return this._albedoTexture && t.push(this._albedoTexture),
        this._ambientTexture && t.push(this._ambientTexture),
        this._opacityTexture && t.push(this._opacityTexture),
        this._reflectionTexture && t.push(this._reflectionTexture),
        this._emissiveTexture && t.push(this._emissiveTexture),
        this._reflectivityTexture && t.push(this._reflectivityTexture),
        this._metallicTexture && t.push(this._metallicTexture),
        this._metallicReflectanceTexture && t.push(this._metallicReflectanceTexture),
        this._reflectanceTexture && t.push(this._reflectanceTexture),
        this._microSurfaceTexture && t.push(this._microSurfaceTexture),
        this._bumpTexture && t.push(this._bumpTexture),
        this._lightmapTexture && t.push(this._lightmapTexture),
        this.detailMap.getActiveTextures(t),
        this.subSurface.getActiveTextures(t),
        this.clearCoat.getActiveTextures(t),
        this.sheen.getActiveTextures(t),
        this.anisotropy.getActiveTextures(t),
        t
    }
    ,
    e.prototype.hasTexture = function(t) {
        return i.prototype.hasTexture.call(this, t) || this._albedoTexture === t || this._ambientTexture === t || this._opacityTexture === t || this._reflectionTexture === t || this._reflectivityTexture === t || this._metallicTexture === t || this._metallicReflectanceTexture === t || this._reflectanceTexture === t || this._microSurfaceTexture === t || this._bumpTexture === t || this._lightmapTexture === t ? !0 : this.detailMap.hasTexture(t) || this.subSurface.hasTexture(t) || this.clearCoat.hasTexture(t) || this.sheen.hasTexture(t) || this.anisotropy.hasTexture(t)
    }
    ,
    e.prototype.setPrePassRenderer = function(t) {
        if (this.subSurface.isScatteringEnabled) {
            var r = this.getScene().enableSubSurfaceForPrePass();
            return r && (r.enabled = !0),
            !0
        }
        return !1
    }
    ,
    e.prototype.dispose = function(t, r) {
        var n, o, a, s, l, u, c, h, f, d, _, g;
        r && (this._environmentBRDFTexture && this.getScene().environmentBRDFTexture !== this._environmentBRDFTexture && this._environmentBRDFTexture.dispose(),
        (n = this._albedoTexture) === null || n === void 0 || n.dispose(),
        (o = this._ambientTexture) === null || o === void 0 || o.dispose(),
        (a = this._opacityTexture) === null || a === void 0 || a.dispose(),
        (s = this._reflectionTexture) === null || s === void 0 || s.dispose(),
        (l = this._emissiveTexture) === null || l === void 0 || l.dispose(),
        (u = this._metallicTexture) === null || u === void 0 || u.dispose(),
        (c = this._reflectivityTexture) === null || c === void 0 || c.dispose(),
        (h = this._bumpTexture) === null || h === void 0 || h.dispose(),
        (f = this._lightmapTexture) === null || f === void 0 || f.dispose(),
        (d = this._metallicReflectanceTexture) === null || d === void 0 || d.dispose(),
        (_ = this._reflectanceTexture) === null || _ === void 0 || _.dispose(),
        (g = this._microSurfaceTexture) === null || g === void 0 || g.dispose()),
        this.detailMap.dispose(r),
        this.subSurface.dispose(r),
        this.clearCoat.dispose(r),
        this.sheen.dispose(r),
        this.anisotropy.dispose(r),
        this._renderTargets.dispose(),
        this._imageProcessingConfiguration && this._imageProcessingObserver && this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),
        i.prototype.dispose.call(this, t, r)
    }
    ,
    e.PBRMATERIAL_OPAQUE = Material.MATERIAL_OPAQUE,
    e.PBRMATERIAL_ALPHATEST = Material.MATERIAL_ALPHATEST,
    e.PBRMATERIAL_ALPHABLEND = Material.MATERIAL_ALPHABLEND,
    e.PBRMATERIAL_ALPHATESTANDBLEND = Material.MATERIAL_ALPHATESTANDBLEND,
    e.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 0,
    e.LIGHTFALLOFF_PHYSICAL = 0,
    e.LIGHTFALLOFF_GLTF = 1,
    e.LIGHTFALLOFF_STANDARD = 2,
    __decorate([serializeAsImageProcessingConfiguration()], e.prototype, "_imageProcessingConfiguration", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsMiscDirty")], e.prototype, "debugMode", void 0),
    __decorate([serialize()], e.prototype, "useLogarithmicDepth", null),
    e
}(PushMaterial)
  , SheenBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Fragment) || this;
        return r.albedoScaling = !1,
        r.linkSheenWithAlbedo = !1,
        r._isUnique = !0,
        r.registerInput("intensity", NodeMaterialBlockConnectionPointTypes.Float, !0, NodeMaterialBlockTargets.Fragment),
        r.registerInput("color", NodeMaterialBlockConnectionPointTypes.Color3, !0, NodeMaterialBlockTargets.Fragment),
        r.registerInput("roughness", NodeMaterialBlockConnectionPointTypes.Float, !0, NodeMaterialBlockTargets.Fragment),
        r.registerOutput("sheen", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("sheen",r,NodeMaterialConnectionPointDirection.Output,e,"SheenBlock")),
        r
    }
    return e.prototype.initialize = function(t) {
        t._excludeVariableName("sheenOut"),
        t._excludeVariableName("sheenMapData"),
        t._excludeVariableName("vSheenColor"),
        t._excludeVariableName("vSheenRoughness")
    }
    ,
    e.prototype.getClassName = function() {
        return "SheenBlock"
    }
    ,
    Object.defineProperty(e.prototype, "intensity", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "color", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "roughness", {
        get: function() {
            return this._inputs[2]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "sheen", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.prepareDefines = function(t, r, n) {
        i.prototype.prepareDefines.call(this, t, r, n),
        n.setValue("SHEEN", !0),
        n.setValue("SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE", !0, !0),
        n.setValue("SHEEN_LINKWITHALBEDO", this.linkSheenWithAlbedo, !0),
        n.setValue("SHEEN_ROUGHNESS", this.roughness.isConnected, !0),
        n.setValue("SHEEN_ALBEDOSCALING", this.albedoScaling, !0)
    }
    ,
    e.prototype.getCode = function(t) {
        var r = ""
          , n = this.color.isConnected ? this.color.associatedVariableName : "vec3(1.)"
          , o = this.intensity.isConnected ? this.intensity.associatedVariableName : "1."
          , a = this.roughness.isConnected ? this.roughness.associatedVariableName : "0."
          , s = "vec4(0.)";
        return r = `#ifdef SHEEN
            sheenOutParams sheenOut;

            vec4 vSheenColor = vec4(` + n + ", " + o + `);

            sheenBlock(
                vSheenColor,
            #ifdef SHEEN_ROUGHNESS
                ` + a + `,
            #endif
                roughness,
            #ifdef SHEEN_TEXTURE
                ` + s + `,
                1.0,
            #endif
                reflectance,
            #ifdef SHEEN_LINKWITHALBEDO
                baseColor,
                surfaceAlbedo,
            #endif
            #ifdef ENVIRONMENTBRDF
                NdotV,
                environmentBrdf,
            #endif
            #if defined(REFLECTION) && defined(ENVIRONMENTBRDF)
                AARoughnessFactors,
                ` + (t == null ? void 0 : t._vReflectionMicrosurfaceInfosName) + `,
                ` + (t == null ? void 0 : t._vReflectionInfosName) + `,
                ` + (t == null ? void 0 : t.reflectionColor) + `,
                vLightingIntensity,
                #ifdef ` + (t == null ? void 0 : t._define3DName) + `
                    ` + (t == null ? void 0 : t._cubeSamplerName) + `,
                #else
                    ` + (t == null ? void 0 : t._2DSamplerName) + `,
                #endif
                reflectionOut.reflectionCoords,
                NdotVUnclamped,
                #ifndef LODBASEDMICROSFURACE
                    #ifdef ` + (t == null ? void 0 : t._define3DName) + `
                        ` + (t == null ? void 0 : t._cubeSamplerName) + `,
                        ` + (t == null ? void 0 : t._cubeSamplerName) + `,
                    #else
                        ` + (t == null ? void 0 : t._2DSamplerName) + `,
                        ` + (t == null ? void 0 : t._2DSamplerName) + `,
                    #endif
                #endif
                #if !defined(` + (t == null ? void 0 : t._defineSkyboxName) + `) && defined(RADIANCEOCCLUSION)
                    seo,
                #endif
                #if !defined(` + (t == null ? void 0 : t._defineSkyboxName) + ") && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(" + (t == null ? void 0 : t._define3DName) + `)
                    eho,
                #endif
            #endif
                sheenOut
            );

            #ifdef SHEEN_LINKWITHALBEDO
                surfaceAlbedo = sheenOut.surfaceAlbedo;
            #endif
        #endif\r
`,
        r
    }
    ,
    e.prototype._buildBlock = function(t) {
        return t.target === NodeMaterialBlockTargets.Fragment && t.sharedData.blocksWithDefines.push(this),
        this
    }
    ,
    e.prototype._dumpPropertiesCode = function() {
        var t = i.prototype._dumpPropertiesCode.call(this);
        return t += this._codeVariableName + ".albedoScaling = " + this.albedoScaling + `;\r
`,
        t += this._codeVariableName + ".linkSheenWithAlbedo = " + this.linkSheenWithAlbedo + `;\r
`,
        t
    }
    ,
    e.prototype.serialize = function() {
        var t = i.prototype.serialize.call(this);
        return t.albedoScaling = this.albedoScaling,
        t.linkSheenWithAlbedo = this.linkSheenWithAlbedo,
        t
    }
    ,
    e.prototype._deserialize = function(t, r, n) {
        i.prototype._deserialize.call(this, t, r, n),
        this.albedoScaling = t.albedoScaling,
        this.linkSheenWithAlbedo = t.linkSheenWithAlbedo
    }
    ,
    __decorate([editableInPropertyPage("Albedo scaling", PropertyTypeForEdition.Boolean, "PROPERTIES", {
        notifiers: {
            update: !0
        }
    })], e.prototype, "albedoScaling", void 0),
    __decorate([editableInPropertyPage("Link sheen with albedo", PropertyTypeForEdition.Boolean, "PROPERTIES", {
        notifiers: {
            update: !0
        }
    })], e.prototype, "linkSheenWithAlbedo", void 0),
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.SheenBlock", SheenBlock);
var AnisotropyBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Fragment) || this;
        return r._isUnique = !0,
        r.registerInput("intensity", NodeMaterialBlockConnectionPointTypes.Float, !0, NodeMaterialBlockTargets.Fragment),
        r.registerInput("direction", NodeMaterialBlockConnectionPointTypes.Vector2, !0, NodeMaterialBlockTargets.Fragment),
        r.registerInput("uv", NodeMaterialBlockConnectionPointTypes.Vector2, !0),
        r.registerInput("worldTangent", NodeMaterialBlockConnectionPointTypes.Vector4, !0),
        r.registerOutput("anisotropy", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("anisotropy",r,NodeMaterialConnectionPointDirection.Output,e,"AnisotropyBlock")),
        r
    }
    return e.prototype.initialize = function(t) {
        t._excludeVariableName("anisotropicOut"),
        t._excludeVariableName("TBN")
    }
    ,
    e.prototype.getClassName = function() {
        return "AnisotropyBlock"
    }
    ,
    Object.defineProperty(e.prototype, "intensity", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "direction", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "uv", {
        get: function() {
            return this._inputs[2]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "worldTangent", {
        get: function() {
            return this._inputs[3]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "anisotropy", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._generateTBNSpace = function(t) {
        var r = ""
          , n = "//" + this.name
          , o = this.uv
          , a = this.worldPositionConnectionPoint
          , s = this.worldNormalConnectionPoint
          , l = this.worldTangent;
        o.isConnected || console.error("You must connect the 'uv' input of the Anisotropy block!"),
        t._emitExtension("derivatives", "#extension GL_OES_standard_derivatives : enable");
        var u = {
            search: /defined\(TANGENT\)/g,
            replace: l.isConnected ? "defined(TANGENT)" : "defined(IGNORE)"
        };
        return l.isConnected && (r += "vec3 tbnNormal = normalize(" + s.associatedVariableName + `.xyz);\r
`,
        r += "vec3 tbnTangent = normalize(" + l.associatedVariableName + `.xyz);\r
`,
        r += `vec3 tbnBitangent = cross(tbnNormal, tbnTangent);\r
`,
        r += `mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal);\r
`),
        r += `
            #if defined(` + (l.isConnected ? "TANGENT" : "IGNORE") + `) && defined(NORMAL)
                mat3 TBN = vTBN;
            #else
                mat3 TBN = cotangent_frame(` + (s.associatedVariableName + ".xyz") + ", " + ("v_" + a.associatedVariableName + ".xyz") + ", " + (o.isConnected ? o.associatedVariableName : "vec2(0.)") + `, vec2(1., 1.));
            #endif\r
`,
        t._emitFunctionFromInclude("bumpFragmentMainFunctions", n, {
            replaceStrings: [u]
        }),
        r
    }
    ,
    e.prototype.getCode = function(t, r) {
        r === void 0 && (r = !1);
        var n = "";
        r && (n += this._generateTBNSpace(t));
        var o = this.intensity.isConnected ? this.intensity.associatedVariableName : "1.0"
          , a = this.direction.isConnected ? this.direction.associatedVariableName : "vec2(1., 0.)";
        return n += `anisotropicOutParams anisotropicOut;
            anisotropicBlock(
                vec3(` + a + ", " + o + `),
            #ifdef ANISOTROPIC_TEXTURE
                vec3(0.),
            #endif
                TBN,
                normalW,
                viewDirectionW,
                anisotropicOut
            );\r
`,
        n
    }
    ,
    e.prototype.prepareDefines = function(t, r, n) {
        i.prototype.prepareDefines.call(this, t, r, n),
        n.setValue("ANISOTROPIC", !0),
        n.setValue("ANISOTROPIC_TEXTURE", !1, !0)
    }
    ,
    e.prototype._buildBlock = function(t) {
        return t.target === NodeMaterialBlockTargets.Fragment && t.sharedData.blocksWithDefines.push(this),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.AnisotropyBlock", AnisotropyBlock);
var ReflectionBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t) || this;
        return r.useSphericalHarmonics = !0,
        r.forceIrradianceInFragment = !1,
        r._isUnique = !0,
        r.registerInput("position", NodeMaterialBlockConnectionPointTypes.Vector3, !1, NodeMaterialBlockTargets.Vertex),
        r.registerInput("world", NodeMaterialBlockConnectionPointTypes.Matrix, !1, NodeMaterialBlockTargets.Vertex),
        r.registerInput("color", NodeMaterialBlockConnectionPointTypes.Color3, !0, NodeMaterialBlockTargets.Fragment),
        r.registerOutput("reflection", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("reflection",r,NodeMaterialConnectionPointDirection.Output,e,"ReflectionBlock")),
        r
    }
    return e.prototype.getClassName = function() {
        return "ReflectionBlock"
    }
    ,
    Object.defineProperty(e.prototype, "position", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "worldPosition", {
        get: function() {
            return this.worldPositionConnectionPoint
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "worldNormal", {
        get: function() {
            return this.worldNormalConnectionPoint
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "world", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cameraPosition", {
        get: function() {
            return this.cameraPositionConnectionPoint
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "view", {
        get: function() {
            return this.viewConnectionPoint
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "color", {
        get: function() {
            return this._inputs[2]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "reflection", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "hasTexture", {
        get: function() {
            return !!this._getTexture()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "reflectionColor", {
        get: function() {
            return this.color.isConnected ? this.color.associatedVariableName : "vec3(1., 1., 1.)"
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._getTexture = function() {
        return this.texture ? this.texture : this._scene.environmentTexture
    }
    ,
    e.prototype.prepareDefines = function(t, r, n) {
        i.prototype.prepareDefines.call(this, t, r, n);
        var o = this._getTexture()
          , a = o && o.getTextureMatrix;
        n.setValue("REFLECTION", a, !0),
        a && (n.setValue(this._defineLODReflectionAlpha, o.lodLevelInAlpha, !0),
        n.setValue(this._defineLinearSpecularReflection, o.linearSpecularLOD, !0),
        n.setValue(this._defineOppositeZ, this._scene.useRightHandedSystem ? !o.invertZ : o.invertZ, !0),
        n.setValue("SPHERICAL_HARMONICS", this.useSphericalHarmonics, !0),
        n.setValue("GAMMAREFLECTION", o.gammaSpace, !0),
        n.setValue("RGBDREFLECTION", o.isRGBD, !0),
        o && o.coordinatesMode !== Texture.SKYBOX_MODE && o.isCube && (n.setValue("USESPHERICALFROMREFLECTIONMAP", !0),
        n.setValue("USEIRRADIANCEMAP", !1),
        this.forceIrradianceInFragment || this._scene.getEngine().getCaps().maxVaryingVectors <= 8 ? n.setValue("USESPHERICALINVERTEX", !1) : n.setValue("USESPHERICALINVERTEX", !0)))
    }
    ,
    e.prototype.bind = function(t, r, n, o) {
        i.prototype.bind.call(this, t, r, n);
        var a = this._getTexture();
        if (!(!a || !o)) {
            a.isCube ? t.setTexture(this._cubeSamplerName, a) : t.setTexture(this._2DSamplerName, a);
            var s = a.getSize().width;
            t.setFloat3(this._vReflectionMicrosurfaceInfosName, s, a.lodGenerationScale, a.lodGenerationOffset),
            t.setFloat2(this._vReflectionFilteringInfoName, s, Scalar.Log2(s));
            var l = o.materialDefines
              , u = a.sphericalPolynomial;
            if (l.USESPHERICALFROMREFLECTIONMAP && u)
                if (l.SPHERICAL_HARMONICS) {
                    var c = u.preScaledHarmonics;
                    t.setVector3("vSphericalL00", c.l00),
                    t.setVector3("vSphericalL1_1", c.l1_1),
                    t.setVector3("vSphericalL10", c.l10),
                    t.setVector3("vSphericalL11", c.l11),
                    t.setVector3("vSphericalL2_2", c.l2_2),
                    t.setVector3("vSphericalL2_1", c.l2_1),
                    t.setVector3("vSphericalL20", c.l20),
                    t.setVector3("vSphericalL21", c.l21),
                    t.setVector3("vSphericalL22", c.l22)
                } else
                    t.setFloat3("vSphericalX", u.x.x, u.x.y, u.x.z),
                    t.setFloat3("vSphericalY", u.y.x, u.y.y, u.y.z),
                    t.setFloat3("vSphericalZ", u.z.x, u.z.y, u.z.z),
                    t.setFloat3("vSphericalXX_ZZ", u.xx.x - u.zz.x, u.xx.y - u.zz.y, u.xx.z - u.zz.z),
                    t.setFloat3("vSphericalYY_ZZ", u.yy.x - u.zz.x, u.yy.y - u.zz.y, u.yy.z - u.zz.z),
                    t.setFloat3("vSphericalZZ", u.zz.x, u.zz.y, u.zz.z),
                    t.setFloat3("vSphericalXY", u.xy.x, u.xy.y, u.xy.z),
                    t.setFloat3("vSphericalYZ", u.yz.x, u.yz.y, u.yz.z),
                    t.setFloat3("vSphericalZX", u.zx.x, u.zx.y, u.zx.z)
        }
    }
    ,
    e.prototype.handleVertexSide = function(t) {
        var r = i.prototype.handleVertexSide.call(this, t);
        t._emitFunctionFromInclude("harmonicsFunctions", "//" + this.name, {
            replaceStrings: [{
                search: /uniform vec3 vSphericalL00;[\s\S]*?uniform vec3 vSphericalL22;/g,
                replace: ""
            }, {
                search: /uniform vec3 vSphericalX;[\s\S]*?uniform vec3 vSphericalZX;/g,
                replace: ""
            }]
        });
        var n = t._getFreeVariableName("reflectionVector");
        return this._vEnvironmentIrradianceName = t._getFreeVariableName("vEnvironmentIrradiance"),
        t._emitVaryingFromString(this._vEnvironmentIrradianceName, "vec3", "defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)"),
        t._emitUniformFromString("vSphericalL00", "vec3", "SPHERICAL_HARMONICS"),
        t._emitUniformFromString("vSphericalL1_1", "vec3", "SPHERICAL_HARMONICS"),
        t._emitUniformFromString("vSphericalL10", "vec3", "SPHERICAL_HARMONICS"),
        t._emitUniformFromString("vSphericalL11", "vec3", "SPHERICAL_HARMONICS"),
        t._emitUniformFromString("vSphericalL2_2", "vec3", "SPHERICAL_HARMONICS"),
        t._emitUniformFromString("vSphericalL2_1", "vec3", "SPHERICAL_HARMONICS"),
        t._emitUniformFromString("vSphericalL20", "vec3", "SPHERICAL_HARMONICS"),
        t._emitUniformFromString("vSphericalL21", "vec3", "SPHERICAL_HARMONICS"),
        t._emitUniformFromString("vSphericalL22", "vec3", "SPHERICAL_HARMONICS"),
        t._emitUniformFromString("vSphericalX", "vec3", "SPHERICAL_HARMONICS", !0),
        t._emitUniformFromString("vSphericalY", "vec3", "SPHERICAL_HARMONICS", !0),
        t._emitUniformFromString("vSphericalZ", "vec3", "SPHERICAL_HARMONICS", !0),
        t._emitUniformFromString("vSphericalXX_ZZ", "vec3", "SPHERICAL_HARMONICS", !0),
        t._emitUniformFromString("vSphericalYY_ZZ", "vec3", "SPHERICAL_HARMONICS", !0),
        t._emitUniformFromString("vSphericalZZ", "vec3", "SPHERICAL_HARMONICS", !0),
        t._emitUniformFromString("vSphericalXY", "vec3", "SPHERICAL_HARMONICS", !0),
        t._emitUniformFromString("vSphericalYZ", "vec3", "SPHERICAL_HARMONICS", !0),
        t._emitUniformFromString("vSphericalZX", "vec3", "SPHERICAL_HARMONICS", !0),
        r += `#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)
                vec3 ` + n + " = vec3(" + this._reflectionMatrixName + " * vec4(normalize(" + this.worldNormal.associatedVariableName + `).xyz, 0)).xyz;
                #ifdef ` + this._defineOppositeZ + `
                    ` + n + `.z *= -1.0;
                #endif
                ` + this._vEnvironmentIrradianceName + " = computeEnvironmentIrradiance(" + n + `);
            #endif\r
`,
        r
    }
    ,
    e.prototype.getCode = function(t, r) {
        var n = "";
        this.handleFragmentSideInits(t),
        t._emitFunctionFromInclude("harmonicsFunctions", "//" + this.name, {
            replaceStrings: [{
                search: /uniform vec3 vSphericalL00;[\s\S]*?uniform vec3 vSphericalL22;/g,
                replace: ""
            }, {
                search: /uniform vec3 vSphericalX;[\s\S]*?uniform vec3 vSphericalZX;/g,
                replace: ""
            }]
        }),
        t._emitFunction("sampleReflection", `
            #ifdef ` + this._define3DName + `
                #define sampleReflection(s, c) textureCube(s, c)
            #else
                #define sampleReflection(s, c) texture2D(s, c)
            #endif\r
`, "//" + this.name),
        t._emitFunction("sampleReflectionLod", `
            #ifdef ` + this._define3DName + `
                #define sampleReflectionLod(s, c, l) textureCubeLodEXT(s, c, l)
            #else
                #define sampleReflectionLod(s, c, l) texture2DLodEXT(s, c, l)
            #endif\r
`, "//" + this.name);
        var o = `
            vec3 computeReflectionCoordsPBR(vec4 worldPos, vec3 worldNormal) {
                ` + this.handleFragmentSideCodeReflectionCoords("worldNormal", "worldPos", !0) + `
                return ` + this._reflectionVectorName + `;
            }\r
`;
        return t._emitFunction("computeReflectionCoordsPBR", o, "//" + this.name),
        this._vReflectionMicrosurfaceInfosName = t._getFreeVariableName("vReflectionMicrosurfaceInfos"),
        t._emitUniformFromString(this._vReflectionMicrosurfaceInfosName, "vec3"),
        this._vReflectionInfosName = t._getFreeVariableName("vReflectionInfos"),
        this._vReflectionFilteringInfoName = t._getFreeVariableName("vReflectionFilteringInfo"),
        t._emitUniformFromString(this._vReflectionFilteringInfoName, "vec2"),
        n += `#ifdef REFLECTION
            vec2 ` + this._vReflectionInfosName + ` = vec2(1., 0.);

            reflectionOutParams reflectionOut;

            reflectionBlock(
                ` + ("v_" + this.worldPosition.associatedVariableName + ".xyz") + `,
                ` + r + `,
                alphaG,
                ` + this._vReflectionMicrosurfaceInfosName + `,
                ` + this._vReflectionInfosName + `,
                ` + this.reflectionColor + `,
            #ifdef ANISOTROPIC
                anisotropicOut,
            #endif
            #if defined(` + this._defineLODReflectionAlpha + ") && !defined(" + this._defineSkyboxName + `)
                NdotVUnclamped,
            #endif
            #ifdef ` + this._defineLinearSpecularReflection + `
                roughness,
            #endif
            #ifdef ` + this._define3DName + `
                ` + this._cubeSamplerName + `,
            #else
                ` + this._2DSamplerName + `,
            #endif
            #if defined(NORMAL) && defined(USESPHERICALINVERTEX)
                ` + this._vEnvironmentIrradianceName + `,
            #endif
            #ifdef USESPHERICALFROMREFLECTIONMAP
                #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)
                    ` + this._reflectionMatrixName + `,
                #endif
            #endif
            #ifdef USEIRRADIANCEMAP
                irradianceSampler, // ** not handled **
            #endif
            #ifndef LODBASEDMICROSFURACE
                #ifdef ` + this._define3DName + `
                    ` + this._cubeSamplerName + `,
                    ` + this._cubeSamplerName + `,
                #else
                    ` + this._2DSamplerName + `,
                    ` + this._2DSamplerName + `,
                #endif
            #endif
            #ifdef REALTIME_FILTERING
                ` + this._vReflectionFilteringInfoName + `,
            #endif
                reflectionOut
            );
        #endif\r
`,
        n
    }
    ,
    e.prototype._buildBlock = function(t) {
        return this._scene = t.sharedData.scene,
        t.target !== NodeMaterialBlockTargets.Fragment && (this._defineLODReflectionAlpha = t._getFreeDefineName("LODINREFLECTIONALPHA"),
        this._defineLinearSpecularReflection = t._getFreeDefineName("LINEARSPECULARREFLECTION")),
        this
    }
    ,
    e.prototype._dumpPropertiesCode = function() {
        var t = i.prototype._dumpPropertiesCode.call(this);
        return this.texture && (t += this._codeVariableName + ".texture.gammaSpace = " + this.texture.gammaSpace + `;\r
`),
        t += this._codeVariableName + ".useSphericalHarmonics = " + this.useSphericalHarmonics + `;\r
`,
        t += this._codeVariableName + ".forceIrradianceInFragment = " + this.forceIrradianceInFragment + `;\r
`,
        t
    }
    ,
    e.prototype.serialize = function() {
        var t, r, n = i.prototype.serialize.call(this);
        return n.useSphericalHarmonics = this.useSphericalHarmonics,
        n.forceIrradianceInFragment = this.forceIrradianceInFragment,
        n.gammaSpace = (r = (t = this.texture) === null || t === void 0 ? void 0 : t.gammaSpace) !== null && r !== void 0 ? r : !0,
        n
    }
    ,
    e.prototype._deserialize = function(t, r, n) {
        i.prototype._deserialize.call(this, t, r, n),
        this.useSphericalHarmonics = t.useSphericalHarmonics,
        this.forceIrradianceInFragment = t.forceIrradianceInFragment,
        this.texture && (this.texture.gammaSpace = t.gammaSpace)
    }
    ,
    __decorate([editableInPropertyPage("Spherical Harmonics", PropertyTypeForEdition.Boolean, "ADVANCED", {
        notifiers: {
            update: !0
        }
    })], e.prototype, "useSphericalHarmonics", void 0),
    __decorate([editableInPropertyPage("Force irradiance in fragment", PropertyTypeForEdition.Boolean, "ADVANCED", {
        notifiers: {
            update: !0
        }
    })], e.prototype, "forceIrradianceInFragment", void 0),
    e
}(ReflectionTextureBaseBlock);
RegisterClass("BABYLON.ReflectionBlock", ReflectionBlock);
var ClearCoatBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Fragment) || this;
        return r.remapF0OnInterfaceChange = !0,
        r._isUnique = !0,
        r.registerInput("intensity", NodeMaterialBlockConnectionPointTypes.Float, !1, NodeMaterialBlockTargets.Fragment),
        r.registerInput("roughness", NodeMaterialBlockConnectionPointTypes.Float, !0, NodeMaterialBlockTargets.Fragment),
        r.registerInput("indexOfRefraction", NodeMaterialBlockConnectionPointTypes.Float, !0, NodeMaterialBlockTargets.Fragment),
        r.registerInput("normalMapColor", NodeMaterialBlockConnectionPointTypes.Color3, !0, NodeMaterialBlockTargets.Fragment),
        r.registerInput("uv", NodeMaterialBlockConnectionPointTypes.Vector2, !0, NodeMaterialBlockTargets.Fragment),
        r.registerInput("tintColor", NodeMaterialBlockConnectionPointTypes.Color3, !0, NodeMaterialBlockTargets.Fragment),
        r.registerInput("tintAtDistance", NodeMaterialBlockConnectionPointTypes.Float, !0, NodeMaterialBlockTargets.Fragment),
        r.registerInput("tintThickness", NodeMaterialBlockConnectionPointTypes.Float, !0, NodeMaterialBlockTargets.Fragment),
        r.registerInput("worldTangent", NodeMaterialBlockConnectionPointTypes.Vector4, !0),
        r.registerOutput("clearcoat", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("clearcoat",r,NodeMaterialConnectionPointDirection.Output,e,"ClearCoatBlock")),
        r
    }
    return e.prototype.initialize = function(t) {
        t._excludeVariableName("clearcoatOut"),
        t._excludeVariableName("vClearCoatParams"),
        t._excludeVariableName("vClearCoatTintParams"),
        t._excludeVariableName("vClearCoatRefractionParams"),
        t._excludeVariableName("vClearCoatTangentSpaceParams")
    }
    ,
    e.prototype.getClassName = function() {
        return "ClearCoatBlock"
    }
    ,
    Object.defineProperty(e.prototype, "intensity", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "roughness", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "indexOfRefraction", {
        get: function() {
            return this._inputs[2]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "normalMapColor", {
        get: function() {
            return this._inputs[3]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "uv", {
        get: function() {
            return this._inputs[4]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "tintColor", {
        get: function() {
            return this._inputs[5]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "tintAtDistance", {
        get: function() {
            return this._inputs[6]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "tintThickness", {
        get: function() {
            return this._inputs[7]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "worldTangent", {
        get: function() {
            return this._inputs[8]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "clearcoat", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.autoConfigure = function(t) {
        if (!this.intensity.isConnected) {
            var r = new InputBlock("ClearCoat intensity",NodeMaterialBlockTargets.Fragment,NodeMaterialBlockConnectionPointTypes.Float);
            r.value = 1,
            r.output.connectTo(this.intensity)
        }
    }
    ,
    e.prototype.prepareDefines = function(t, r, n) {
        i.prototype.prepareDefines.call(this, t, r, n),
        n.setValue("CLEARCOAT", !0),
        n.setValue("CLEARCOAT_TEXTURE", !1, !0),
        n.setValue("CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE", !0, !0),
        n.setValue("CLEARCOAT_TINT", this.tintColor.isConnected || this.tintThickness.isConnected || this.tintAtDistance.isConnected, !0),
        n.setValue("CLEARCOAT_BUMP", this.normalMapColor.isConnected, !0),
        n.setValue("CLEARCOAT_DEFAULTIOR", this.indexOfRefraction.isConnected ? this.indexOfRefraction.connectInputBlock.value === PBRClearCoatConfiguration._DefaultIndexOfRefraction : !0, !0),
        n.setValue("CLEARCOAT_REMAP_F0", this.remapF0OnInterfaceChange, !0)
    }
    ,
    e.prototype.bind = function(t, r, n, o) {
        var a, s;
        i.prototype.bind.call(this, t, r, n);
        var l = (s = (a = this.indexOfRefraction.connectInputBlock) === null || a === void 0 ? void 0 : a.value) !== null && s !== void 0 ? s : PBRClearCoatConfiguration._DefaultIndexOfRefraction
          , u = 1 - l
          , c = 1 + l
          , h = Math.pow(-u / c, 2)
          , f = 1 / l;
        t.setFloat4("vClearCoatRefractionParams", h, f, u, c);
        var d = this.clearcoat.hasEndpoints ? this.clearcoat.endpoints[0].ownerBlock : null
          , _ = d != null && d.perturbedNormal.isConnected ? d.perturbedNormal.connectedPoint.ownerBlock : null;
        this._scene._mirroredCameraPosition ? t.setFloat2("vClearCoatTangentSpaceParams", _ != null && _.invertX ? 1 : -1, _ != null && _.invertY ? 1 : -1) : t.setFloat2("vClearCoatTangentSpaceParams", _ != null && _.invertX ? -1 : 1, _ != null && _.invertY ? -1 : 1)
    }
    ,
    e.prototype._generateTBNSpace = function(t, r, n) {
        var o = ""
          , a = "//" + this.name
          , s = this.worldTangent;
        t._emitExtension("derivatives", "#extension GL_OES_standard_derivatives : enable");
        var l = {
            search: /defined\(TANGENT\)/g,
            replace: s.isConnected ? "defined(TANGENT)" : "defined(IGNORE)"
        };
        return s.isConnected && (o += "vec3 tbnNormal = normalize(" + n + `.xyz);\r
`,
        o += "vec3 tbnTangent = normalize(" + s.associatedVariableName + `.xyz);\r
`,
        o += `vec3 tbnBitangent = cross(tbnNormal, tbnTangent);\r
`,
        o += `mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal);\r
`),
        t._emitFunctionFromInclude("bumpFragmentMainFunctions", a, {
            replaceStrings: [l]
        }),
        o
    }
    ,
    e.GetCode = function(t, r, n, o, a, s, l) {
        var u = ""
          , c = r != null && r.intensity.isConnected ? r.intensity.associatedVariableName : "1."
          , h = r != null && r.roughness.isConnected ? r.roughness.associatedVariableName : "0."
          , f = r != null && r.normalMapColor.isConnected ? r.normalMapColor.associatedVariableName : "vec3(0.)"
          , d = r != null && r.uv.isConnected ? r.uv.associatedVariableName : "vec2(0.)"
          , _ = r != null && r.tintColor.isConnected ? r.tintColor.associatedVariableName : "vec3(1.)"
          , g = r != null && r.tintThickness.isConnected ? r.tintThickness.associatedVariableName : "1."
          , m = r != null && r.tintAtDistance.isConnected ? r.tintAtDistance.associatedVariableName : "1."
          , v = "vec4(0.)";
        return r && (t._emitUniformFromString("vClearCoatRefractionParams", "vec4"),
        t._emitUniformFromString("vClearCoatTangentSpaceParams", "vec2")),
        a && r && (u += r._generateTBNSpace(t, o, l),
        s = r.worldTangent.isConnected),
        u += `clearcoatOutParams clearcoatOut;

        #ifdef CLEARCOAT
            vec2 vClearCoatParams = vec2(` + c + ", " + h + `);
            vec4 vClearCoatTintParams = vec4(` + _ + ", " + g + `);

            clearcoatBlock(
                ` + o + `.xyz,
                geometricNormalW,
                viewDirectionW,
                vClearCoatParams,
                specularEnvironmentR0,
            #ifdef CLEARCOAT_TEXTURE
                vec2(0.),
            #endif
            #ifdef CLEARCOAT_TINT
                vClearCoatTintParams,
                ` + m + `,
                vClearCoatRefractionParams,
                #ifdef CLEARCOAT_TINT_TEXTURE
                    ` + v + `,
                #endif
            #endif
            #ifdef CLEARCOAT_BUMP
                vec2(0., 1.),
                vec4(` + f + `, 0.),
                ` + d + `,
                #if defined(` + (s ? "TANGENT" : "IGNORE") + `) && defined(NORMAL)
                    vTBN,
                #else
                    vClearCoatTangentSpaceParams,
                #endif
                #ifdef OBJECTSPACE_NORMALMAP
                    normalMatrix,
                #endif
            #endif
            #if defined(FORCENORMALFORWARD) && defined(NORMAL)
                faceNormal,
            #endif
            #ifdef REFLECTION
                ` + (n == null ? void 0 : n._vReflectionMicrosurfaceInfosName) + `,
                ` + (n == null ? void 0 : n._vReflectionInfosName) + `,
                ` + (n == null ? void 0 : n.reflectionColor) + `,
                vLightingIntensity,
                #ifdef ` + (n == null ? void 0 : n._define3DName) + `
                    ` + (n == null ? void 0 : n._cubeSamplerName) + `,
                #else
                    ` + (n == null ? void 0 : n._2DSamplerName) + `,
                #endif
                #ifndef LODBASEDMICROSFURACE
                    #ifdef ` + (n == null ? void 0 : n._define3DName) + `
                        ` + (n == null ? void 0 : n._cubeSamplerName) + `,
                        ` + (n == null ? void 0 : n._cubeSamplerName) + `,
                    #else
                        ` + (n == null ? void 0 : n._2DSamplerName) + `,
                        ` + (n == null ? void 0 : n._2DSamplerName) + `,
                    #endif
                #endif
            #endif
            #if defined(ENVIRONMENTBRDF) && !defined(` + (n == null ? void 0 : n._defineSkyboxName) + `)
                #ifdef RADIANCEOCCLUSION
                    ambientMonochrome,
                #endif
            #endif
            #if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING)
                (gl_FrontFacing ? 1. : -1.),
            #endif
                clearcoatOut
            );
        #else
            clearcoatOut.specularEnvironmentR0 = specularEnvironmentR0;
        #endif\r
`,
        u
    }
    ,
    e.prototype._buildBlock = function(t) {
        return this._scene = t.sharedData.scene,
        t.target === NodeMaterialBlockTargets.Fragment && (t.sharedData.bindableBlocks.push(this),
        t.sharedData.blocksWithDefines.push(this)),
        this
    }
    ,
    e.prototype._dumpPropertiesCode = function() {
        var t = i.prototype._dumpPropertiesCode.call(this);
        return t += this._codeVariableName + ".remapF0OnInterfaceChange = " + this.remapF0OnInterfaceChange + `;\r
`,
        t
    }
    ,
    e.prototype.serialize = function() {
        var t = i.prototype.serialize.call(this);
        return t.remapF0OnInterfaceChange = this.remapF0OnInterfaceChange,
        t
    }
    ,
    e.prototype._deserialize = function(t, r, n) {
        var o;
        i.prototype._deserialize.call(this, t, r, n),
        this.remapF0OnInterfaceChange = (o = t.remapF0OnInterfaceChange) !== null && o !== void 0 ? o : !0
    }
    ,
    __decorate([editableInPropertyPage("Remap F0 on interface change", PropertyTypeForEdition.Boolean, "ADVANCED")], e.prototype, "remapF0OnInterfaceChange", void 0),
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.ClearCoatBlock", ClearCoatBlock);
var RefractionBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Fragment) || this;
        return r.linkRefractionWithTransparency = !1,
        r.invertRefractionY = !1,
        r.useThicknessAsDepth = !1,
        r._isUnique = !0,
        r.registerInput("intensity", NodeMaterialBlockConnectionPointTypes.Float, !1, NodeMaterialBlockTargets.Fragment),
        r.registerInput("tintAtDistance", NodeMaterialBlockConnectionPointTypes.Float, !0, NodeMaterialBlockTargets.Fragment),
        r.registerInput("volumeIndexOfRefraction", NodeMaterialBlockConnectionPointTypes.Float, !0, NodeMaterialBlockTargets.Fragment),
        r.registerOutput("refraction", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("refraction",r,NodeMaterialConnectionPointDirection.Output,e,"RefractionBlock")),
        r
    }
    return e.prototype.initialize = function(t) {
        t._excludeVariableName("vRefractionPosition"),
        t._excludeVariableName("vRefractionSize")
    }
    ,
    e.prototype.getClassName = function() {
        return "RefractionBlock"
    }
    ,
    Object.defineProperty(e.prototype, "intensity", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "tintAtDistance", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "volumeIndexOfRefraction", {
        get: function() {
            return this._inputs[2]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "view", {
        get: function() {
            return this.viewConnectionPoint
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "refraction", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "hasTexture", {
        get: function() {
            return !!this._getTexture()
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._getTexture = function() {
        return this.texture ? this.texture : this._scene.environmentTexture
    }
    ,
    e.prototype.autoConfigure = function(t) {
        if (!this.intensity.isConnected) {
            var r = new InputBlock("Refraction intensity",NodeMaterialBlockTargets.Fragment,NodeMaterialBlockConnectionPointTypes.Float);
            r.value = 1,
            r.output.connectTo(this.intensity)
        }
        if (this.view && !this.view.isConnected) {
            var n = t.getInputBlockByPredicate(function(o) {
                return o.systemValue === NodeMaterialSystemValues.View
            });
            n || (n = new InputBlock("view"),
            n.setAsSystemValue(NodeMaterialSystemValues.View)),
            n.output.connectTo(this.view)
        }
    }
    ,
    e.prototype.prepareDefines = function(t, r, n) {
        i.prototype.prepareDefines.call(this, t, r, n);
        var o = this._getTexture()
          , a = o && o.getTextureMatrix;
        n.setValue("SS_REFRACTION", a, !0),
        a && (n.setValue(this._define3DName, o.isCube, !0),
        n.setValue(this._defineLODRefractionAlpha, o.lodLevelInAlpha, !0),
        n.setValue(this._defineLinearSpecularRefraction, o.linearSpecularLOD, !0),
        n.setValue(this._defineOppositeZ, this._scene.useRightHandedSystem ? !o.invertZ : o.invertZ, !0),
        n.setValue("SS_LINKREFRACTIONTOTRANSPARENCY", this.linkRefractionWithTransparency, !0),
        n.setValue("SS_GAMMAREFRACTION", o.gammaSpace, !0),
        n.setValue("SS_RGBDREFRACTION", o.isRGBD, !0),
        n.setValue("SS_USE_LOCAL_REFRACTIONMAP_CUBIC", !!o.boundingBoxSize, !0),
        n.setValue("SS_USE_THICKNESS_AS_DEPTH", this.useThicknessAsDepth, !0))
    }
    ,
    e.prototype.isReady = function() {
        var t = this._getTexture();
        return !(t && !t.isReadyOrNotBlocking())
    }
    ,
    e.prototype.bind = function(t, r, n, o) {
        var a, s, l, u;
        i.prototype.bind.call(this, t, r, n);
        var c = this._getTexture();
        if (!!c) {
            c.isCube ? t.setTexture(this._cubeSamplerName, c) : t.setTexture(this._2DSamplerName, c),
            t.setMatrix(this._refractionMatrixName, c.getReflectionTextureMatrix());
            var h = 1;
            c.isCube || c.depth && (h = c.depth);
            var f = (u = (s = (a = this.volumeIndexOfRefraction.connectInputBlock) === null || a === void 0 ? void 0 : a.value) !== null && s !== void 0 ? s : (l = this.indexOfRefractionConnectionPoint.connectInputBlock) === null || l === void 0 ? void 0 : l.value) !== null && u !== void 0 ? u : 1.5;
            t.setFloat4(this._vRefractionInfosName, c.level, 1 / f, h, this.invertRefractionY ? -1 : 1),
            t.setFloat4(this._vRefractionMicrosurfaceInfosName, c.getSize().width, c.lodGenerationScale, c.lodGenerationOffset, 1 / f);
            var d = c.getSize().width;
            if (t.setFloat2(this._vRefractionFilteringInfoName, d, Scalar.Log2(d)),
            c.boundingBoxSize) {
                var _ = c;
                t.setVector3("vRefractionPosition", _.boundingBoxPosition),
                t.setVector3("vRefractionSize", _.boundingBoxSize)
            }
        }
    }
    ,
    e.prototype.getCode = function(t) {
        var r = "";
        return t.sharedData.blockingBlocks.push(this),
        t.sharedData.textureBlocks.push(this),
        this._cubeSamplerName = t._getFreeVariableName(this.name + "CubeSampler"),
        t.samplers.push(this._cubeSamplerName),
        this._2DSamplerName = t._getFreeVariableName(this.name + "2DSampler"),
        t.samplers.push(this._2DSamplerName),
        this._define3DName = t._getFreeDefineName("SS_REFRACTIONMAP_3D"),
        t._samplerDeclaration += "#ifdef " + this._define3DName + `\r
`,
        t._samplerDeclaration += "uniform samplerCube " + this._cubeSamplerName + `;\r
`,
        t._samplerDeclaration += `#else\r
`,
        t._samplerDeclaration += "uniform sampler2D " + this._2DSamplerName + `;\r
`,
        t._samplerDeclaration += `#endif\r
`,
        t.sharedData.blocksWithDefines.push(this),
        t.sharedData.bindableBlocks.push(this),
        this._defineLODRefractionAlpha = t._getFreeDefineName("SS_LODINREFRACTIONALPHA"),
        this._defineLinearSpecularRefraction = t._getFreeDefineName("SS_LINEARSPECULARREFRACTION"),
        this._defineOppositeZ = t._getFreeDefineName("SS_REFRACTIONMAP_OPPOSITEZ"),
        this._refractionMatrixName = t._getFreeVariableName("refractionMatrix"),
        t._emitUniformFromString(this._refractionMatrixName, "mat4"),
        t._emitFunction("sampleRefraction", `
            #ifdef ` + this._define3DName + `
                #define sampleRefraction(s, c) textureCube(s, c)
            #else
                #define sampleRefraction(s, c) texture2D(s, c)
            #endif\r
`, "//" + this.name),
        t._emitFunction("sampleRefractionLod", `
            #ifdef ` + this._define3DName + `
                #define sampleRefractionLod(s, c, l) textureCubeLodEXT(s, c, l)
            #else
                #define sampleRefractionLod(s, c, l) texture2DLodEXT(s, c, l)
            #endif\r
`, "//" + this.name),
        this._vRefractionMicrosurfaceInfosName = t._getFreeVariableName("vRefractionMicrosurfaceInfos"),
        t._emitUniformFromString(this._vRefractionMicrosurfaceInfosName, "vec4"),
        this._vRefractionInfosName = t._getFreeVariableName("vRefractionInfos"),
        t._emitUniformFromString(this._vRefractionInfosName, "vec4"),
        this._vRefractionFilteringInfoName = t._getFreeVariableName("vRefractionFilteringInfo"),
        t._emitUniformFromString(this._vRefractionFilteringInfoName, "vec2"),
        t._emitUniformFromString("vRefractionPosition", "vec3"),
        t._emitUniformFromString("vRefractionSize", "vec3"),
        r
    }
    ,
    e.prototype._buildBlock = function(t) {
        return this._scene = t.sharedData.scene,
        this
    }
    ,
    e.prototype._dumpPropertiesCode = function() {
        var t = i.prototype._dumpPropertiesCode.call(this);
        return this.texture && (this.texture.isCube ? t = this._codeVariableName + '.texture = new BABYLON.CubeTexture("' + this.texture.name + `");\r
` : t = this._codeVariableName + '.texture = new BABYLON.Texture("' + this.texture.name + `");\r
`,
        t += this._codeVariableName + ".texture.coordinatesMode = " + this.texture.coordinatesMode + `;\r
`),
        t += this._codeVariableName + ".linkRefractionWithTransparency = " + this.linkRefractionWithTransparency + `;\r
`,
        t += this._codeVariableName + ".invertRefractionY = " + this.invertRefractionY + `;\r
`,
        t += this._codeVariableName + ".useThicknessAsDepth = " + this.useThicknessAsDepth + `;\r
`,
        t
    }
    ,
    e.prototype.serialize = function() {
        var t = i.prototype.serialize.call(this);
        return this.texture && !this.texture.isRenderTarget && (t.texture = this.texture.serialize()),
        t.linkRefractionWithTransparency = this.linkRefractionWithTransparency,
        t.invertRefractionY = this.invertRefractionY,
        t.useThicknessAsDepth = this.useThicknessAsDepth,
        t
    }
    ,
    e.prototype._deserialize = function(t, r, n) {
        i.prototype._deserialize.call(this, t, r, n),
        t.texture && (n = t.texture.url.indexOf("data:") === 0 ? "" : n,
        t.texture.isCube ? this.texture = CubeTexture.Parse(t.texture, r, n) : this.texture = Texture.Parse(t.texture, r, n)),
        this.linkRefractionWithTransparency = t.linkRefractionWithTransparency,
        this.invertRefractionY = t.invertRefractionY,
        this.useThicknessAsDepth = !!t.useThicknessAsDepth
    }
    ,
    __decorate([editableInPropertyPage("Link refraction to transparency", PropertyTypeForEdition.Boolean, "ADVANCED", {
        notifiers: {
            update: !0
        }
    })], e.prototype, "linkRefractionWithTransparency", void 0),
    __decorate([editableInPropertyPage("Invert refraction Y", PropertyTypeForEdition.Boolean, "ADVANCED", {
        notifiers: {
            update: !0
        }
    })], e.prototype, "invertRefractionY", void 0),
    __decorate([editableInPropertyPage("Use thickness as depth", PropertyTypeForEdition.Boolean, "ADVANCED", {
        notifiers: {
            update: !0
        }
    })], e.prototype, "useThicknessAsDepth", void 0),
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.RefractionBlock", RefractionBlock);
var SubSurfaceBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Fragment) || this;
        return r._isUnique = !0,
        r.registerInput("thickness", NodeMaterialBlockConnectionPointTypes.Float, !1, NodeMaterialBlockTargets.Fragment),
        r.registerInput("tintColor", NodeMaterialBlockConnectionPointTypes.Color3, !0, NodeMaterialBlockTargets.Fragment),
        r.registerInput("translucencyIntensity", NodeMaterialBlockConnectionPointTypes.Float, !0, NodeMaterialBlockTargets.Fragment),
        r.registerInput("translucencyDiffusionDist", NodeMaterialBlockConnectionPointTypes.Color3, !0, NodeMaterialBlockTargets.Fragment),
        r.registerInput("refraction", NodeMaterialBlockConnectionPointTypes.Object, !0, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("refraction",r,NodeMaterialConnectionPointDirection.Input,RefractionBlock,"RefractionBlock")),
        r.registerOutput("subsurface", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("subsurface",r,NodeMaterialConnectionPointDirection.Output,e,"SubSurfaceBlock")),
        r
    }
    return e.prototype.initialize = function(t) {
        t._excludeVariableName("subSurfaceOut"),
        t._excludeVariableName("vThicknessParam"),
        t._excludeVariableName("vTintColor"),
        t._excludeVariableName("vSubSurfaceIntensity")
    }
    ,
    e.prototype.getClassName = function() {
        return "SubSurfaceBlock"
    }
    ,
    Object.defineProperty(e.prototype, "thickness", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "tintColor", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "translucencyIntensity", {
        get: function() {
            return this._inputs[2]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "translucencyDiffusionDist", {
        get: function() {
            return this._inputs[3]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "refraction", {
        get: function() {
            return this._inputs[4]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "subsurface", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.autoConfigure = function(t) {
        if (!this.thickness.isConnected) {
            var r = new InputBlock("SubSurface thickness",NodeMaterialBlockTargets.Fragment,NodeMaterialBlockConnectionPointTypes.Float);
            r.value = 0,
            r.output.connectTo(this.thickness)
        }
    }
    ,
    e.prototype.prepareDefines = function(t, r, n) {
        i.prototype.prepareDefines.call(this, t, r, n);
        var o = this.translucencyDiffusionDist.isConnected || this.translucencyIntensity.isConnected;
        n.setValue("SUBSURFACE", o || this.refraction.isConnected, !0),
        n.setValue("SS_TRANSLUCENCY", o, !0),
        n.setValue("SS_THICKNESSANDMASK_TEXTURE", !1, !0),
        n.setValue("SS_REFRACTIONINTENSITY_TEXTURE", !1, !0),
        n.setValue("SS_TRANSLUCENCYINTENSITY_TEXTURE", !1, !0),
        n.setValue("SS_MASK_FROM_THICKNESS_TEXTURE", !1, !0),
        n.setValue("SS_USE_GLTF_TEXTURES", !1, !0)
    }
    ,
    e.GetCode = function(t, r, n, o) {
        var a, s, l, u, c, h, f, d, _, g, m, v, y, b, T, C, A = "", S = r != null && r.thickness.isConnected ? r.thickness.associatedVariableName : "0.", P = r != null && r.tintColor.isConnected ? r.tintColor.associatedVariableName : "vec3(1.)", R = r != null && r.translucencyIntensity.isConnected ? r == null ? void 0 : r.translucencyIntensity.associatedVariableName : "1.", M = r != null && r.translucencyDiffusionDist.isConnected ? r == null ? void 0 : r.translucencyDiffusionDist.associatedVariableName : "vec3(1.)", x = r != null && r.refraction.isConnected ? (a = r == null ? void 0 : r.refraction.connectedPoint) === null || a === void 0 ? void 0 : a.ownerBlock : null, I = x != null && x.tintAtDistance.isConnected ? x.tintAtDistance.associatedVariableName : "1.", w = x != null && x.intensity.isConnected ? x.intensity.associatedVariableName : "1.", O = x != null && x.view.isConnected ? x.view.associatedVariableName : "";
        return A += (s = x == null ? void 0 : x.getCode(t)) !== null && s !== void 0 ? s : "",
        A += `subSurfaceOutParams subSurfaceOut;

        #ifdef SUBSURFACE
            vec2 vThicknessParam = vec2(0., ` + S + `);
            vec4 vTintColor = vec4(` + P + ", " + I + `);
            vec3 vSubSurfaceIntensity = vec3(` + w + ", " + R + `, 0.);

            subSurfaceBlock(
                vSubSurfaceIntensity,
                vThicknessParam,
                vTintColor,
                normalW,
                specularEnvironmentReflectance,
            #ifdef SS_THICKNESSANDMASK_TEXTURE
                vec4(0.),
            #endif
            #ifdef REFLECTION
                #ifdef SS_TRANSLUCENCY
                    ` + (n == null ? void 0 : n._reflectionMatrixName) + `,
                    #ifdef USESPHERICALFROMREFLECTIONMAP
                        #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)
                            reflectionOut.irradianceVector,
                        #endif
                        #if defined(REALTIME_FILTERING)
                            ` + (n == null ? void 0 : n._cubeSamplerName) + `,
                            ` + (n == null ? void 0 : n._vReflectionFilteringInfoName) + `,
                        #endif
                        #endif
                    #ifdef USEIRRADIANCEMAP
                        irradianceSampler,
                    #endif
                #endif
            #endif
            #if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY)
                surfaceAlbedo,
            #endif
            #ifdef SS_REFRACTION
                ` + o + `.xyz,
                viewDirectionW,
                ` + O + `,
                ` + ((l = x == null ? void 0 : x._vRefractionInfosName) !== null && l !== void 0 ? l : "") + `,
                ` + ((u = x == null ? void 0 : x._refractionMatrixName) !== null && u !== void 0 ? u : "") + `,
                ` + ((c = x == null ? void 0 : x._vRefractionMicrosurfaceInfosName) !== null && c !== void 0 ? c : "") + `,
                vLightingIntensity,
                #ifdef SS_LINKREFRACTIONTOTRANSPARENCY
                    alpha,
                #endif
                #ifdef ` + ((h = x == null ? void 0 : x._defineLODRefractionAlpha) !== null && h !== void 0 ? h : "IGNORE") + `
                    NdotVUnclamped,
                #endif
                #ifdef ` + ((f = x == null ? void 0 : x._defineLinearSpecularRefraction) !== null && f !== void 0 ? f : "IGNORE") + `
                    roughness,
                #endif
                alphaG,
                #ifdef ` + ((d = x == null ? void 0 : x._define3DName) !== null && d !== void 0 ? d : "IGNORE") + `
                    ` + ((_ = x == null ? void 0 : x._cubeSamplerName) !== null && _ !== void 0 ? _ : "") + `,
                #else
                    ` + ((g = x == null ? void 0 : x._2DSamplerName) !== null && g !== void 0 ? g : "") + `,
                #endif
                #ifndef LODBASEDMICROSFURACE
                    #ifdef ` + ((m = x == null ? void 0 : x._define3DName) !== null && m !== void 0 ? m : "IGNORE") + `
                        ` + ((v = x == null ? void 0 : x._cubeSamplerName) !== null && v !== void 0 ? v : "") + `,
                        ` + ((y = x == null ? void 0 : x._cubeSamplerName) !== null && y !== void 0 ? y : "") + `,
                    #else
                        ` + ((b = x == null ? void 0 : x._2DSamplerName) !== null && b !== void 0 ? b : "") + `,
                        ` + ((T = x == null ? void 0 : x._2DSamplerName) !== null && T !== void 0 ? T : "") + `,
                    #endif
                #endif
                #ifdef ANISOTROPIC
                    anisotropicOut,
                #endif
                #ifdef REALTIME_FILTERING
                    ` + ((C = x == null ? void 0 : x._vRefractionFilteringInfoName) !== null && C !== void 0 ? C : "") + `,
                #endif
                #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC
                    vRefractionPosition,
                    vRefractionSize,
                #endif
            #endif
            #ifdef SS_TRANSLUCENCY
                ` + M + `,
            #endif
                subSurfaceOut
            );

            #ifdef SS_REFRACTION
                surfaceAlbedo = subSurfaceOut.surfaceAlbedo;
                #ifdef SS_LINKREFRACTIONTOTRANSPARENCY
                    alpha = subSurfaceOut.alpha;
                #endif
            #endif
        #else
            subSurfaceOut.specularEnvironmentReflectance = specularEnvironmentReflectance;
        #endif\r
`,
        A
    }
    ,
    e.prototype._buildBlock = function(t) {
        return t.target === NodeMaterialBlockTargets.Fragment && t.sharedData.blocksWithDefines.push(this),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.SubSurfaceBlock", SubSurfaceBlock);
var mapOutputToVariable = {
    ambientClr: ["finalAmbient", ""],
    diffuseDir: ["finalDiffuse", ""],
    specularDir: ["finalSpecularScaled", "!defined(UNLIT) && defined(SPECULARTERM)"],
    clearcoatDir: ["finalClearCoatScaled", "!defined(UNLIT) && defined(CLEARCOAT)"],
    sheenDir: ["finalSheenScaled", "!defined(UNLIT) && defined(SHEEN)"],
    diffuseInd: ["finalIrradiance", "!defined(UNLIT) && defined(REFLECTION)"],
    specularInd: ["finalRadianceScaled", "!defined(UNLIT) && defined(REFLECTION)"],
    clearcoatInd: ["clearcoatOut.finalClearCoatRadianceScaled", "!defined(UNLIT) && defined(REFLECTION) && defined(CLEARCOAT)"],
    sheenInd: ["sheenOut.finalSheenRadianceScaled", "!defined(UNLIT) && defined(REFLECTION) && defined(SHEEN) && defined(ENVIRONMENTBRDF)"],
    refraction: ["subSurfaceOut.finalRefraction", "!defined(UNLIT) && defined(SS_REFRACTION)"],
    lighting: ["finalColor.rgb", ""],
    shadow: ["shadow", ""],
    alpha: ["alpha", ""]
}
  , PBRMetallicRoughnessBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.VertexAndFragment) || this;
        return r._environmentBRDFTexture = null,
        r._metallicReflectanceColor = Color3.White(),
        r._metallicF0Factor = 1,
        r.directIntensity = 1,
        r.environmentIntensity = 1,
        r.specularIntensity = 1,
        r.lightFalloff = 0,
        r.useAlphaTest = !1,
        r.alphaTestCutoff = .5,
        r.useAlphaBlending = !1,
        r.useRadianceOverAlpha = !0,
        r.useSpecularOverAlpha = !0,
        r.enableSpecularAntiAliasing = !1,
        r.realTimeFiltering = !1,
        r.realTimeFilteringQuality = 8,
        r.useEnergyConservation = !0,
        r.useRadianceOcclusion = !0,
        r.useHorizonOcclusion = !0,
        r.unlit = !1,
        r.forceNormalForward = !1,
        r.debugMode = 0,
        r.debugLimit = 0,
        r.debugFactor = 1,
        r._isUnique = !0,
        r.registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes.Vector4, !1, NodeMaterialBlockTargets.Vertex),
        r.registerInput("worldNormal", NodeMaterialBlockConnectionPointTypes.Vector4, !1, NodeMaterialBlockTargets.Fragment),
        r.registerInput("view", NodeMaterialBlockConnectionPointTypes.Matrix, !1),
        r.registerInput("cameraPosition", NodeMaterialBlockConnectionPointTypes.Vector3, !1, NodeMaterialBlockTargets.Fragment),
        r.registerInput("perturbedNormal", NodeMaterialBlockConnectionPointTypes.Vector4, !0, NodeMaterialBlockTargets.Fragment),
        r.registerInput("baseColor", NodeMaterialBlockConnectionPointTypes.Color3, !0, NodeMaterialBlockTargets.Fragment),
        r.registerInput("metallic", NodeMaterialBlockConnectionPointTypes.Float, !1, NodeMaterialBlockTargets.Fragment),
        r.registerInput("roughness", NodeMaterialBlockConnectionPointTypes.Float, !1, NodeMaterialBlockTargets.Fragment),
        r.registerInput("ambientOcc", NodeMaterialBlockConnectionPointTypes.Float, !0, NodeMaterialBlockTargets.Fragment),
        r.registerInput("opacity", NodeMaterialBlockConnectionPointTypes.Float, !0, NodeMaterialBlockTargets.Fragment),
        r.registerInput("indexOfRefraction", NodeMaterialBlockConnectionPointTypes.Float, !0, NodeMaterialBlockTargets.Fragment),
        r.registerInput("ambientColor", NodeMaterialBlockConnectionPointTypes.Color3, !0, NodeMaterialBlockTargets.Fragment),
        r.registerInput("reflection", NodeMaterialBlockConnectionPointTypes.Object, !0, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("reflection",r,NodeMaterialConnectionPointDirection.Input,ReflectionBlock,"ReflectionBlock")),
        r.registerInput("clearcoat", NodeMaterialBlockConnectionPointTypes.Object, !0, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("clearcoat",r,NodeMaterialConnectionPointDirection.Input,ClearCoatBlock,"ClearCoatBlock")),
        r.registerInput("sheen", NodeMaterialBlockConnectionPointTypes.Object, !0, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("sheen",r,NodeMaterialConnectionPointDirection.Input,SheenBlock,"SheenBlock")),
        r.registerInput("subsurface", NodeMaterialBlockConnectionPointTypes.Object, !0, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("subsurface",r,NodeMaterialConnectionPointDirection.Input,SubSurfaceBlock,"SubSurfaceBlock")),
        r.registerInput("anisotropy", NodeMaterialBlockConnectionPointTypes.Object, !0, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("anisotropy",r,NodeMaterialConnectionPointDirection.Input,AnisotropyBlock,"AnisotropyBlock")),
        r.registerOutput("ambientClr", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment),
        r.registerOutput("diffuseDir", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment),
        r.registerOutput("specularDir", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment),
        r.registerOutput("clearcoatDir", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment),
        r.registerOutput("sheenDir", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment),
        r.registerOutput("diffuseInd", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment),
        r.registerOutput("specularInd", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment),
        r.registerOutput("clearcoatInd", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment),
        r.registerOutput("sheenInd", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment),
        r.registerOutput("refraction", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment),
        r.registerOutput("lighting", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment),
        r.registerOutput("shadow", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment),
        r.registerOutput("alpha", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment),
        r
    }
    return e.prototype.initialize = function(t) {
        t._excludeVariableName("vLightingIntensity"),
        t._excludeVariableName("geometricNormalW"),
        t._excludeVariableName("normalW"),
        t._excludeVariableName("faceNormal"),
        t._excludeVariableName("albedoOpacityOut"),
        t._excludeVariableName("surfaceAlbedo"),
        t._excludeVariableName("alpha"),
        t._excludeVariableName("aoOut"),
        t._excludeVariableName("baseColor"),
        t._excludeVariableName("reflectivityOut"),
        t._excludeVariableName("microSurface"),
        t._excludeVariableName("roughness"),
        t._excludeVariableName("NdotVUnclamped"),
        t._excludeVariableName("NdotV"),
        t._excludeVariableName("alphaG"),
        t._excludeVariableName("AARoughnessFactors"),
        t._excludeVariableName("environmentBrdf"),
        t._excludeVariableName("ambientMonochrome"),
        t._excludeVariableName("seo"),
        t._excludeVariableName("eho"),
        t._excludeVariableName("environmentRadiance"),
        t._excludeVariableName("irradianceVector"),
        t._excludeVariableName("environmentIrradiance"),
        t._excludeVariableName("diffuseBase"),
        t._excludeVariableName("specularBase"),
        t._excludeVariableName("preInfo"),
        t._excludeVariableName("info"),
        t._excludeVariableName("shadow"),
        t._excludeVariableName("finalDiffuse"),
        t._excludeVariableName("finalAmbient"),
        t._excludeVariableName("ambientOcclusionForDirectDiffuse"),
        t._excludeVariableName("finalColor"),
        t._excludeVariableName("vClipSpacePosition"),
        t._excludeVariableName("vDebugMode")
    }
    ,
    e.prototype.getClassName = function() {
        return "PBRMetallicRoughnessBlock"
    }
    ,
    Object.defineProperty(e.prototype, "worldPosition", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "worldNormal", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "view", {
        get: function() {
            return this._inputs[2]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cameraPosition", {
        get: function() {
            return this._inputs[3]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "perturbedNormal", {
        get: function() {
            return this._inputs[4]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "baseColor", {
        get: function() {
            return this._inputs[5]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "metallic", {
        get: function() {
            return this._inputs[6]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "roughness", {
        get: function() {
            return this._inputs[7]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "ambientOcc", {
        get: function() {
            return this._inputs[8]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "opacity", {
        get: function() {
            return this._inputs[9]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "indexOfRefraction", {
        get: function() {
            return this._inputs[10]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "ambientColor", {
        get: function() {
            return this._inputs[11]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "reflection", {
        get: function() {
            return this._inputs[12]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "clearcoat", {
        get: function() {
            return this._inputs[13]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "sheen", {
        get: function() {
            return this._inputs[14]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "subsurface", {
        get: function() {
            return this._inputs[15]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "anisotropy", {
        get: function() {
            return this._inputs[16]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "ambientClr", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "diffuseDir", {
        get: function() {
            return this._outputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "specularDir", {
        get: function() {
            return this._outputs[2]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "clearcoatDir", {
        get: function() {
            return this._outputs[3]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "sheenDir", {
        get: function() {
            return this._outputs[4]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "diffuseInd", {
        get: function() {
            return this._outputs[5]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "specularInd", {
        get: function() {
            return this._outputs[6]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "clearcoatInd", {
        get: function() {
            return this._outputs[7]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "sheenInd", {
        get: function() {
            return this._outputs[8]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "refraction", {
        get: function() {
            return this._outputs[9]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "lighting", {
        get: function() {
            return this._outputs[10]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "shadow", {
        get: function() {
            return this._outputs[11]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "alpha", {
        get: function() {
            return this._outputs[12]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.autoConfigure = function(t) {
        if (!this.cameraPosition.isConnected) {
            var r = t.getInputBlockByPredicate(function(o) {
                return o.systemValue === NodeMaterialSystemValues.CameraPosition
            });
            r || (r = new InputBlock("cameraPosition"),
            r.setAsSystemValue(NodeMaterialSystemValues.CameraPosition)),
            r.output.connectTo(this.cameraPosition)
        }
        if (!this.view.isConnected) {
            var n = t.getInputBlockByPredicate(function(o) {
                return o.systemValue === NodeMaterialSystemValues.View
            });
            n || (n = new InputBlock("view"),
            n.setAsSystemValue(NodeMaterialSystemValues.View)),
            n.output.connectTo(this.view)
        }
    }
    ,
    e.prototype.prepareDefines = function(t, r, n) {
        n.setValue("PBR", !0),
        n.setValue("METALLICWORKFLOW", !0),
        n.setValue("DEBUGMODE", this.debugMode, !0),
        n.setValue("NORMALXYSCALE", !0),
        n.setValue("BUMP", this.perturbedNormal.isConnected, !0),
        n.setValue("LODBASEDMICROSFURACE", this._scene.getEngine().getCaps().textureLOD),
        n.setValue("ALBEDO", !1, !0),
        n.setValue("OPACITY", this.opacity.isConnected, !0),
        n.setValue("AMBIENT", !0, !0),
        n.setValue("AMBIENTINGRAYSCALE", !1, !0),
        n.setValue("REFLECTIVITY", !1, !0),
        n.setValue("AOSTOREINMETALMAPRED", !1, !0),
        n.setValue("METALLNESSSTOREINMETALMAPBLUE", !1, !0),
        n.setValue("ROUGHNESSSTOREINMETALMAPALPHA", !1, !0),
        n.setValue("ROUGHNESSSTOREINMETALMAPGREEN", !1, !0),
        this.lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD ? (n.setValue("USEPHYSICALLIGHTFALLOFF", !1),
        n.setValue("USEGLTFLIGHTFALLOFF", !1)) : this.lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF ? (n.setValue("USEPHYSICALLIGHTFALLOFF", !1),
        n.setValue("USEGLTFLIGHTFALLOFF", !0)) : (n.setValue("USEPHYSICALLIGHTFALLOFF", !0),
        n.setValue("USEGLTFLIGHTFALLOFF", !1));
        var o = this.alphaTestCutoff.toString();
        n.setValue("ALPHABLEND", this.useAlphaBlending, !0),
        n.setValue("ALPHAFROMALBEDO", !1, !0),
        n.setValue("ALPHATEST", this.useAlphaTest, !0),
        n.setValue("ALPHATESTVALUE", o.indexOf(".") < 0 ? o + "." : o, !0),
        n.setValue("OPACITYRGB", !1, !0),
        n.setValue("RADIANCEOVERALPHA", this.useRadianceOverAlpha, !0),
        n.setValue("SPECULAROVERALPHA", this.useSpecularOverAlpha, !0),
        n.setValue("SPECULARAA", this._scene.getEngine().getCaps().standardDerivatives && this.enableSpecularAntiAliasing, !0),
        n.setValue("REALTIME_FILTERING", this.realTimeFiltering, !0);
        var a = t.getScene();
        if (a.getEngine()._features.needTypeSuffixInShaderConstants ? n.setValue("NUM_SAMPLES", this.realTimeFilteringQuality + "u", !0) : n.setValue("NUM_SAMPLES", "" + this.realTimeFilteringQuality, !0),
        n.setValue("BRDF_V_HEIGHT_CORRELATED", !0),
        n.setValue("MS_BRDF_ENERGY_CONSERVATION", this.useEnergyConservation, !0),
        n.setValue("RADIANCEOCCLUSION", this.useRadianceOcclusion, !0),
        n.setValue("HORIZONOCCLUSION", this.useHorizonOcclusion, !0),
        n.setValue("UNLIT", this.unlit, !0),
        n.setValue("FORCENORMALFORWARD", this.forceNormalForward, !0),
        this._environmentBRDFTexture && MaterialFlags.ReflectionTextureEnabled ? (n.setValue("ENVIRONMENTBRDF", !0),
        n.setValue("ENVIRONMENTBRDF_RGBD", this._environmentBRDFTexture.isRGBD, !0)) : (n.setValue("ENVIRONMENTBRDF", !1),
        n.setValue("ENVIRONMENTBRDF_RGBD", !1)),
        n._areImageProcessingDirty && r.imageProcessingConfiguration && r.imageProcessingConfiguration.prepareDefines(n),
        !!n._areLightsDirty)
            if (!this.light)
                MaterialHelper.PrepareDefinesForLights(a, t, n, !0, r.maxSimultaneousLights),
                n._needNormals = !0,
                MaterialHelper.PrepareDefinesForMultiview(a, n);
            else {
                var s = {
                    needNormals: !1,
                    needRebuild: !1,
                    lightmapMode: !1,
                    shadowEnabled: !1,
                    specularEnabled: !1
                };
                MaterialHelper.PrepareDefinesForLight(a, t, this.light, this._lightId, n, !0, s),
                s.needRebuild && n.rebuild()
            }
    }
    ,
    e.prototype.updateUniformsAndSamples = function(t, r, n, o) {
        for (var a = 0; a < r.maxSimultaneousLights && n["LIGHT" + a]; a++) {
            var s = t.uniforms.indexOf("vLightData" + a) >= 0;
            MaterialHelper.PrepareUniformsAndSamplersForLight(a, t.uniforms, t.samplers, n["PROJECTEDLIGHTTEXTURE" + a], o, s)
        }
    }
    ,
    e.prototype.isReady = function(t, r, n) {
        return !(this._environmentBRDFTexture && !this._environmentBRDFTexture.isReady() || n._areImageProcessingDirty && r.imageProcessingConfiguration && !r.imageProcessingConfiguration.isReady())
    }
    ,
    e.prototype.bind = function(t, r, n) {
        var o, a;
        if (!!n) {
            var s = n.getScene();
            this.light ? MaterialHelper.BindLight(this.light, this._lightId, s, t, !0) : MaterialHelper.BindLights(s, n, t, !0, r.maxSimultaneousLights),
            t.setTexture(this._environmentBrdfSamplerName, this._environmentBRDFTexture),
            t.setFloat2("vDebugMode", this.debugLimit, this.debugFactor);
            var l = this._scene.ambientColor;
            l && t.setColor3("ambientFromScene", l);
            var u = s.useRightHandedSystem === (s._mirroredCameraPosition != null);
            t.setFloat(this._invertNormalName, u ? -1 : 1),
            t.setFloat4("vLightingIntensity", this.directIntensity, 1, this.environmentIntensity * this._scene.environmentIntensity, this.specularIntensity);
            var c = 1
              , h = (a = (o = this.indexOfRefraction.connectInputBlock) === null || o === void 0 ? void 0 : o.value) !== null && a !== void 0 ? a : 1.5
              , f = Math.pow((h - c) / (h + c), 2);
            this._metallicReflectanceColor.scaleToRef(f * this._metallicF0Factor, TmpColors.Color3[0]);
            var d = this._metallicF0Factor;
            t.setColor4(this._vMetallicReflectanceFactorsName, TmpColors.Color3[0], d),
            r.imageProcessingConfiguration && r.imageProcessingConfiguration.bind(t)
        }
    }
    ,
    e.prototype._injectVertexCode = function(t) {
        var r, n, o = this.worldPosition, a = "//" + this.name;
        this.light ? (this._lightId = (t.counters.lightCounter !== void 0 ? t.counters.lightCounter : -1) + 1,
        t.counters.lightCounter = this._lightId,
        t._emitFunctionFromInclude(t.supportUniformBuffers ? "lightVxUboDeclaration" : "lightVxFragmentDeclaration", a, {
            replaceStrings: [{
                search: /{X}/g,
                replace: this._lightId.toString()
            }]
        }, this._lightId.toString())) : (t._emitFunctionFromInclude(t.supportUniformBuffers ? "lightVxUboDeclaration" : "lightVxFragmentDeclaration", a, {
            repeatKey: "maxSimultaneousLights"
        }),
        this._lightId = 0,
        t.sharedData.dynamicUniformBlocks.push(this));
        var s = "v_" + o.associatedVariableName;
        t._emitVaryingFromString(s, "vec4") && (t.compilationString += s + " = " + o.associatedVariableName + `;\r
`);
        var l = this.reflection.isConnected ? (r = this.reflection.connectedPoint) === null || r === void 0 ? void 0 : r.ownerBlock : null;
        l && (l.viewConnectionPoint = this.view),
        t.compilationString += (n = l == null ? void 0 : l.handleVertexSide(t)) !== null && n !== void 0 ? n : "",
        t._emitUniformFromString("vDebugMode", "vec2", "defined(IGNORE) || DEBUGMODE > 0"),
        t._emitUniformFromString("ambientFromScene", "vec3"),
        t._emitVaryingFromString("vClipSpacePosition", "vec4", "defined(IGNORE) || DEBUGMODE > 0") && (t._injectAtEnd += `#if DEBUGMODE > 0\r
`,
        t._injectAtEnd += `vClipSpacePosition = gl_Position;\r
`,
        t._injectAtEnd += `#endif\r
`),
        this.light ? t.compilationString += t._emitCodeFromInclude("shadowsVertex", a, {
            replaceStrings: [{
                search: /{X}/g,
                replace: this._lightId.toString()
            }, {
                search: /worldPos/g,
                replace: o.associatedVariableName
            }]
        }) : (t.compilationString += "vec4 worldPos = " + o.associatedVariableName + `;\r
`,
        this.view.isConnected && (t.compilationString += "mat4 view = " + this.view.associatedVariableName + `;\r
`),
        t.compilationString += t._emitCodeFromInclude("shadowsVertex", a, {
            repeatKey: "maxSimultaneousLights"
        }))
    }
    ,
    e.prototype._getAlbedoOpacityCode = function() {
        var t = `albedoOpacityOutParams albedoOpacityOut;\r
`
          , r = this.baseColor.isConnected ? this.baseColor.associatedVariableName : "vec3(1.)"
          , n = this.opacity.isConnected ? this.opacity.associatedVariableName : "1.";
        return t += `albedoOpacityBlock(
                vec4(` + r + `, 1.),
            #ifdef ALBEDO
                vec4(1.),
                vec2(1., 1.),
            #endif
            #ifdef OPACITY
                vec4(` + n + `),
                vec2(1., 1.),
            #endif
                albedoOpacityOut
            );

            vec3 surfaceAlbedo = albedoOpacityOut.surfaceAlbedo;
            float alpha = albedoOpacityOut.alpha;\r
`,
        t
    }
    ,
    e.prototype._getAmbientOcclusionCode = function() {
        var t = `ambientOcclusionOutParams aoOut;\r
`
          , r = this.ambientOcc.isConnected ? this.ambientOcc.associatedVariableName : "1.";
        return t += `ambientOcclusionBlock(
            #ifdef AMBIENT
                vec3(` + r + `),
                vec4(0., 1.0, 1.0, 0.),
            #endif
                aoOut
            );\r
`,
        t
    }
    ,
    e.prototype._getReflectivityCode = function(t) {
        var r = `reflectivityOutParams reflectivityOut;\r
`
          , n = "1.";
        return this._vMetallicReflectanceFactorsName = t._getFreeVariableName("vMetallicReflectanceFactors"),
        t._emitUniformFromString(this._vMetallicReflectanceFactorsName, "vec4"),
        r += `vec3 baseColor = surfaceAlbedo;

            reflectivityBlock(
                vec4(` + this.metallic.associatedVariableName + ", " + this.roughness.associatedVariableName + `, 0., 0.),
            #ifdef METALLICWORKFLOW
                surfaceAlbedo,
                ` + this._vMetallicReflectanceFactorsName + `,
            #endif
            #ifdef REFLECTIVITY
                vec3(0., 0., ` + n + `),
                vec4(1.),
            #endif
            #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY)  && defined(AOSTOREINMETALMAPRED)
                aoOut.ambientOcclusionColor,
            #endif
            #ifdef MICROSURFACEMAP
                microSurfaceTexel, <== not handled!
            #endif
                reflectivityOut
            );

            float microSurface = reflectivityOut.microSurface;
            float roughness = reflectivityOut.roughness;

            #ifdef METALLICWORKFLOW
                surfaceAlbedo = reflectivityOut.surfaceAlbedo;
            #endif
            #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)
                aoOut.ambientOcclusionColor = reflectivityOut.ambientOcclusionColor;
            #endif\r
`,
        r
    }
    ,
    e.prototype._buildBlock = function(t) {
        var r, n, o, a, s, l, u, c, h, f, d, _, g, m, v, y, b, T, C, A, S, P, R, M, x, I, w, O, D, F, V, N, L, k, U, z, H, G, W, j;
        i.prototype._buildBlock.call(this, t),
        this._scene = t.sharedData.scene,
        this._environmentBRDFTexture || (this._environmentBRDFTexture = GetEnvironmentBRDFTexture(this._scene));
        var B = this.reflection.isConnected ? (r = this.reflection.connectedPoint) === null || r === void 0 ? void 0 : r.ownerBlock : null;
        if (B && (B.worldPositionConnectionPoint = this.worldPosition,
        B.cameraPositionConnectionPoint = this.cameraPosition,
        B.worldNormalConnectionPoint = this.worldNormal),
        t.target !== NodeMaterialBlockTargets.Fragment)
            return this._injectVertexCode(t),
            this;
        t.sharedData.forcedBindableBlocks.push(this),
        t.sharedData.blocksWithDefines.push(this),
        t.sharedData.blockingBlocks.push(this);
        var X = "//" + this.name
          , $ = "v_" + this.worldPosition.associatedVariableName
          , Y = this.perturbedNormal;
        this._environmentBrdfSamplerName = t._getFreeVariableName("environmentBrdfSampler"),
        t._emit2DSampler(this._environmentBrdfSamplerName),
        t.sharedData.hints.needAlphaBlending = t.sharedData.hints.needAlphaBlending || this.useAlphaBlending,
        t.sharedData.hints.needAlphaTesting = t.sharedData.hints.needAlphaTesting || this.useAlphaTest,
        t._emitExtension("lod", "#extension GL_EXT_shader_texture_lod : enable", "defined(LODBASEDMICROSFURACE)"),
        t._emitExtension("derivatives", "#extension GL_OES_standard_derivatives : enable"),
        t.uniforms.push("exposureLinear"),
        t.uniforms.push("contrast"),
        t.uniforms.push("vInverseScreenSize"),
        t.uniforms.push("vignetteSettings1"),
        t.uniforms.push("vignetteSettings2"),
        t.uniforms.push("vCameraColorCurveNegative"),
        t.uniforms.push("vCameraColorCurveNeutral"),
        t.uniforms.push("vCameraColorCurvePositive"),
        t.uniforms.push("txColorTransform"),
        t.uniforms.push("colorTransformSettings"),
        this.light ? t._emitFunctionFromInclude(t.supportUniformBuffers ? "lightUboDeclaration" : "lightFragmentDeclaration", X, {
            replaceStrings: [{
                search: /{X}/g,
                replace: this._lightId.toString()
            }]
        }, this._lightId.toString()) : t._emitFunctionFromInclude(t.supportUniformBuffers ? "lightUboDeclaration" : "lightFragmentDeclaration", X, {
            repeatKey: "maxSimultaneousLights"
        }),
        t._emitFunctionFromInclude("helperFunctions", X),
        t._emitFunctionFromInclude("importanceSampling", X),
        t._emitFunctionFromInclude("pbrHelperFunctions", X),
        t._emitFunctionFromInclude("imageProcessingDeclaration", X),
        t._emitFunctionFromInclude("imageProcessingFunctions", X),
        t._emitFunctionFromInclude("shadowsFragmentFunctions", X, {
            replaceStrings: [{
                search: /vPositionW/g,
                replace: $ + ".xyz"
            }]
        }),
        t._emitFunctionFromInclude("pbrDirectLightingSetupFunctions", X, {
            replaceStrings: [{
                search: /vPositionW/g,
                replace: $ + ".xyz"
            }]
        }),
        t._emitFunctionFromInclude("pbrDirectLightingFalloffFunctions", X),
        t._emitFunctionFromInclude("pbrBRDFFunctions", X, {
            replaceStrings: [{
                search: /REFLECTIONMAP_SKYBOX/g,
                replace: (n = B == null ? void 0 : B._defineSkyboxName) !== null && n !== void 0 ? n : "REFLECTIONMAP_SKYBOX"
            }]
        }),
        t._emitFunctionFromInclude("hdrFilteringFunctions", X),
        t._emitFunctionFromInclude("pbrDirectLightingFunctions", X, {
            replaceStrings: [{
                search: /vPositionW/g,
                replace: $ + ".xyz"
            }]
        }),
        t._emitFunctionFromInclude("pbrIBLFunctions", X),
        t._emitFunctionFromInclude("pbrBlockAlbedoOpacity", X),
        t._emitFunctionFromInclude("pbrBlockReflectivity", X),
        t._emitFunctionFromInclude("pbrBlockAmbientOcclusion", X),
        t._emitFunctionFromInclude("pbrBlockAlphaFresnel", X),
        t._emitFunctionFromInclude("pbrBlockAnisotropic", X),
        t._emitUniformFromString("vLightingIntensity", "vec4"),
        this._vNormalWName = t._getFreeVariableName("vNormalW"),
        t.compilationString += "vec4 " + this._vNormalWName + " = normalize(" + this.worldNormal.associatedVariableName + `);\r
`,
        t._registerTempVariable("viewDirectionW") && (t.compilationString += "vec3 viewDirectionW = normalize(" + this.cameraPosition.associatedVariableName + " - " + $ + `.xyz);\r
`),
        t.compilationString += "vec3 geometricNormalW = " + this._vNormalWName + `.xyz;\r
`,
        t.compilationString += "vec3 normalW = " + (Y.isConnected ? "normalize(" + Y.associatedVariableName + ".xyz)" : "geometricNormalW") + `;\r
`,
        this._invertNormalName = t._getFreeVariableName("invertNormal"),
        t._emitUniformFromString(this._invertNormalName, "float"),
        t.compilationString += t._emitCodeFromInclude("pbrBlockNormalFinal", X, {
            replaceStrings: [{
                search: /vPositionW/g,
                replace: $ + ".xyz"
            }, {
                search: /vEyePosition.w/g,
                replace: this._invertNormalName
            }]
        }),
        t.compilationString += this._getAlbedoOpacityCode(),
        t.compilationString += t._emitCodeFromInclude("depthPrePass", X),
        t.compilationString += this._getAmbientOcclusionCode(),
        t.compilationString += t._emitCodeFromInclude("pbrBlockLightmapInit", X),
        t.compilationString += `#ifdef UNLIT
                vec3 diffuseBase = vec3(1., 1., 1.);
            #else\r
`,
        t.compilationString += this._getReflectivityCode(t),
        t.compilationString += t._emitCodeFromInclude("pbrBlockGeometryInfo", X, {
            replaceStrings: [{
                search: /REFLECTIONMAP_SKYBOX/g,
                replace: (o = B == null ? void 0 : B._defineSkyboxName) !== null && o !== void 0 ? o : "REFLECTIONMAP_SKYBOX"
            }, {
                search: /REFLECTIONMAP_3D/g,
                replace: (a = B == null ? void 0 : B._define3DName) !== null && a !== void 0 ? a : "REFLECTIONMAP_3D"
            }]
        });
        var K = this.anisotropy.isConnected ? (s = this.anisotropy.connectedPoint) === null || s === void 0 ? void 0 : s.ownerBlock : null;
        K && (K.worldPositionConnectionPoint = this.worldPosition,
        K.worldNormalConnectionPoint = this.worldNormal,
        t.compilationString += K.getCode(t, !this.perturbedNormal.isConnected)),
        B && B.hasTexture && (t.compilationString += B.getCode(t, K ? "anisotropicOut.anisotropicNormal" : "normalW")),
        t._emitFunctionFromInclude("pbrBlockReflection", X, {
            replaceStrings: [{
                search: /computeReflectionCoords/g,
                replace: "computeReflectionCoordsPBR"
            }, {
                search: /REFLECTIONMAP_3D/g,
                replace: (l = B == null ? void 0 : B._define3DName) !== null && l !== void 0 ? l : "REFLECTIONMAP_3D"
            }, {
                search: /REFLECTIONMAP_OPPOSITEZ/g,
                replace: (u = B == null ? void 0 : B._defineOppositeZ) !== null && u !== void 0 ? u : "REFLECTIONMAP_OPPOSITEZ"
            }, {
                search: /REFLECTIONMAP_PROJECTION/g,
                replace: (c = B == null ? void 0 : B._defineProjectionName) !== null && c !== void 0 ? c : "REFLECTIONMAP_PROJECTION"
            }, {
                search: /REFLECTIONMAP_SKYBOX/g,
                replace: (h = B == null ? void 0 : B._defineSkyboxName) !== null && h !== void 0 ? h : "REFLECTIONMAP_SKYBOX"
            }, {
                search: /LODINREFLECTIONALPHA/g,
                replace: (f = B == null ? void 0 : B._defineLODReflectionAlpha) !== null && f !== void 0 ? f : "LODINREFLECTIONALPHA"
            }, {
                search: /LINEARSPECULARREFLECTION/g,
                replace: (d = B == null ? void 0 : B._defineLinearSpecularReflection) !== null && d !== void 0 ? d : "LINEARSPECULARREFLECTION"
            }, {
                search: /vReflectionFilteringInfo/g,
                replace: (_ = B == null ? void 0 : B._vReflectionFilteringInfoName) !== null && _ !== void 0 ? _ : "vReflectionFilteringInfo"
            }]
        }),
        t.compilationString += t._emitCodeFromInclude("pbrBlockReflectance0", X, {
            replaceStrings: [{
                search: /metallicReflectanceFactors/g,
                replace: this._vMetallicReflectanceFactorsName
            }]
        });
        var Z = this.sheen.isConnected ? (g = this.sheen.connectedPoint) === null || g === void 0 ? void 0 : g.ownerBlock : null;
        Z && (t.compilationString += Z.getCode(B)),
        t._emitFunctionFromInclude("pbrBlockSheen", X, {
            replaceStrings: [{
                search: /REFLECTIONMAP_3D/g,
                replace: (m = B == null ? void 0 : B._define3DName) !== null && m !== void 0 ? m : "REFLECTIONMAP_3D"
            }, {
                search: /REFLECTIONMAP_SKYBOX/g,
                replace: (v = B == null ? void 0 : B._defineSkyboxName) !== null && v !== void 0 ? v : "REFLECTIONMAP_SKYBOX"
            }, {
                search: /LODINREFLECTIONALPHA/g,
                replace: (y = B == null ? void 0 : B._defineLODReflectionAlpha) !== null && y !== void 0 ? y : "LODINREFLECTIONALPHA"
            }, {
                search: /LINEARSPECULARREFLECTION/g,
                replace: (b = B == null ? void 0 : B._defineLinearSpecularReflection) !== null && b !== void 0 ? b : "LINEARSPECULARREFLECTION"
            }]
        });
        var q = this.clearcoat.isConnected ? (T = this.clearcoat.connectedPoint) === null || T === void 0 ? void 0 : T.ownerBlock : null
          , J = !this.perturbedNormal.isConnected && !this.anisotropy.isConnected
          , Q = this.perturbedNormal.isConnected && ((A = ((C = this.perturbedNormal.connectedPoint) === null || C === void 0 ? void 0 : C.ownerBlock).worldTangent) === null || A === void 0 ? void 0 : A.isConnected)
          , te = this.anisotropy.isConnected && ((S = this.anisotropy.connectedPoint) === null || S === void 0 ? void 0 : S.ownerBlock).worldTangent.isConnected
          , re = Q || !this.perturbedNormal.isConnected && te;
        t.compilationString += ClearCoatBlock.GetCode(t, q, B, $, J, re, this.worldNormal.associatedVariableName),
        J && (re = (P = q == null ? void 0 : q.worldTangent.isConnected) !== null && P !== void 0 ? P : !1),
        t._emitFunctionFromInclude("pbrBlockClearcoat", X, {
            replaceStrings: [{
                search: /computeReflectionCoords/g,
                replace: "computeReflectionCoordsPBR"
            }, {
                search: /REFLECTIONMAP_3D/g,
                replace: (R = B == null ? void 0 : B._define3DName) !== null && R !== void 0 ? R : "REFLECTIONMAP_3D"
            }, {
                search: /REFLECTIONMAP_OPPOSITEZ/g,
                replace: (M = B == null ? void 0 : B._defineOppositeZ) !== null && M !== void 0 ? M : "REFLECTIONMAP_OPPOSITEZ"
            }, {
                search: /REFLECTIONMAP_PROJECTION/g,
                replace: (x = B == null ? void 0 : B._defineProjectionName) !== null && x !== void 0 ? x : "REFLECTIONMAP_PROJECTION"
            }, {
                search: /REFLECTIONMAP_SKYBOX/g,
                replace: (I = B == null ? void 0 : B._defineSkyboxName) !== null && I !== void 0 ? I : "REFLECTIONMAP_SKYBOX"
            }, {
                search: /LODINREFLECTIONALPHA/g,
                replace: (w = B == null ? void 0 : B._defineLODReflectionAlpha) !== null && w !== void 0 ? w : "LODINREFLECTIONALPHA"
            }, {
                search: /LINEARSPECULARREFLECTION/g,
                replace: (O = B == null ? void 0 : B._defineLinearSpecularReflection) !== null && O !== void 0 ? O : "LINEARSPECULARREFLECTION"
            }, {
                search: /defined\(TANGENT\)/g,
                replace: re ? "defined(TANGENT)" : "defined(IGNORE)"
            }]
        }),
        t.compilationString += t._emitCodeFromInclude("pbrBlockReflectance", X, {
            replaceStrings: [{
                search: /REFLECTIONMAP_SKYBOX/g,
                replace: (D = B == null ? void 0 : B._defineSkyboxName) !== null && D !== void 0 ? D : "REFLECTIONMAP_SKYBOX"
            }, {
                search: /REFLECTIONMAP_3D/g,
                replace: (F = B == null ? void 0 : B._define3DName) !== null && F !== void 0 ? F : "REFLECTIONMAP_3D"
            }]
        });
        var ie = this.subsurface.isConnected ? (V = this.subsurface.connectedPoint) === null || V === void 0 ? void 0 : V.ownerBlock : null
          , ee = this.subsurface.isConnected ? (L = ((N = this.subsurface.connectedPoint) === null || N === void 0 ? void 0 : N.ownerBlock).refraction.connectedPoint) === null || L === void 0 ? void 0 : L.ownerBlock : null;
        ee && (ee.viewConnectionPoint = this.view,
        ee.indexOfRefractionConnectionPoint = this.indexOfRefraction),
        t.compilationString += SubSurfaceBlock.GetCode(t, ie, B, $),
        t._emitFunctionFromInclude("pbrBlockSubSurface", X, {
            replaceStrings: [{
                search: /REFLECTIONMAP_3D/g,
                replace: (k = B == null ? void 0 : B._define3DName) !== null && k !== void 0 ? k : "REFLECTIONMAP_3D"
            }, {
                search: /REFLECTIONMAP_OPPOSITEZ/g,
                replace: (U = B == null ? void 0 : B._defineOppositeZ) !== null && U !== void 0 ? U : "REFLECTIONMAP_OPPOSITEZ"
            }, {
                search: /REFLECTIONMAP_PROJECTION/g,
                replace: (z = B == null ? void 0 : B._defineProjectionName) !== null && z !== void 0 ? z : "REFLECTIONMAP_PROJECTION"
            }, {
                search: /SS_REFRACTIONMAP_3D/g,
                replace: (H = ee == null ? void 0 : ee._define3DName) !== null && H !== void 0 ? H : "SS_REFRACTIONMAP_3D"
            }, {
                search: /SS_LODINREFRACTIONALPHA/g,
                replace: (G = ee == null ? void 0 : ee._defineLODRefractionAlpha) !== null && G !== void 0 ? G : "SS_LODINREFRACTIONALPHA"
            }, {
                search: /SS_LINEARSPECULARREFRACTION/g,
                replace: (W = ee == null ? void 0 : ee._defineLinearSpecularRefraction) !== null && W !== void 0 ? W : "SS_LINEARSPECULARREFRACTION"
            }, {
                search: /SS_REFRACTIONMAP_OPPOSITEZ/g,
                replace: (j = ee == null ? void 0 : ee._defineOppositeZ) !== null && j !== void 0 ? j : "SS_REFRACTIONMAP_OPPOSITEZ"
            }]
        }),
        t.compilationString += t._emitCodeFromInclude("pbrBlockDirectLighting", X),
        this.light ? t.compilationString += t._emitCodeFromInclude("lightFragment", X, {
            replaceStrings: [{
                search: /{X}/g,
                replace: this._lightId.toString()
            }]
        }) : t.compilationString += t._emitCodeFromInclude("lightFragment", X, {
            repeatKey: "maxSimultaneousLights"
        }),
        t.compilationString += t._emitCodeFromInclude("pbrBlockFinalLitComponents", X),
        t.compilationString += `#endif\r
`;
        var ne = this.ambientColor.isConnected ? this.ambientColor.associatedVariableName : "vec3(0., 0., 0.)"
          , ce = PBRBaseMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS.toString();
        ce.indexOf(".") === -1 && (ce += "."),
        t.compilationString += t._emitCodeFromInclude("pbrBlockFinalUnlitComponents", X, {
            replaceStrings: [{
                search: /vec3 finalEmissive[\s\S]*?finalEmissive\*=vLightingIntensity\.y;/g,
                replace: ""
            }, {
                search: /vAmbientColor/g,
                replace: ne + " * ambientFromScene"
            }, {
                search: /vAmbientInfos\.w/g,
                replace: ce
            }]
        }),
        t.compilationString += t._emitCodeFromInclude("pbrBlockFinalColorComposition", X, {
            replaceStrings: [{
                search: /finalEmissive/g,
                replace: "vec3(0.)"
            }]
        }),
        t.compilationString += t._emitCodeFromInclude("pbrBlockImageProcessing", X, {
            replaceStrings: [{
                search: /visibility/g,
                replace: "1."
            }]
        }),
        t.compilationString += t._emitCodeFromInclude("pbrDebug", X, {
            replaceStrings: [{
                search: /vNormalW/g,
                replace: this._vNormalWName
            }, {
                search: /vPositionW/g,
                replace: $
            }, {
                search: /albedoTexture\.rgb;/g,
                replace: `vec3(1.);\r
gl_FragColor.rgb = toGammaSpace(gl_FragColor.rgb);\r
`
            }]
        });
        for (var he = 0, fe = this._outputs; he < fe.length; he++) {
            var ue = fe[he];
            if (ue.hasEndpoints) {
                var _e = mapOutputToVariable[ue.name];
                if (_e) {
                    var ae = _e[0]
                      , se = _e[1];
                    se && (t.compilationString += "#if " + se + `\r
`),
                    t.compilationString += this._declareOutput(ue, t) + " = " + ae + `;\r
`,
                    se && (t.compilationString += `#else\r
`,
                    t.compilationString += this._declareOutput(ue, t) + ` = vec3(0.);\r
`,
                    t.compilationString += `#endif\r
`)
                } else
                    console.error("There's no remapping for the " + ue.name + " end point! No code generated")
            }
        }
        return this
    }
    ,
    e.prototype._dumpPropertiesCode = function() {
        var t = i.prototype._dumpPropertiesCode.call(this);
        return t += this._codeVariableName + ".lightFalloff = " + this.lightFalloff + `;\r
`,
        t += this._codeVariableName + ".useAlphaTest = " + this.useAlphaTest + `;\r
`,
        t += this._codeVariableName + ".alphaTestCutoff = " + this.alphaTestCutoff + `;\r
`,
        t += this._codeVariableName + ".useAlphaBlending = " + this.useAlphaBlending + `;\r
`,
        t += this._codeVariableName + ".useRadianceOverAlpha = " + this.useRadianceOverAlpha + `;\r
`,
        t += this._codeVariableName + ".useSpecularOverAlpha = " + this.useSpecularOverAlpha + `;\r
`,
        t += this._codeVariableName + ".enableSpecularAntiAliasing = " + this.enableSpecularAntiAliasing + `;\r
`,
        t += this._codeVariableName + ".realTimeFiltering = " + this.realTimeFiltering + `;\r
`,
        t += this._codeVariableName + ".realTimeFilteringQuality = " + this.realTimeFilteringQuality + `;\r
`,
        t += this._codeVariableName + ".useEnergyConservation = " + this.useEnergyConservation + `;\r
`,
        t += this._codeVariableName + ".useRadianceOcclusion = " + this.useRadianceOcclusion + `;\r
`,
        t += this._codeVariableName + ".useHorizonOcclusion = " + this.useHorizonOcclusion + `;\r
`,
        t += this._codeVariableName + ".unlit = " + this.unlit + `;\r
`,
        t += this._codeVariableName + ".forceNormalForward = " + this.forceNormalForward + `;\r
`,
        t += this._codeVariableName + ".debugMode = " + this.debugMode + `;\r
`,
        t += this._codeVariableName + ".debugLimit = " + this.debugLimit + `;\r
`,
        t += this._codeVariableName + ".debugFactor = " + this.debugFactor + `;\r
`,
        t
    }
    ,
    e.prototype.serialize = function() {
        var t = i.prototype.serialize.call(this);
        return this.light && (t.lightId = this.light.id),
        t.lightFalloff = this.lightFalloff,
        t.useAlphaTest = this.useAlphaTest,
        t.alphaTestCutoff = this.alphaTestCutoff,
        t.useAlphaBlending = this.useAlphaBlending,
        t.useRadianceOverAlpha = this.useRadianceOverAlpha,
        t.useSpecularOverAlpha = this.useSpecularOverAlpha,
        t.enableSpecularAntiAliasing = this.enableSpecularAntiAliasing,
        t.realTimeFiltering = this.realTimeFiltering,
        t.realTimeFilteringQuality = this.realTimeFilteringQuality,
        t.useEnergyConservation = this.useEnergyConservation,
        t.useRadianceOcclusion = this.useRadianceOcclusion,
        t.useHorizonOcclusion = this.useHorizonOcclusion,
        t.unlit = this.unlit,
        t.forceNormalForward = this.forceNormalForward,
        t.debugMode = this.debugMode,
        t.debugLimit = this.debugLimit,
        t.debugFactor = this.debugFactor,
        t
    }
    ,
    e.prototype._deserialize = function(t, r, n) {
        var o, a;
        i.prototype._deserialize.call(this, t, r, n),
        t.lightId && (this.light = r.getLightById(t.lightId)),
        this.lightFalloff = (o = t.lightFalloff) !== null && o !== void 0 ? o : 0,
        this.useAlphaTest = t.useAlphaTest,
        this.alphaTestCutoff = t.alphaTestCutoff,
        this.useAlphaBlending = t.useAlphaBlending,
        this.useRadianceOverAlpha = t.useRadianceOverAlpha,
        this.useSpecularOverAlpha = t.useSpecularOverAlpha,
        this.enableSpecularAntiAliasing = t.enableSpecularAntiAliasing,
        this.realTimeFiltering = !!t.realTimeFiltering,
        this.realTimeFilteringQuality = (a = t.realTimeFilteringQuality) !== null && a !== void 0 ? a : 8,
        this.useEnergyConservation = t.useEnergyConservation,
        this.useRadianceOcclusion = t.useRadianceOcclusion,
        this.useHorizonOcclusion = t.useHorizonOcclusion,
        this.unlit = t.unlit,
        this.forceNormalForward = !!t.forceNormalForward,
        this.debugMode = t.debugMode,
        this.debugLimit = t.debugLimit,
        this.debugFactor = t.debugFactor
    }
    ,
    __decorate([editableInPropertyPage("Direct lights", PropertyTypeForEdition.Float, "INTENSITY", {
        min: 0,
        max: 1,
        notifiers: {
            update: !0
        }
    })], e.prototype, "directIntensity", void 0),
    __decorate([editableInPropertyPage("Environment lights", PropertyTypeForEdition.Float, "INTENSITY", {
        min: 0,
        max: 1,
        notifiers: {
            update: !0
        }
    })], e.prototype, "environmentIntensity", void 0),
    __decorate([editableInPropertyPage("Specular highlights", PropertyTypeForEdition.Float, "INTENSITY", {
        min: 0,
        max: 1,
        notifiers: {
            update: !0
        }
    })], e.prototype, "specularIntensity", void 0),
    __decorate([editableInPropertyPage("Light falloff", PropertyTypeForEdition.List, "LIGHTING & COLORS", {
        notifiers: {
            update: !0
        },
        options: [{
            label: "Physical",
            value: PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL
        }, {
            label: "GLTF",
            value: PBRBaseMaterial.LIGHTFALLOFF_GLTF
        }, {
            label: "Standard",
            value: PBRBaseMaterial.LIGHTFALLOFF_STANDARD
        }]
    })], e.prototype, "lightFalloff", void 0),
    __decorate([editableInPropertyPage("Alpha Testing", PropertyTypeForEdition.Boolean, "OPACITY")], e.prototype, "useAlphaTest", void 0),
    __decorate([editableInPropertyPage("Alpha CutOff", PropertyTypeForEdition.Float, "OPACITY", {
        min: 0,
        max: 1,
        notifiers: {
            update: !0
        }
    })], e.prototype, "alphaTestCutoff", void 0),
    __decorate([editableInPropertyPage("Alpha blending", PropertyTypeForEdition.Boolean, "OPACITY")], e.prototype, "useAlphaBlending", void 0),
    __decorate([editableInPropertyPage("Radiance over alpha", PropertyTypeForEdition.Boolean, "RENDERING", {
        notifiers: {
            update: !0
        }
    })], e.prototype, "useRadianceOverAlpha", void 0),
    __decorate([editableInPropertyPage("Specular over alpha", PropertyTypeForEdition.Boolean, "RENDERING", {
        notifiers: {
            update: !0
        }
    })], e.prototype, "useSpecularOverAlpha", void 0),
    __decorate([editableInPropertyPage("Specular anti-aliasing", PropertyTypeForEdition.Boolean, "RENDERING", {
        notifiers: {
            update: !0
        }
    })], e.prototype, "enableSpecularAntiAliasing", void 0),
    __decorate([editableInPropertyPage("Realtime filtering", PropertyTypeForEdition.Boolean, "RENDERING", {
        notifiers: {
            update: !0
        }
    })], e.prototype, "realTimeFiltering", void 0),
    __decorate([editableInPropertyPage("Realtime filtering quality", PropertyTypeForEdition.List, "RENDERING", {
        notifiers: {
            update: !0
        },
        options: [{
            label: "Low",
            value: 8
        }, {
            label: "Medium",
            value: 16
        }, {
            label: "High",
            value: 64
        }]
    })], e.prototype, "realTimeFilteringQuality", void 0),
    __decorate([editableInPropertyPage("Energy Conservation", PropertyTypeForEdition.Boolean, "ADVANCED", {
        notifiers: {
            update: !0
        }
    })], e.prototype, "useEnergyConservation", void 0),
    __decorate([editableInPropertyPage("Radiance occlusion", PropertyTypeForEdition.Boolean, "ADVANCED", {
        notifiers: {
            update: !0
        }
    })], e.prototype, "useRadianceOcclusion", void 0),
    __decorate([editableInPropertyPage("Horizon occlusion", PropertyTypeForEdition.Boolean, "ADVANCED", {
        notifiers: {
            update: !0
        }
    })], e.prototype, "useHorizonOcclusion", void 0),
    __decorate([editableInPropertyPage("Unlit", PropertyTypeForEdition.Boolean, "ADVANCED", {
        notifiers: {
            update: !0
        }
    })], e.prototype, "unlit", void 0),
    __decorate([editableInPropertyPage("Force normal forward", PropertyTypeForEdition.Boolean, "ADVANCED", {
        notifiers: {
            update: !0
        }
    })], e.prototype, "forceNormalForward", void 0),
    __decorate([editableInPropertyPage("Debug mode", PropertyTypeForEdition.List, "DEBUG", {
        notifiers: {
            update: !0
        },
        options: [{
            label: "None",
            value: 0
        }, {
            label: "Normalized position",
            value: 1
        }, {
            label: "Normals",
            value: 2
        }, {
            label: "Tangents",
            value: 3
        }, {
            label: "Bitangents",
            value: 4
        }, {
            label: "Bump Normals",
            value: 5
        }, {
            label: "ClearCoat Normals",
            value: 8
        }, {
            label: "ClearCoat Tangents",
            value: 9
        }, {
            label: "ClearCoat Bitangents",
            value: 10
        }, {
            label: "Anisotropic Normals",
            value: 11
        }, {
            label: "Anisotropic Tangents",
            value: 12
        }, {
            label: "Anisotropic Bitangents",
            value: 13
        }, {
            label: "Env Refraction",
            value: 40
        }, {
            label: "Env Reflection",
            value: 41
        }, {
            label: "Env Clear Coat",
            value: 42
        }, {
            label: "Direct Diffuse",
            value: 50
        }, {
            label: "Direct Specular",
            value: 51
        }, {
            label: "Direct Clear Coat",
            value: 52
        }, {
            label: "Direct Sheen",
            value: 53
        }, {
            label: "Env Irradiance",
            value: 54
        }, {
            label: "Surface Albedo",
            value: 60
        }, {
            label: "Reflectance 0",
            value: 61
        }, {
            label: "Metallic",
            value: 62
        }, {
            label: "Metallic F0",
            value: 71
        }, {
            label: "Roughness",
            value: 63
        }, {
            label: "AlphaG",
            value: 64
        }, {
            label: "NdotV",
            value: 65
        }, {
            label: "ClearCoat Color",
            value: 66
        }, {
            label: "ClearCoat Roughness",
            value: 67
        }, {
            label: "ClearCoat NdotV",
            value: 68
        }, {
            label: "Transmittance",
            value: 69
        }, {
            label: "Refraction Transmittance",
            value: 70
        }, {
            label: "SEO",
            value: 80
        }, {
            label: "EHO",
            value: 81
        }, {
            label: "Energy Factor",
            value: 82
        }, {
            label: "Specular Reflectance",
            value: 83
        }, {
            label: "Clear Coat Reflectance",
            value: 84
        }, {
            label: "Sheen Reflectance",
            value: 85
        }, {
            label: "Luminance Over Alpha",
            value: 86
        }, {
            label: "Alpha",
            value: 87
        }]
    })], e.prototype, "debugMode", void 0),
    __decorate([editableInPropertyPage("Split position", PropertyTypeForEdition.Float, "DEBUG", {
        min: -1,
        max: 1,
        notifiers: {
            update: !0
        }
    })], e.prototype, "debugLimit", void 0),
    __decorate([editableInPropertyPage("Output factor", PropertyTypeForEdition.Float, "DEBUG", {
        min: 0,
        max: 5,
        notifiers: {
            update: !0
        }
    })], e.prototype, "debugFactor", void 0),
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.PBRMetallicRoughnessBlock", PBRMetallicRoughnessBlock);
var ModBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Neutral) || this;
        return r.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        r.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        r._outputs[0]._typeConnectionSource = r._inputs[0],
        r._linkConnectionTypes(0, 1),
        r
    }
    return e.prototype.getClassName = function() {
        return "ModBlock"
    }
    ,
    Object.defineProperty(e.prototype, "left", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "right", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = this._outputs[0];
        return t.compilationString += this._declareOutput(r, t) + (" = mod(" + this.left.associatedVariableName + ", " + this.right.associatedVariableName + `);\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.ModBlock", ModBlock);
var MatrixBuilderBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Neutral) || this;
        return r.registerInput("row0", NodeMaterialBlockConnectionPointTypes.Vector4),
        r.registerInput("row1", NodeMaterialBlockConnectionPointTypes.Vector4),
        r.registerInput("row2", NodeMaterialBlockConnectionPointTypes.Vector4),
        r.registerInput("row3", NodeMaterialBlockConnectionPointTypes.Vector4),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Matrix),
        r
    }
    return e.prototype.getClassName = function() {
        return "MatrixBuilder"
    }
    ,
    Object.defineProperty(e.prototype, "row0", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "row1", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "row2", {
        get: function() {
            return this._inputs[2]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "row3", {
        get: function() {
            return this._inputs[3]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.autoConfigure = function(t) {
        if (!this.row0.isConnected) {
            var r = new InputBlock("row0");
            r.value = new Vector4(1,0,0,0),
            r.output.connectTo(this.row0)
        }
        if (!this.row1.isConnected) {
            var n = new InputBlock("row1");
            n.value = new Vector4(0,1,0,0),
            n.output.connectTo(this.row1)
        }
        if (!this.row2.isConnected) {
            var o = new InputBlock("row2");
            o.value = new Vector4(0,0,1,0),
            o.output.connectTo(this.row2)
        }
        if (!this.row3.isConnected) {
            var a = new InputBlock("row3");
            a.value = new Vector4(0,0,0,1),
            a.output.connectTo(this.row3)
        }
    }
    ,
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = this._outputs[0]
          , n = this.row0
          , o = this.row1
          , a = this.row2
          , s = this.row3;
        return t.compilationString += this._declareOutput(r, t) + (" = mat4(" + n.associatedVariableName + ", " + o.associatedVariableName + ", " + a.associatedVariableName + ", " + s.associatedVariableName + `);\r
`),
        this
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.MatrixBuilder", MatrixBuilderBlock);
var ConditionalBlockConditions;
(function(i) {
    i[i.Equal = 0] = "Equal",
    i[i.NotEqual = 1] = "NotEqual",
    i[i.LessThan = 2] = "LessThan",
    i[i.GreaterThan = 3] = "GreaterThan",
    i[i.LessOrEqual = 4] = "LessOrEqual",
    i[i.GreaterOrEqual = 5] = "GreaterOrEqual",
    i[i.Xor = 6] = "Xor",
    i[i.Or = 7] = "Or",
    i[i.And = 8] = "And"
}
)(ConditionalBlockConditions || (ConditionalBlockConditions = {}));
var ConditionalBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Neutral) || this;
        return r.condition = ConditionalBlockConditions.LessThan,
        r.registerInput("a", NodeMaterialBlockConnectionPointTypes.Float),
        r.registerInput("b", NodeMaterialBlockConnectionPointTypes.Float),
        r.registerInput("true", NodeMaterialBlockConnectionPointTypes.AutoDetect, !0),
        r.registerInput("false", NodeMaterialBlockConnectionPointTypes.AutoDetect, !0),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput),
        r._linkConnectionTypes(2, 3),
        r._outputs[0]._typeConnectionSource = r._inputs[2],
        r._outputs[0]._defaultConnectionPointType = NodeMaterialBlockConnectionPointTypes.Float,
        r
    }
    return e.prototype.getClassName = function() {
        return "ConditionalBlock"
    }
    ,
    Object.defineProperty(e.prototype, "a", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "b", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "true", {
        get: function() {
            return this._inputs[2]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "false", {
        get: function() {
            return this._inputs[3]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._buildBlock = function(t) {
        i.prototype._buildBlock.call(this, t);
        var r = this._outputs[0]
          , n = this.true.isConnected ? this.true.associatedVariableName : "1.0"
          , o = this.false.isConnected ? this.false.associatedVariableName : "0.0";
        switch (this.condition) {
        case ConditionalBlockConditions.Equal:
            {
                t.compilationString += this._declareOutput(r, t) + (" = " + this.a.associatedVariableName + " == " + this.b.associatedVariableName + " ? " + n + " : " + o + `;\r
`);
                break
            }
        case ConditionalBlockConditions.NotEqual:
            {
                t.compilationString += this._declareOutput(r, t) + (" = " + this.a.associatedVariableName + " != " + this.b.associatedVariableName + " ? " + n + " : " + o + `;\r
`);
                break
            }
        case ConditionalBlockConditions.LessThan:
            {
                t.compilationString += this._declareOutput(r, t) + (" = " + this.a.associatedVariableName + " < " + this.b.associatedVariableName + " ? " + n + " : " + o + `;\r
`);
                break
            }
        case ConditionalBlockConditions.LessOrEqual:
            {
                t.compilationString += this._declareOutput(r, t) + (" = " + this.a.associatedVariableName + " <= " + this.b.associatedVariableName + " ? " + n + " : " + o + `;\r
`);
                break
            }
        case ConditionalBlockConditions.GreaterThan:
            {
                t.compilationString += this._declareOutput(r, t) + (" = " + this.a.associatedVariableName + " > " + this.b.associatedVariableName + " ? " + n + " : " + o + `;\r
`);
                break
            }
        case ConditionalBlockConditions.GreaterOrEqual:
            {
                t.compilationString += this._declareOutput(r, t) + (" = " + this.a.associatedVariableName + " >= " + this.b.associatedVariableName + " ? " + n + " : " + o + `;\r
`);
                break
            }
        case ConditionalBlockConditions.Xor:
            {
                t.compilationString += this._declareOutput(r, t) + (" = (mod(" + this.a.associatedVariableName + " + " + this.b.associatedVariableName + ", 2.0) > 0.0) ? " + n + " : " + o + `;\r
`);
                break
            }
        case ConditionalBlockConditions.Or:
            {
                t.compilationString += this._declareOutput(r, t) + (" = (min(" + this.a.associatedVariableName + " + " + this.b.associatedVariableName + ", 1.0) > 0.0) ? " + n + " : " + o + `;\r
`);
                break
            }
        case ConditionalBlockConditions.And:
            {
                t.compilationString += this._declareOutput(r, t) + (" = (" + this.a.associatedVariableName + " * " + this.b.associatedVariableName + " > 0.0)  ? " + n + " : " + o + `;\r
`);
                break
            }
        }
        return this
    }
    ,
    e.prototype.serialize = function() {
        var t = i.prototype.serialize.call(this);
        return t.condition = this.condition,
        t
    }
    ,
    e.prototype._deserialize = function(t, r, n) {
        i.prototype._deserialize.call(this, t, r, n),
        this.condition = t.condition
    }
    ,
    e.prototype._dumpPropertiesCode = function() {
        var t = i.prototype._dumpPropertiesCode.call(this) + (this._codeVariableName + ".condition = BABYLON.ConditionalBlockConditions." + ConditionalBlockConditions[this.condition] + `;\r
`);
        return t
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.ConditionalBlock", ConditionalBlock);
var CloudBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Neutral) || this;
        return r.octaves = 6,
        r.registerInput("seed", NodeMaterialBlockConnectionPointTypes.AutoDetect),
        r.registerInput("chaos", NodeMaterialBlockConnectionPointTypes.AutoDetect, !0),
        r.registerInput("offsetX", NodeMaterialBlockConnectionPointTypes.Float, !0),
        r.registerInput("offsetY", NodeMaterialBlockConnectionPointTypes.Float, !0),
        r.registerInput("offsetZ", NodeMaterialBlockConnectionPointTypes.Float, !0),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float),
        r._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector2),
        r._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector3),
        r._linkConnectionTypes(0, 1),
        r
    }
    return e.prototype.getClassName = function() {
        return "CloudBlock"
    }
    ,
    Object.defineProperty(e.prototype, "seed", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "chaos", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "offsetX", {
        get: function() {
            return this._inputs[2]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "offsetY", {
        get: function() {
            return this._inputs[3]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "offsetZ", {
        get: function() {
            return this._inputs[4]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._buildBlock = function(t) {
        var r, n;
        if (i.prototype._buildBlock.call(this, t),
        !!this.seed.isConnected && !!this._outputs[0].hasEndpoints) {
            var o = `

        float cloudRandom(in float p) { p = fract(p * 0.011); p *= p + 7.5; p *= p + p; return fract(p); }

        // Based on Morgan McGuire @morgan3d
        // https://www.shadertoy.com/view/4dS3Wd
        float cloudNoise(in vec2 x, in vec2 chaos) {
            vec2 step = chaos * vec2(75., 120.) + vec2(75., 120.);

            vec2 i = floor(x);
            vec2 f = fract(x);

            float n = dot(i, step);

            vec2 u = f * f * (3.0 - 2.0 * f);
            return mix(
                    mix(cloudRandom(n + dot(step, vec2(0, 0))), cloudRandom(n + dot(step, vec2(1, 0))), u.x),
                    mix(cloudRandom(n + dot(step, vec2(0, 1))), cloudRandom(n + dot(step, vec2(1, 1))), u.x),
                    u.y
                );
        }

        float cloudNoise(in vec3 x, in vec3 chaos) {
            vec3 step = chaos * vec3(60., 120., 75.) + vec3(60., 120., 75.);

            vec3 i = floor(x);
            vec3 f = fract(x);

            float n = dot(i, step);

            vec3 u = f * f * (3.0 - 2.0 * f);
            return mix(mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 0))), cloudRandom(n + dot(step, vec3(1, 0, 0))), u.x),
                           mix( cloudRandom(n + dot(step, vec3(0, 1, 0))), cloudRandom(n + dot(step, vec3(1, 1, 0))), u.x), u.y),
                       mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 1))), cloudRandom(n + dot(step, vec3(1, 0, 1))), u.x),
                           mix( cloudRandom(n + dot(step, vec3(0, 1, 1))), cloudRandom(n + dot(step, vec3(1, 1, 1))), u.x), u.y), u.z);
        }`
              , a = `
        float fbm(in vec2 st, in vec2 chaos) {
            // Initial values
            float value = 0.0;
            float amplitude = .5;
            float frequency = 0.;

            // Loop of octaves
            for (int i = 0; i < OCTAVES; i++) {
                value += amplitude * cloudNoise(st, chaos);
                st *= 2.0;
                amplitude *= 0.5;
            }
            return value;
        }

        float fbm(in vec3 x, in vec3 chaos) {
            // Initial values
            float value = 0.0;
            float amplitude = 0.5;
            for (int i = 0; i < OCTAVES; ++i) {
                value += amplitude * cloudNoise(x, chaos);
                x = x * 2.0;
                amplitude *= 0.5;
            }
            return value;
        }`
              , s = "fbm" + this.octaves;
            t._emitFunction("CloudBlockCode", o, "// CloudBlockCode"),
            t._emitFunction("CloudBlockCodeFBM" + this.octaves, a.replace(/fbm/gi, s).replace(/OCTAVES/gi, (this.octaves | 0).toString()), "// CloudBlockCode FBM");
            var l = t._getFreeVariableName("st")
              , u = ((r = this.seed.connectedPoint) === null || r === void 0 ? void 0 : r.type) === NodeMaterialBlockConnectionPointTypes.Vector2 ? "vec2" : "vec3";
            t.compilationString += u + " " + l + " = " + this.seed.associatedVariableName + `;\r
`,
            this.offsetX.isConnected && (t.compilationString += l + ".x += 0.1 * " + this.offsetX.associatedVariableName + `;\r
`),
            this.offsetY.isConnected && (t.compilationString += l + ".y += 0.1 * " + this.offsetY.associatedVariableName + `;\r
`),
            this.offsetZ.isConnected && u === "vec3" && (t.compilationString += l + ".z += 0.1 * " + this.offsetZ.associatedVariableName + `;\r
`);
            var c = "";
            return this.chaos.isConnected ? c = this.chaos.associatedVariableName : c = ((n = this.seed.connectedPoint) === null || n === void 0 ? void 0 : n.type) === NodeMaterialBlockConnectionPointTypes.Vector2 ? "vec2(0., 0.)" : "vec3(0., 0., 0.)",
            t.compilationString += this._declareOutput(this._outputs[0], t) + (" = " + s + "(" + l + ", " + c + `);\r
`),
            this
        }
    }
    ,
    e.prototype._dumpPropertiesCode = function() {
        var t = i.prototype._dumpPropertiesCode.call(this) + (this._codeVariableName + ".octaves = " + this.octaves + `;\r
`);
        return t
    }
    ,
    e.prototype.serialize = function() {
        var t = i.prototype.serialize.call(this);
        return t.octaves = this.octaves,
        t
    }
    ,
    e.prototype._deserialize = function(t, r, n) {
        i.prototype._deserialize.call(this, t, r, n),
        this.octaves = t.octaves
    }
    ,
    __decorate([editableInPropertyPage("Octaves", PropertyTypeForEdition.Int)], e.prototype, "octaves", void 0),
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.CloudBlock", CloudBlock);
var VoronoiNoiseBlock = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t, NodeMaterialBlockTargets.Neutral) || this;
        return r.registerInput("seed", NodeMaterialBlockConnectionPointTypes.Vector2),
        r.registerInput("offset", NodeMaterialBlockConnectionPointTypes.Float),
        r.registerInput("density", NodeMaterialBlockConnectionPointTypes.Float),
        r.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float),
        r.registerOutput("cells", NodeMaterialBlockConnectionPointTypes.Float),
        r
    }
    return e.prototype.getClassName = function() {
        return "VoronoiNoiseBlock"
    }
    ,
    Object.defineProperty(e.prototype, "seed", {
        get: function() {
            return this._inputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "offset", {
        get: function() {
            return this._inputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "density", {
        get: function() {
            return this._inputs[2]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "output", {
        get: function() {
            return this._outputs[0]
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cells", {
        get: function() {
            return this._outputs[1]
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._buildBlock = function(t) {
        if (i.prototype._buildBlock.call(this, t),
        !!this.seed.isConnected) {
            var r = `vec2 voronoiRandom(vec2 seed, float offset){
            mat2 m = mat2(15.27, 47.63, 99.41, 89.98);
            vec2 uv = fract(sin(m * seed) * 46839.32);
            return vec2(sin(uv.y * offset) * 0.5 + 0.5, cos(uv.x * offset) * 0.5 + 0.5);
        }
        `;
            t._emitFunction("voronoiRandom", r, "// Voronoi random generator"),
            r = `void voronoi(vec2 seed, float offset, float density, out float outValue, out float cells){
            vec2 g = floor(seed * density);
            vec2 f = fract(seed * density);
            float t = 8.0;
            vec3 res = vec3(8.0, 0.0, 0.0);

            for(int y=-1; y<=1; y++)
            {
                for(int x=-1; x<=1; x++)
                {
                    vec2 lattice = vec2(x,y);
                    vec2 randomOffset = voronoiRandom(lattice + g, offset);
                    float d = distance(lattice + randomOffset, f);
                    if(d < res.x)
                    {
                        res = vec3(d, randomOffset.x, randomOffset.y);
                        outValue = res.x;
                        cells = res.y;
                    }
                }
            }
        }
        `,
            t._emitFunction("voronoi", r, "// Voronoi");
            var n = t._getFreeVariableName("tempOutput")
              , o = t._getFreeVariableName("tempCells");
            return t.compilationString += "float " + n + ` = 0.0;\r
`,
            t.compilationString += "float " + o + ` = 0.0;\r
`,
            t.compilationString += "voronoi(" + this.seed.associatedVariableName + ", " + this.offset.associatedVariableName + ", " + this.density.associatedVariableName + ", " + n + ", " + o + `);\r
`,
            this.output.hasEndpoints && (t.compilationString += this._declareOutput(this.output, t) + (" = " + n + `;\r
`)),
            this.cells.hasEndpoints && (t.compilationString += this._declareOutput(this.cells, t) + (" = " + o + `;\r
`)),
            this
        }
    }
    ,
    e
}(NodeMaterialBlock);
RegisterClass("BABYLON.VoronoiNoiseBlock", VoronoiNoiseBlock);
Node$2.AddNodeConstructor("Light_Type_2", function(i, e) {
    return function() {
        return new SpotLight(i,Vector3.Zero(),Vector3.Zero(),0,0,e)
    }
});
var SpotLight = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a, s) {
        var l = i.call(this, t, s) || this;
        return l._innerAngle = 0,
        l._projectionTextureMatrix = Matrix.Zero(),
        l._projectionTextureLightNear = 1e-6,
        l._projectionTextureLightFar = 1e3,
        l._projectionTextureUpDirection = Vector3.Up(),
        l._projectionTextureViewLightDirty = !0,
        l._projectionTextureProjectionLightDirty = !0,
        l._projectionTextureDirty = !0,
        l._projectionTextureViewTargetVector = Vector3.Zero(),
        l._projectionTextureViewLightMatrix = Matrix.Zero(),
        l._projectionTextureProjectionLightMatrix = Matrix.Zero(),
        l._projectionTextureScalingMatrix = Matrix.FromValues(.5, 0, 0, 0, 0, .5, 0, 0, 0, 0, .5, 0, .5, .5, .5, 1),
        l.position = r,
        l.direction = n,
        l.angle = o,
        l.exponent = a,
        l
    }
    return Object.defineProperty(e.prototype, "angle", {
        get: function() {
            return this._angle
        },
        set: function(t) {
            this._angle = t,
            this._cosHalfAngle = Math.cos(t * .5),
            this._projectionTextureProjectionLightDirty = !0,
            this.forceProjectionMatrixCompute(),
            this._computeAngleValues()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "innerAngle", {
        get: function() {
            return this._innerAngle
        },
        set: function(t) {
            this._innerAngle = t,
            this._computeAngleValues()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "shadowAngleScale", {
        get: function() {
            return this._shadowAngleScale
        },
        set: function(t) {
            this._shadowAngleScale = t,
            this.forceProjectionMatrixCompute()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "projectionTextureMatrix", {
        get: function() {
            return this._projectionTextureMatrix
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "projectionTextureLightNear", {
        get: function() {
            return this._projectionTextureLightNear
        },
        set: function(t) {
            this._projectionTextureLightNear = t,
            this._projectionTextureProjectionLightDirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "projectionTextureLightFar", {
        get: function() {
            return this._projectionTextureLightFar
        },
        set: function(t) {
            this._projectionTextureLightFar = t,
            this._projectionTextureProjectionLightDirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "projectionTextureUpDirection", {
        get: function() {
            return this._projectionTextureUpDirection
        },
        set: function(t) {
            this._projectionTextureUpDirection = t,
            this._projectionTextureProjectionLightDirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "projectionTexture", {
        get: function() {
            return this._projectionTexture
        },
        set: function(t) {
            var r = this;
            this._projectionTexture !== t && (this._projectionTexture = t,
            this._projectionTextureDirty = !0,
            this._projectionTexture && !this._projectionTexture.isReady() && (e._IsProceduralTexture(this._projectionTexture) ? this._projectionTexture.getEffect().executeWhenCompiled(function() {
                r._markMeshesAsLightDirty()
            }) : e._IsTexture(this._projectionTexture) && this._projectionTexture.onLoadObservable.addOnce(function() {
                r._markMeshesAsLightDirty()
            })))
        },
        enumerable: !1,
        configurable: !0
    }),
    e._IsProceduralTexture = function(t) {
        return t.onGeneratedObservable !== void 0
    }
    ,
    e._IsTexture = function(t) {
        return t.onLoadObservable !== void 0
    }
    ,
    Object.defineProperty(e.prototype, "projectionTextureProjectionLightMatrix", {
        get: function() {
            return this._projectionTextureProjectionLightMatrix
        },
        set: function(t) {
            this._projectionTextureProjectionLightMatrix = t,
            this._projectionTextureProjectionLightDirty = !1,
            this._projectionTextureDirty = !0
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getClassName = function() {
        return "SpotLight"
    }
    ,
    e.prototype.getTypeID = function() {
        return Light.LIGHTTYPEID_SPOTLIGHT
    }
    ,
    e.prototype._setDirection = function(t) {
        i.prototype._setDirection.call(this, t),
        this._projectionTextureViewLightDirty = !0
    }
    ,
    e.prototype._setPosition = function(t) {
        i.prototype._setPosition.call(this, t),
        this._projectionTextureViewLightDirty = !0
    }
    ,
    e.prototype._setDefaultShadowProjectionMatrix = function(t, r, n) {
        var o = this.getScene().activeCamera;
        if (!!o) {
            this._shadowAngleScale = this._shadowAngleScale || 1;
            var a = this._shadowAngleScale * this._angle
              , s = this.shadowMinZ !== void 0 ? this.shadowMinZ : o.minZ
              , l = this.shadowMaxZ !== void 0 ? this.shadowMaxZ : o.maxZ
              , u = this.getScene().getEngine().useReverseDepthBuffer;
            Matrix.PerspectiveFovLHToRef(a, 1, u ? l : s, u ? s : l, t, !0, this._scene.getEngine().isNDCHalfZRange, void 0, u)
        }
    }
    ,
    e.prototype._computeProjectionTextureViewLightMatrix = function() {
        this._projectionTextureViewLightDirty = !1,
        this._projectionTextureDirty = !0,
        this.position.addToRef(this.direction, this._projectionTextureViewTargetVector),
        Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix)
    }
    ,
    e.prototype._computeProjectionTextureProjectionLightMatrix = function() {
        this._projectionTextureProjectionLightDirty = !1,
        this._projectionTextureDirty = !0;
        var t = this.projectionTextureLightFar
          , r = this.projectionTextureLightNear
          , n = t / (t - r)
          , o = -n * r
          , a = 1 / Math.tan(this._angle / 2)
          , s = 1;
        Matrix.FromValuesToRef(a / s, 0, 0, 0, 0, a, 0, 0, 0, 0, n, 1, 0, 0, o, 0, this._projectionTextureProjectionLightMatrix)
    }
    ,
    e.prototype._computeProjectionTextureMatrix = function() {
        if (this._projectionTextureDirty = !1,
        this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix),
        this._projectionTexture instanceof Texture) {
            var t = this._projectionTexture.uScale / 2
              , r = this._projectionTexture.vScale / 2;
            Matrix.FromValuesToRef(t, 0, 0, 0, 0, r, 0, 0, 0, 0, .5, 0, .5, .5, .5, 1, this._projectionTextureScalingMatrix)
        }
        this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix)
    }
    ,
    e.prototype._buildUniformLayout = function() {
        this._uniformBuffer.addUniform("vLightData", 4),
        this._uniformBuffer.addUniform("vLightDiffuse", 4),
        this._uniformBuffer.addUniform("vLightSpecular", 4),
        this._uniformBuffer.addUniform("vLightDirection", 3),
        this._uniformBuffer.addUniform("vLightFalloff", 4),
        this._uniformBuffer.addUniform("shadowsInfo", 3),
        this._uniformBuffer.addUniform("depthValues", 2),
        this._uniformBuffer.create()
    }
    ,
    e.prototype._computeAngleValues = function() {
        this._lightAngleScale = 1 / Math.max(.001, Math.cos(this._innerAngle * .5) - this._cosHalfAngle),
        this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale
    }
    ,
    e.prototype.transferTexturesToEffect = function(t, r) {
        return this.projectionTexture && this.projectionTexture.isReady() && (this._projectionTextureViewLightDirty && this._computeProjectionTextureViewLightMatrix(),
        this._projectionTextureProjectionLightDirty && this._computeProjectionTextureProjectionLightMatrix(),
        this._projectionTextureDirty && this._computeProjectionTextureMatrix(),
        t.setMatrix("textureProjectionMatrix" + r, this._projectionTextureMatrix),
        t.setTexture("projectionLightSampler" + r, this.projectionTexture)),
        this
    }
    ,
    e.prototype.transferToEffect = function(t, r) {
        var n;
        return this.computeTransformedInformation() ? (this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, r),
        n = Vector3.Normalize(this.transformedDirection)) : (this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, r),
        n = Vector3.Normalize(this.direction)),
        this._uniformBuffer.updateFloat4("vLightDirection", n.x, n.y, n.z, this._cosHalfAngle, r),
        this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, r),
        this
    }
    ,
    e.prototype.transferToNodeMaterialEffect = function(t, r) {
        var n;
        return this.computeTransformedInformation() ? n = Vector3.Normalize(this.transformedDirection) : n = Vector3.Normalize(this.direction),
        this.getScene().useRightHandedSystem ? t.setFloat3(r, -n.x, -n.y, -n.z) : t.setFloat3(r, n.x, n.y, n.z),
        this
    }
    ,
    e.prototype.dispose = function() {
        i.prototype.dispose.call(this),
        this._projectionTexture && this._projectionTexture.dispose()
    }
    ,
    e.prototype.getDepthMinZ = function(t) {
        var r = this._scene.getEngine()
          , n = this.shadowMinZ !== void 0 ? this.shadowMinZ : t.minZ;
        return r.useReverseDepthBuffer && r.isNDCHalfZRange ? n : this._scene.getEngine().isNDCHalfZRange ? 0 : n
    }
    ,
    e.prototype.getDepthMaxZ = function(t) {
        var r = this._scene.getEngine()
          , n = this.shadowMaxZ !== void 0 ? this.shadowMaxZ : t.maxZ;
        return r.useReverseDepthBuffer && r.isNDCHalfZRange ? 0 : n
    }
    ,
    e.prototype.prepareLightSpecificDefines = function(t, r) {
        t["SPOTLIGHT" + r] = !0,
        t["PROJECTEDLIGHTTEXTURE" + r] = !!(this.projectionTexture && this.projectionTexture.isReady())
    }
    ,
    __decorate([serialize()], e.prototype, "angle", null),
    __decorate([serialize()], e.prototype, "innerAngle", null),
    __decorate([serialize()], e.prototype, "shadowAngleScale", null),
    __decorate([serialize()], e.prototype, "exponent", void 0),
    __decorate([serialize()], e.prototype, "projectionTextureLightNear", null),
    __decorate([serialize()], e.prototype, "projectionTextureLightFar", null),
    __decorate([serialize()], e.prototype, "projectionTextureUpDirection", null),
    __decorate([serializeAsTexture("projectedLightTexture")], e.prototype, "_projectionTexture", void 0),
    e
}(ShadowLight)
  , name$V = "glowMapGenerationPixelShader"
  , shader$V = `#if defined(DIFFUSE_ISLINEAR) || defined(EMISSIVE_ISLINEAR)
#include<helperFunctions>
#endif
#ifdef DIFFUSE
varying vec2 vUVDiffuse;
uniform sampler2D diffuseSampler;
#endif
#ifdef OPACITY
varying vec2 vUVOpacity;
uniform sampler2D opacitySampler;
uniform float opacityIntensity;
#endif
#ifdef EMISSIVE
varying vec2 vUVEmissive;
uniform sampler2D emissiveSampler;
#endif
#ifdef VERTEXALPHA
varying vec4 vColor;
#endif
uniform vec4 glowColor;
void main(void)
{
vec4 finalColor=glowColor;

#ifdef DIFFUSE
vec4 albedoTexture=texture2D(diffuseSampler,vUVDiffuse);
#ifdef DIFFUSE_ISLINEAR
albedoTexture=toGammaSpace(albedoTexture);
#endif
#ifdef GLOW

finalColor.a*=albedoTexture.a;
#endif
#ifdef HIGHLIGHT

finalColor.a=albedoTexture.a;
#endif
#endif
#ifdef OPACITY
vec4 opacityMap=texture2D(opacitySampler,vUVOpacity);
#ifdef OPACITYRGB
finalColor.a*=getLuminance(opacityMap.rgb);
#else
finalColor.a*=opacityMap.a;
#endif
finalColor.a*=opacityIntensity;
#endif
#ifdef VERTEXALPHA
finalColor.a*=vColor.a;
#endif
#ifdef ALPHATEST
if (finalColor.a<ALPHATESTVALUE)
discard;
#endif
#ifdef EMISSIVE
vec4 emissive=texture2D(emissiveSampler,vUVEmissive);
#ifdef EMISSIVE_ISLINEAR
emissive=toGammaSpace(emissive);
#endif
gl_FragColor=emissive*finalColor;
#else
gl_FragColor=finalColor;
#endif
#ifdef HIGHLIGHT

gl_FragColor.a=glowColor.a;
#endif
}`;
ShaderStore.ShadersStore[name$V] = shader$V;
var name$U = "glowMapGenerationVertexShader"
  , shader$U = `
attribute vec3 position;
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]

#include<instancesDeclaration>
uniform mat4 viewProjection;
varying vec4 vPosition;
#ifdef UV1
attribute vec2 uv;
#endif
#ifdef UV2
attribute vec2 uv2;
#endif
#ifdef DIFFUSE
varying vec2 vUVDiffuse;
uniform mat4 diffuseMatrix;
#endif
#ifdef OPACITY
varying vec2 vUVOpacity;
uniform mat4 opacityMatrix;
#endif
#ifdef EMISSIVE
varying vec2 vUVEmissive;
uniform mat4 emissiveMatrix;
#endif
#ifdef VERTEXALPHA
attribute vec4 color;
varying vec4 vColor;
#endif
void main(void)
{
vec3 positionUpdated=position;
#ifdef UV1
vec2 uvUpdated=uv;
#endif
#include<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
#include<instancesVertex>
#include<bonesVertex>
#include<bakedVertexAnimation>
#ifdef CUBEMAP
vPosition=finalWorld*vec4(positionUpdated,1.0);
gl_Position=viewProjection*finalWorld*vec4(position,1.0);
#else
vPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);
gl_Position=vPosition;
#endif
#ifdef DIFFUSE
#ifdef DIFFUSEUV1
vUVDiffuse=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));
#endif
#ifdef DIFFUSEUV2
vUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));
#endif
#endif
#ifdef OPACITY
#ifdef OPACITYUV1
vUVOpacity=vec2(opacityMatrix*vec4(uvUpdated,1.0,0.0));
#endif
#ifdef OPACITYUV2
vUVOpacity=vec2(opacityMatrix*vec4(uv2,1.0,0.0));
#endif
#endif
#ifdef EMISSIVE
#ifdef EMISSIVEUV1
vUVEmissive=vec2(emissiveMatrix*vec4(uvUpdated,1.0,0.0));
#endif
#ifdef EMISSIVEUV2
vUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));
#endif
#endif
#ifdef VERTEXALPHA
vColor=color;
#endif
}`;
ShaderStore.ShadersStore[name$U] = shader$U;
var EffectLayer = function() {
    function i(e, t) {
        this._vertexBuffers = {},
        this._maxSize = 0,
        this._mainTextureDesiredSize = {
            width: 0,
            height: 0
        },
        this._shouldRender = !0,
        this._postProcesses = [],
        this._textures = [],
        this._emissiveTextureAndColor = {
            texture: null,
            color: new Color4
        },
        this.neutralColor = new Color4,
        this.isEnabled = !0,
        this.disableBoundingBoxesFromEffectLayer = !1,
        this.onDisposeObservable = new Observable,
        this.onBeforeRenderMainTextureObservable = new Observable,
        this.onBeforeComposeObservable = new Observable,
        this.onBeforeRenderMeshToEffect = new Observable,
        this.onAfterRenderMeshToEffect = new Observable,
        this.onAfterComposeObservable = new Observable,
        this.onSizeChangedObservable = new Observable,
        this.name = e,
        this._scene = t || EngineStore.LastCreatedScene,
        i._SceneComponentInitialization(this._scene),
        this._engine = this._scene.getEngine(),
        this._maxSize = this._engine.getCaps().maxTextureSize,
        this._scene.effectLayers.push(this),
        this._mergeDrawWrapper = [],
        this._generateIndexBuffer(),
        this._generateVertexBuffer()
    }
    return Object.defineProperty(i.prototype, "camera", {
        get: function() {
            return this._effectLayerOptions.camera
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "renderingGroupId", {
        get: function() {
            return this._effectLayerOptions.renderingGroupId
        },
        set: function(e) {
            this._effectLayerOptions.renderingGroupId = e
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.setMaterialForRendering = function(e, t) {
        this._mainTexture.setMaterialForRendering(e, t)
    }
    ,
    i.prototype._numInternalDraws = function() {
        return 1
    }
    ,
    i.prototype._init = function(e) {
        this._effectLayerOptions = __assign({
            mainTextureRatio: .5,
            alphaBlendingMode: 2,
            camera: null,
            renderingGroupId: -1
        }, e),
        this._setMainTextureSize(),
        this._createMainTexture(),
        this._createTextureAndPostProcesses()
    }
    ,
    i.prototype._generateIndexBuffer = function() {
        var e = [];
        e.push(0),
        e.push(1),
        e.push(2),
        e.push(0),
        e.push(2),
        e.push(3),
        this._indexBuffer = this._engine.createIndexBuffer(e)
    }
    ,
    i.prototype._generateVertexBuffer = function() {
        var e = [];
        e.push(1, 1),
        e.push(-1, 1),
        e.push(-1, -1),
        e.push(1, -1);
        var t = new VertexBuffer(this._engine,e,VertexBuffer.PositionKind,!1,!1,2);
        this._vertexBuffers[VertexBuffer.PositionKind] = t
    }
    ,
    i.prototype._setMainTextureSize = function() {
        this._effectLayerOptions.mainTextureFixedSize ? (this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize,
        this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize) : (this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio,
        this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio,
        this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? Engine.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width,
        this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? Engine.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)
    }
    ,
    i.prototype._createMainTexture = function() {
        var e = this;
        if (this._mainTexture = new RenderTargetTexture("EffectLayerMainRTT",{
            width: this._mainTextureDesiredSize.width,
            height: this._mainTextureDesiredSize.height
        },this._scene,!1,!0,0),
        this._mainTexture.activeCamera = this._effectLayerOptions.camera,
        this._mainTexture.wrapU = Texture.CLAMP_ADDRESSMODE,
        this._mainTexture.wrapV = Texture.CLAMP_ADDRESSMODE,
        this._mainTexture.anisotropicFilteringLevel = 1,
        this._mainTexture.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE),
        this._mainTexture.renderParticles = !1,
        this._mainTexture.renderList = null,
        this._mainTexture.ignoreCameraViewport = !0,
        this._mainTexture.customRenderFunction = function(r, n, o, a) {
            e.onBeforeRenderMainTextureObservable.notifyObservers(e);
            var s, l = e._scene.getEngine();
            if (a.length) {
                for (l.setColorWrite(!1),
                s = 0; s < a.length; s++)
                    e._renderSubMesh(a.data[s]);
                l.setColorWrite(!0)
            }
            for (s = 0; s < r.length; s++)
                e._renderSubMesh(r.data[s]);
            for (s = 0; s < n.length; s++)
                e._renderSubMesh(n.data[s]);
            var u = l.getAlphaMode();
            for (s = 0; s < o.length; s++)
                e._renderSubMesh(o.data[s], !0);
            l.setAlphaMode(u)
        }
        ,
        this._mainTexture.onClearObservable.add(function(r) {
            r.clear(e.neutralColor, !0, !0, !0)
        }),
        this._scene.getBoundingBoxRenderer) {
            var t = this._scene.getBoundingBoxRenderer().enabled;
            this._mainTexture.onBeforeBindObservable.add(function() {
                e._scene.getBoundingBoxRenderer().enabled = !e.disableBoundingBoxesFromEffectLayer && t
            }),
            this._mainTexture.onAfterUnbindObservable.add(function() {
                e._scene.getBoundingBoxRenderer().enabled = t
            })
        }
    }
    ,
    i.prototype._addCustomEffectDefines = function(e) {}
    ,
    i.prototype._isReady = function(e, t, r) {
        var n, o = this._scene.getEngine(), a = e.getMesh(), s = (n = a._internalAbstractMeshDataInfo._materialForRenderPass) === null || n === void 0 ? void 0 : n[o.currentRenderPassId];
        if (s)
            return s.isReadyForSubMesh(a, e, t);
        var l = e.getMaterial();
        if (!l)
            return !1;
        if (this._useMeshMaterial(e.getRenderingMesh()))
            return l.isReadyForSubMesh(e.getMesh(), e, t);
        var u = []
          , c = [VertexBuffer.PositionKind]
          , h = !1
          , f = !1;
        if (l) {
            var d = l.needAlphaTesting()
              , _ = l.getAlphaTestTexture()
              , g = _ && _.hasAlpha && (l.useAlphaFromDiffuseTexture || l._useAlphaFromAlbedoTexture);
            _ && (d || g) && (u.push("#define DIFFUSE"),
            a.isVerticesDataPresent(VertexBuffer.UV2Kind) && _.coordinatesIndex === 1 ? (u.push("#define DIFFUSEUV2"),
            f = !0) : a.isVerticesDataPresent(VertexBuffer.UVKind) && (u.push("#define DIFFUSEUV1"),
            h = !0),
            d && (u.push("#define ALPHATEST"),
            u.push("#define ALPHATESTVALUE 0.4")),
            _.gammaSpace || u.push("#define DIFFUSE_ISLINEAR"));
            var m = l.opacityTexture;
            m && (u.push("#define OPACITY"),
            a.isVerticesDataPresent(VertexBuffer.UV2Kind) && m.coordinatesIndex === 1 ? (u.push("#define OPACITYUV2"),
            f = !0) : a.isVerticesDataPresent(VertexBuffer.UVKind) && (u.push("#define OPACITYUV1"),
            h = !0))
        }
        r && (u.push("#define EMISSIVE"),
        a.isVerticesDataPresent(VertexBuffer.UV2Kind) && r.coordinatesIndex === 1 ? (u.push("#define EMISSIVEUV2"),
        f = !0) : a.isVerticesDataPresent(VertexBuffer.UVKind) && (u.push("#define EMISSIVEUV1"),
        h = !0),
        r.gammaSpace || u.push("#define EMISSIVE_ISLINEAR")),
        a.isVerticesDataPresent(VertexBuffer.ColorKind) && a.hasVertexAlpha && (c.push(VertexBuffer.ColorKind),
        u.push("#define VERTEXALPHA")),
        h && (c.push(VertexBuffer.UVKind),
        u.push("#define UV1")),
        f && (c.push(VertexBuffer.UV2Kind),
        u.push("#define UV2"));
        var v = new EffectFallbacks;
        if (a.useBones && a.computeBonesUsingShaders) {
            c.push(VertexBuffer.MatricesIndicesKind),
            c.push(VertexBuffer.MatricesWeightsKind),
            a.numBoneInfluencers > 4 && (c.push(VertexBuffer.MatricesIndicesExtraKind),
            c.push(VertexBuffer.MatricesWeightsExtraKind)),
            u.push("#define NUM_BONE_INFLUENCERS " + a.numBoneInfluencers);
            var y = a.skeleton;
            y && y.isUsingTextureForMatrices ? u.push("#define BONETEXTURE") : u.push("#define BonesPerMesh " + (y ? y.bones.length + 1 : 0)),
            a.numBoneInfluencers > 0 && v.addCPUSkinningFallback(0, a)
        } else
            u.push("#define NUM_BONE_INFLUENCERS 0");
        var b = a.morphTargetManager
          , T = 0;
        b && b.numInfluencers > 0 && (u.push("#define MORPHTARGETS"),
        T = b.numInfluencers,
        u.push("#define NUM_MORPH_INFLUENCERS " + T),
        b.isUsingTextureForTargets && u.push("#define MORPHTARGETS_TEXTURE"),
        MaterialHelper.PrepareAttributesForMorphTargetsInfluencers(c, a, T)),
        t && (u.push("#define INSTANCES"),
        MaterialHelper.PushAttributesForInstances(c),
        e.getRenderingMesh().hasThinInstances && u.push("#define THIN_INSTANCES")),
        this._addCustomEffectDefines(u);
        var C = e._getDrawWrapper(void 0, !0)
          , A = C.defines
          , S = u.join(`
`);
        return A !== S && C.setEffect(this._engine.createEffect("glowMapGeneration", c, ["world", "mBones", "viewProjection", "glowColor", "morphTargetInfluences", "boneTextureWidth", "diffuseMatrix", "emissiveMatrix", "opacityMatrix", "opacityIntensity", "morphTargetTextureInfo", "morphTargetTextureIndices"], ["diffuseSampler", "emissiveSampler", "opacitySampler", "boneSampler", "morphTargets"], S, v, void 0, void 0, {
            maxSimultaneousMorphTargets: T
        }), S),
        C.effect.isReady()
    }
    ,
    i.prototype.render = function() {
        for (var e = 0; e < this._postProcesses.length; e++)
            if (!this._postProcesses[e].isReady())
                return;
        for (var t = this._scene.getEngine(), r = this._numInternalDraws(), n = !0, o = 0; o < r; ++o) {
            var a = this._mergeDrawWrapper[o];
            a || (a = this._mergeDrawWrapper[o] = new DrawWrapper(this._engine),
            a.setEffect(this._createMergeEffect())),
            n = n && a.effect.isReady()
        }
        if (!!n) {
            this.onBeforeComposeObservable.notifyObservers(this);
            for (var s = t.getAlphaMode(), l = 0; l < r; ++l) {
                var a = this._mergeDrawWrapper[l];
                t.enableEffect(a),
                t.setState(!1),
                t.bindBuffers(this._vertexBuffers, this._indexBuffer, a.effect),
                t.setAlphaMode(this._effectLayerOptions.alphaBlendingMode),
                this._internalRender(a.effect, l)
            }
            t.setAlphaMode(s),
            this.onAfterComposeObservable.notifyObservers(this);
            var u = this._mainTexture.getSize();
            this._setMainTextureSize(),
            (u.width !== this._mainTextureDesiredSize.width || u.height !== this._mainTextureDesiredSize.height) && this._mainTextureDesiredSize.width !== 0 && this._mainTextureDesiredSize.height !== 0 && (this.onSizeChangedObservable.notifyObservers(this),
            this._disposeTextureAndPostProcesses(),
            this._createMainTexture(),
            this._createTextureAndPostProcesses())
        }
    }
    ,
    i.prototype.hasMesh = function(e) {
        return this.renderingGroupId === -1 || e.renderingGroupId === this.renderingGroupId
    }
    ,
    i.prototype.shouldRender = function() {
        return this.isEnabled && this._shouldRender
    }
    ,
    i.prototype._shouldRenderMesh = function(e) {
        return !0
    }
    ,
    i.prototype._canRenderMesh = function(e, t) {
        return !t.needAlphaBlendingForMesh(e)
    }
    ,
    i.prototype._shouldRenderEmissiveTextureForMesh = function() {
        return !0
    }
    ,
    i.prototype._renderSubMesh = function(e, t) {
        var r, n;
        if (t === void 0 && (t = !1),
        !!this.shouldRender()) {
            var o = e.getMaterial()
              , a = e.getMesh()
              , s = e.getReplacementMesh()
              , l = e.getRenderingMesh()
              , u = e.getEffectiveMesh()
              , c = this._scene
              , h = c.getEngine();
            if (u._internalAbstractMeshDataInfo._isActiveIntermediate = !1,
            !!o && !!this._canRenderMesh(l, o)) {
                var f = (r = l.overrideMaterialSideOrientation) !== null && r !== void 0 ? r : o.sideOrientation
                  , d = l._getWorldMatrixDeterminant();
                d < 0 && (f = f === Material.ClockWiseSideOrientation ? Material.CounterClockWiseSideOrientation : Material.ClockWiseSideOrientation);
                var _ = f === Material.ClockWiseSideOrientation;
                h.setState(o.backFaceCulling, o.zOffset, void 0, _, o.cullBackFaces, void 0, o.zOffsetUnits);
                var g = l._getInstancesRenderList(e._id, !!s);
                if (!g.mustReturn && !!this._shouldRenderMesh(l)) {
                    var m = g.hardwareInstancedRendering[e._id] || l.hasThinInstances;
                    if (this._setEmissiveTextureAndColor(l, e, o),
                    this.onBeforeRenderMeshToEffect.notifyObservers(a),
                    this._useMeshMaterial(l))
                        l.render(e, m, s || void 0);
                    else if (this._isReady(e, m, this._emissiveTextureAndColor.texture)) {
                        var v = (n = u._internalAbstractMeshDataInfo._materialForRenderPass) === null || n === void 0 ? void 0 : n[h.currentRenderPassId]
                          , y = e._getDrawWrapper();
                        if (!y && v && (y = v._getDrawWrapper()),
                        !y)
                            return;
                        var b = y.effect;
                        if (h.enableEffect(y),
                        !m) {
                            var T = c.forcePointsCloud ? Material.PointFillMode : c.forceWireframe ? Material.WireFrameFillMode : o.fillMode;
                            l._bind(e, b, T)
                        }
                        if (v ? v.bindForSubMesh(u.getWorldMatrix(), u, e) : (b.setMatrix("viewProjection", c.getTransformMatrix()),
                        b.setMatrix("world", u.getWorldMatrix()),
                        b.setFloat4("glowColor", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a)),
                        !v) {
                            var C = o.needAlphaTesting()
                              , A = o.getAlphaTestTexture()
                              , S = A && A.hasAlpha && (o.useAlphaFromDiffuseTexture || o._useAlphaFromAlbedoTexture);
                            if (A && (C || S)) {
                                b.setTexture("diffuseSampler", A);
                                var P = A.getTextureMatrix();
                                P && b.setMatrix("diffuseMatrix", P)
                            }
                            var R = o.opacityTexture;
                            if (R) {
                                b.setTexture("opacitySampler", R),
                                b.setFloat("opacityIntensity", R.level);
                                var P = R.getTextureMatrix();
                                P && b.setMatrix("opacityMatrix", P)
                            }
                            if (this._emissiveTextureAndColor.texture && (b.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture),
                            b.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix())),
                            l.useBones && l.computeBonesUsingShaders && l.skeleton) {
                                var M = l.skeleton;
                                if (M.isUsingTextureForMatrices) {
                                    var x = M.getTransformMatrixTexture(l);
                                    if (!x)
                                        return;
                                    b.setTexture("boneSampler", x),
                                    b.setFloat("boneTextureWidth", 4 * (M.bones.length + 1))
                                } else
                                    b.setMatrices("mBones", M.getTransformMatrices(l))
                            }
                            MaterialHelper.BindMorphTargetParameters(l, b),
                            l.morphTargetManager && l.morphTargetManager.isUsingTextureForTargets && l.morphTargetManager._bind(b),
                            t && h.setAlphaMode(o.alphaMode)
                        }
                        l._processRendering(u, e, b, o.fillMode, g, m, function(I, w) {
                            return b.setMatrix("world", w)
                        })
                    } else
                        this._mainTexture.resetRefreshCounter();
                    this.onAfterRenderMeshToEffect.notifyObservers(a)
                }
            }
        }
    }
    ,
    i.prototype._useMeshMaterial = function(e) {
        return !1
    }
    ,
    i.prototype._rebuild = function() {
        var e = this._vertexBuffers[VertexBuffer.PositionKind];
        e && e._rebuild(),
        this._generateIndexBuffer()
    }
    ,
    i.prototype._disposeTextureAndPostProcesses = function() {
        this._mainTexture.dispose();
        for (var e = 0; e < this._postProcesses.length; e++)
            this._postProcesses[e] && this._postProcesses[e].dispose();
        this._postProcesses = [];
        for (var e = 0; e < this._textures.length; e++)
            this._textures[e] && this._textures[e].dispose();
        this._textures = []
    }
    ,
    i.prototype.dispose = function() {
        var e = this._vertexBuffers[VertexBuffer.PositionKind];
        e && (e.dispose(),
        this._vertexBuffers[VertexBuffer.PositionKind] = null),
        this._indexBuffer && (this._scene.getEngine()._releaseBuffer(this._indexBuffer),
        this._indexBuffer = null);
        for (var t = 0, r = this._mergeDrawWrapper; t < r.length; t++) {
            var n = r[t];
            n.dispose()
        }
        this._mergeDrawWrapper = [],
        this._disposeTextureAndPostProcesses();
        var o = this._scene.effectLayers.indexOf(this, 0);
        o > -1 && this._scene.effectLayers.splice(o, 1),
        this.onDisposeObservable.notifyObservers(this),
        this.onDisposeObservable.clear(),
        this.onBeforeRenderMainTextureObservable.clear(),
        this.onBeforeComposeObservable.clear(),
        this.onBeforeRenderMeshToEffect.clear(),
        this.onAfterRenderMeshToEffect.clear(),
        this.onAfterComposeObservable.clear(),
        this.onSizeChangedObservable.clear()
    }
    ,
    i.prototype.getClassName = function() {
        return "EffectLayer"
    }
    ,
    i.Parse = function(e, t, r) {
        var n = Tools.Instantiate(e.customType);
        return n.Parse(e, t, r)
    }
    ,
    i._SceneComponentInitialization = function(e) {
        throw _WarnImport("EffectLayerSceneComponent")
    }
    ,
    __decorate([serialize()], i.prototype, "name", void 0),
    __decorate([serializeAsColor4()], i.prototype, "neutralColor", void 0),
    __decorate([serialize()], i.prototype, "isEnabled", void 0),
    __decorate([serializeAsCameraReference()], i.prototype, "camera", null),
    __decorate([serialize()], i.prototype, "renderingGroupId", null),
    __decorate([serialize()], i.prototype, "disableBoundingBoxesFromEffectLayer", void 0),
    i
}()
  , name$T = "glowMapMergePixelShader"
  , shader$T = `
varying vec2 vUV;
uniform sampler2D textureSampler;
#ifdef EMISSIVE
uniform sampler2D textureSampler2;
#endif

uniform float offset;
void main(void) {
vec4 baseColor=texture2D(textureSampler,vUV);
#ifdef EMISSIVE
baseColor+=texture2D(textureSampler2,vUV);
baseColor*=offset;
#else
baseColor.a=abs(offset-baseColor.a);
#ifdef STROKE
float alpha=smoothstep(.0,.1,baseColor.a);
baseColor.a=alpha;
baseColor.rgb=baseColor.rgb*alpha;
#endif
#endif
#if LDR
baseColor=clamp(baseColor,0.,1.0);
#endif
gl_FragColor=baseColor;
}`;
ShaderStore.ShadersStore[name$T] = shader$T;
var name$S = "glowMapMergeVertexShader"
  , shader$S = `
attribute vec2 position;

varying vec2 vUV;
const vec2 madd=vec2(0.5,0.5);
void main(void) {
vUV=position*madd+madd;
gl_Position=vec4(position,0.0,1.0);
}`;
ShaderStore.ShadersStore[name$S] = shader$S;
AbstractScene.AddParser(SceneComponentConstants.NAME_EFFECTLAYER, function(i, e, t, r) {
    if (i.effectLayers) {
        t.effectLayers || (t.effectLayers = new Array);
        for (var n = 0; n < i.effectLayers.length; n++) {
            var o = EffectLayer.Parse(i.effectLayers[n], e, r);
            t.effectLayers.push(o)
        }
    }
});
AbstractScene.prototype.removeEffectLayer = function(i) {
    var e = this.effectLayers.indexOf(i);
    return e !== -1 && this.effectLayers.splice(e, 1),
    e
}
;
AbstractScene.prototype.addEffectLayer = function(i) {
    this.effectLayers.push(i)
}
;
var EffectLayerSceneComponent = function() {
    function i(e) {
        this.name = SceneComponentConstants.NAME_EFFECTLAYER,
        this._renderEffects = !1,
        this._needStencil = !1,
        this._previousStencilState = !1,
        this.scene = e,
        this._engine = e.getEngine(),
        e.effectLayers = new Array
    }
    return i.prototype.register = function() {
        this.scene._isReadyForMeshStage.registerStep(SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh),
        this.scene._cameraDrawRenderTargetStage.registerStep(SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture),
        this.scene._beforeCameraDrawStage.registerStep(SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil),
        this.scene._afterRenderingGroupDrawStage.registerStep(SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup),
        this.scene._afterCameraDrawStage.registerStep(SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack),
        this.scene._afterCameraDrawStage.registerStep(SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera)
    }
    ,
    i.prototype.rebuild = function() {
        for (var e = this.scene.effectLayers, t = 0, r = e; t < r.length; t++) {
            var n = r[t];
            n._rebuild()
        }
    }
    ,
    i.prototype.serialize = function(e) {
        e.effectLayers = [];
        for (var t = this.scene.effectLayers, r = 0, n = t; r < n.length; r++) {
            var o = n[r];
            o.serialize && e.effectLayers.push(o.serialize())
        }
    }
    ,
    i.prototype.addFromContainer = function(e) {
        var t = this;
        !e.effectLayers || e.effectLayers.forEach(function(r) {
            t.scene.addEffectLayer(r)
        })
    }
    ,
    i.prototype.removeFromContainer = function(e, t) {
        var r = this;
        !e.effectLayers || e.effectLayers.forEach(function(n) {
            r.scene.removeEffectLayer(n),
            t && n.dispose()
        })
    }
    ,
    i.prototype.dispose = function() {
        for (var e = this.scene.effectLayers; e.length; )
            e[0].dispose()
    }
    ,
    i.prototype._isReadyForMesh = function(e, t) {
        for (var r = this._engine.currentRenderPassId, n = this.scene.effectLayers, o = 0, a = n; o < a.length; o++) {
            var s = a[o];
            if (!!s.hasMesh(e)) {
                var l = s._mainTexture;
                this._engine.currentRenderPassId = l.renderPassId;
                for (var u = 0, c = e.subMeshes; u < c.length; u++) {
                    var h = c[u];
                    if (!s.isReady(h, t))
                        return this._engine.currentRenderPassId = r,
                        !1
                }
            }
        }
        return this._engine.currentRenderPassId = r,
        !0
    }
    ,
    i.prototype._renderMainTexture = function(e) {
        this._renderEffects = !1,
        this._needStencil = !1;
        var t = !1
          , r = this.scene.effectLayers;
        if (r && r.length > 0) {
            this._previousStencilState = this._engine.getStencilBuffer();
            for (var n = 0, o = r; n < o.length; n++) {
                var a = o[n];
                if (a.shouldRender() && (!a.camera || a.camera.cameraRigMode === Camera$1.RIG_MODE_NONE && e === a.camera || a.camera.cameraRigMode !== Camera$1.RIG_MODE_NONE && a.camera._rigCameras.indexOf(e) > -1)) {
                    this._renderEffects = !0,
                    this._needStencil = this._needStencil || a.needStencil();
                    var s = a._mainTexture;
                    s._shouldRender() && (this.scene.incrementRenderId(),
                    s.render(!1, !1),
                    t = !0)
                }
            }
            this.scene.incrementRenderId()
        }
        return t
    }
    ,
    i.prototype._setStencil = function() {
        this._needStencil && this._engine.setStencilBuffer(!0)
    }
    ,
    i.prototype._setStencilBack = function() {
        this._needStencil && this._engine.setStencilBuffer(this._previousStencilState)
    }
    ,
    i.prototype._draw = function(e) {
        if (this._renderEffects) {
            this._engine.setDepthBuffer(!1);
            for (var t = this.scene.effectLayers, r = 0; r < t.length; r++) {
                var n = t[r];
                n.renderingGroupId === e && n.shouldRender() && n.render()
            }
            this._engine.setDepthBuffer(!0)
        }
    }
    ,
    i.prototype._drawCamera = function() {
        this._renderEffects && this._draw(-1)
    }
    ,
    i.prototype._drawRenderingGroup = function(e) {
        !this.scene._isInIntermediateRendering() && this._renderEffects && this._draw(e)
    }
    ,
    i
}();
EffectLayer._SceneComponentInitialization = function(i) {
    var e = i._getComponent(SceneComponentConstants.NAME_EFFECTLAYER);
    e || (e = new EffectLayerSceneComponent(i),
    i._addComponent(e))
}
;
AbstractScene.prototype.getGlowLayerByName = function(i) {
    for (var e = 0; e < this.effectLayers.length; e++)
        if (this.effectLayers[e].name === i && this.effectLayers[e].getEffectName() === GlowLayer.EffectName)
            return this.effectLayers[e];
    return null
}
;
var GlowLayer = function(i) {
    __extends(e, i);
    function e(t, r, n) {
        var o = i.call(this, t, r) || this;
        return o._intensity = 1,
        o._includedOnlyMeshes = [],
        o._excludedMeshes = [],
        o._meshesUsingTheirOwnMaterials = [],
        o.neutralColor = new Color4(0,0,0,1),
        o._options = __assign({
            mainTextureRatio: e.DefaultTextureRatio,
            blurKernelSize: 32,
            mainTextureFixedSize: void 0,
            camera: null,
            mainTextureSamples: 1,
            renderingGroupId: -1,
            ldrMerge: !1,
            alphaBlendingMode: 1
        }, n),
        o._init({
            alphaBlendingMode: o._options.alphaBlendingMode,
            camera: o._options.camera,
            mainTextureFixedSize: o._options.mainTextureFixedSize,
            mainTextureRatio: o._options.mainTextureRatio,
            renderingGroupId: o._options.renderingGroupId
        }),
        o
    }
    return Object.defineProperty(e.prototype, "blurKernelSize", {
        get: function() {
            return this._horizontalBlurPostprocess1.kernel
        },
        set: function(t) {
            this._horizontalBlurPostprocess1.kernel = t,
            this._verticalBlurPostprocess1.kernel = t,
            this._horizontalBlurPostprocess2.kernel = t,
            this._verticalBlurPostprocess2.kernel = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "intensity", {
        get: function() {
            return this._intensity
        },
        set: function(t) {
            this._intensity = t
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getEffectName = function() {
        return e.EffectName
    }
    ,
    e.prototype._createMergeEffect = function() {
        var t = `#define EMISSIVE 
`;
        return this._options.ldrMerge && (t += `#define LDR 
`),
        this._engine.createEffect("glowMapMerge", [VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], t)
    }
    ,
    e.prototype._createTextureAndPostProcesses = function() {
        var t = this
          , r = this._mainTextureDesiredSize.width
          , n = this._mainTextureDesiredSize.height;
        r = this._engine.needPOTTextures ? Engine.GetExponentOfTwo(r, this._maxSize) : r,
        n = this._engine.needPOTTextures ? Engine.GetExponentOfTwo(n, this._maxSize) : n;
        var o = 0;
        this._engine.getCaps().textureHalfFloatRender ? o = 2 : o = 0,
        this._blurTexture1 = new RenderTargetTexture("GlowLayerBlurRTT",{
            width: r,
            height: n
        },this._scene,!1,!0,o),
        this._blurTexture1.wrapU = Texture.CLAMP_ADDRESSMODE,
        this._blurTexture1.wrapV = Texture.CLAMP_ADDRESSMODE,
        this._blurTexture1.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE),
        this._blurTexture1.renderParticles = !1,
        this._blurTexture1.ignoreCameraViewport = !0;
        var a = Math.floor(r / 2)
          , s = Math.floor(n / 2);
        this._blurTexture2 = new RenderTargetTexture("GlowLayerBlurRTT2",{
            width: a,
            height: s
        },this._scene,!1,!0,o),
        this._blurTexture2.wrapU = Texture.CLAMP_ADDRESSMODE,
        this._blurTexture2.wrapV = Texture.CLAMP_ADDRESSMODE,
        this._blurTexture2.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE),
        this._blurTexture2.renderParticles = !1,
        this._blurTexture2.ignoreCameraViewport = !0,
        this._textures = [this._blurTexture1, this._blurTexture2],
        this._horizontalBlurPostprocess1 = new BlurPostProcess("GlowLayerHBP1",new Vector2(1,0),this._options.blurKernelSize / 2,{
            width: r,
            height: n
        },null,Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,o),
        this._horizontalBlurPostprocess1.width = r,
        this._horizontalBlurPostprocess1.height = n,
        this._horizontalBlurPostprocess1.externalTextureSamplerBinding = !0,
        this._horizontalBlurPostprocess1.onApplyObservable.add(function(l) {
            l.setTexture("textureSampler", t._mainTexture)
        }),
        this._verticalBlurPostprocess1 = new BlurPostProcess("GlowLayerVBP1",new Vector2(0,1),this._options.blurKernelSize / 2,{
            width: r,
            height: n
        },null,Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,o),
        this._horizontalBlurPostprocess2 = new BlurPostProcess("GlowLayerHBP2",new Vector2(1,0),this._options.blurKernelSize / 2,{
            width: a,
            height: s
        },null,Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,o),
        this._horizontalBlurPostprocess2.width = a,
        this._horizontalBlurPostprocess2.height = s,
        this._horizontalBlurPostprocess2.externalTextureSamplerBinding = !0,
        this._horizontalBlurPostprocess2.onApplyObservable.add(function(l) {
            l.setTexture("textureSampler", t._blurTexture1)
        }),
        this._verticalBlurPostprocess2 = new BlurPostProcess("GlowLayerVBP2",new Vector2(0,1),this._options.blurKernelSize / 2,{
            width: a,
            height: s
        },null,Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,o),
        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 l = t._blurTexture1.renderTarget;
            if (l) {
                t._scene.postProcessManager.directRender(t._postProcesses1, l, !0);
                var u = t._blurTexture2.renderTarget;
                u && t._scene.postProcessManager.directRender(t._postProcesses2, u, !0),
                t._engine.unBindFramebuffer(u != null ? u : l, !0)
            }
        }),
        this._postProcesses.map(function(l) {
            l.autoClear = !1
        })
    }
    ,
    e.prototype.isReady = function(t, r) {
        var n = t.getMaterial()
          , o = t.getRenderingMesh();
        if (!n || !o)
            return !1;
        var a = n.emissiveTexture;
        return i.prototype._isReady.call(this, t, r, a)
    }
    ,
    e.prototype.needStencil = function() {
        return !1
    }
    ,
    e.prototype._canRenderMesh = function(t, r) {
        return !0
    }
    ,
    e.prototype._internalRender = function(t) {
        t.setTexture("textureSampler", this._blurTexture1),
        t.setTexture("textureSampler2", this._blurTexture2),
        t.setFloat("offset", this._intensity);
        var r = this._engine
          , n = r.getStencilBuffer();
        r.setStencilBuffer(!1),
        r.drawElementsType(Material.TriangleFillMode, 0, 6),
        r.setStencilBuffer(n)
    }
    ,
    e.prototype._setEmissiveTextureAndColor = function(t, r, n) {
        var o, a = 1;
        if (this.customEmissiveTextureSelector ? this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(t, r, n) : n ? (this._emissiveTextureAndColor.texture = n.emissiveTexture,
        this._emissiveTextureAndColor.texture && (a = this._emissiveTextureAndColor.texture.level)) : this._emissiveTextureAndColor.texture = null,
        this.customEmissiveColorSelector)
            this.customEmissiveColorSelector(t, r, n, this._emissiveTextureAndColor.color);
        else if (n.emissiveColor) {
            var s = (o = n.emissiveIntensity) !== null && o !== void 0 ? o : 1;
            a *= s,
            this._emissiveTextureAndColor.color.set(n.emissiveColor.r * a, n.emissiveColor.g * a, n.emissiveColor.b * a, n.alpha)
        } else
            this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a)
    }
    ,
    e.prototype._shouldRenderMesh = function(t) {
        return this.hasMesh(t)
    }
    ,
    e.prototype._addCustomEffectDefines = function(t) {
        t.push("#define GLOW")
    }
    ,
    e.prototype.addExcludedMesh = function(t) {
        this._excludedMeshes.indexOf(t.uniqueId) === -1 && this._excludedMeshes.push(t.uniqueId)
    }
    ,
    e.prototype.removeExcludedMesh = function(t) {
        var r = this._excludedMeshes.indexOf(t.uniqueId);
        r !== -1 && this._excludedMeshes.splice(r, 1)
    }
    ,
    e.prototype.addIncludedOnlyMesh = function(t) {
        this._includedOnlyMeshes.indexOf(t.uniqueId) === -1 && this._includedOnlyMeshes.push(t.uniqueId)
    }
    ,
    e.prototype.removeIncludedOnlyMesh = function(t) {
        var r = this._includedOnlyMeshes.indexOf(t.uniqueId);
        r !== -1 && this._includedOnlyMeshes.splice(r, 1)
    }
    ,
    e.prototype.hasMesh = function(t) {
        return i.prototype.hasMesh.call(this, t) ? this._includedOnlyMeshes.length ? this._includedOnlyMeshes.indexOf(t.uniqueId) !== -1 : this._excludedMeshes.length ? this._excludedMeshes.indexOf(t.uniqueId) === -1 : !0 : !1
    }
    ,
    e.prototype._useMeshMaterial = function(t) {
        return this._meshesUsingTheirOwnMaterials.length == 0 ? !1 : this._meshesUsingTheirOwnMaterials.indexOf(t.uniqueId) > -1
    }
    ,
    e.prototype.referenceMeshToUseItsOwnMaterial = function(t) {
        var r = this;
        this._meshesUsingTheirOwnMaterials.push(t.uniqueId),
        t.onDisposeObservable.add(function() {
            r._disposeMesh(t)
        })
    }
    ,
    e.prototype.unReferenceMeshFromUsingItsOwnMaterial = function(t) {
        for (var r = this._meshesUsingTheirOwnMaterials.indexOf(t.uniqueId); r >= 0; )
            this._meshesUsingTheirOwnMaterials.splice(r, 1),
            r = this._meshesUsingTheirOwnMaterials.indexOf(t.uniqueId)
    }
    ,
    e.prototype._disposeMesh = function(t) {
        this.removeIncludedOnlyMesh(t),
        this.removeExcludedMesh(t)
    }
    ,
    e.prototype.getClassName = function() {
        return "GlowLayer"
    }
    ,
    e.prototype.serialize = function() {
        var t = SerializationHelper.Serialize(this);
        t.customType = "BABYLON.GlowLayer";
        var r;
        if (t.includedMeshes = [],
        this._includedOnlyMeshes.length)
            for (r = 0; r < this._includedOnlyMeshes.length; r++) {
                var n = this._scene.getMeshByUniqueId(this._includedOnlyMeshes[r]);
                n && t.includedMeshes.push(n.id)
            }
        if (t.excludedMeshes = [],
        this._excludedMeshes.length)
            for (r = 0; r < this._excludedMeshes.length; r++) {
                var n = this._scene.getMeshByUniqueId(this._excludedMeshes[r]);
                n && t.excludedMeshes.push(n.id)
            }
        return t
    }
    ,
    e.Parse = function(t, r, n) {
        var o = SerializationHelper.Parse(function() {
            return new e(t.name,r,t.options)
        }, t, r, n), a;
        for (a = 0; a < t.excludedMeshes.length; a++) {
            var s = r.getMeshById(t.excludedMeshes[a]);
            s && o.addExcludedMesh(s)
        }
        for (a = 0; a < t.includedMeshes.length; a++) {
            var s = r.getMeshById(t.includedMeshes[a]);
            s && o.addIncludedOnlyMesh(s)
        }
        return o
    }
    ,
    e.EffectName = "GlowLayer",
    e.DefaultBlurKernelSize = 32,
    e.DefaultTextureRatio = .5,
    __decorate([serialize()], e.prototype, "blurKernelSize", null),
    __decorate([serialize()], e.prototype, "intensity", null),
    __decorate([serialize("options")], e.prototype, "_options", void 0),
    e
}(EffectLayer);
RegisterClass("BABYLON.GlowLayer", GlowLayer);
var name$R = "glowBlurPostProcessPixelShader"
  , shader$R = `
varying vec2 vUV;
uniform sampler2D textureSampler;

uniform vec2 screenSize;
uniform vec2 direction;
uniform float blurWidth;

float getLuminance(vec3 color)
{
return dot(color,vec3(0.2126,0.7152,0.0722));
}
void main(void)
{
float weights[7];
weights[0]=0.05;
weights[1]=0.1;
weights[2]=0.2;
weights[3]=0.3;
weights[4]=0.2;
weights[5]=0.1;
weights[6]=0.05;
vec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);
vec2 texelStep=texelSize*direction*blurWidth;
vec2 start=vUV-3.0*texelStep;
vec4 baseColor=vec4(0.,0.,0.,0.);
vec2 texelOffset=vec2(0.,0.);
for (int i=0; i<7; i++)
{

vec4 texel=texture2D(textureSampler,start+texelOffset);
baseColor.a+=texel.a*weights[i];

float luminance=getLuminance(baseColor.rgb);
float luminanceTexel=getLuminance(texel.rgb);
float choice=step(luminanceTexel,luminance);
baseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;
texelOffset+=texelStep;
}
gl_FragColor=baseColor;
}`;
ShaderStore.ShadersStore[name$R] = shader$R;
AbstractScene.prototype.getHighlightLayerByName = function(i) {
    for (var e = 0; e < this.effectLayers.length; e++)
        if (this.effectLayers[e].name === i && this.effectLayers[e].getEffectName() === HighlightLayer.EffectName)
            return this.effectLayers[e];
    return null
}
;
var GlowBlurPostProcess = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a, s, l, u) {
        s === void 0 && (s = Texture.BILINEAR_SAMPLINGMODE);
        var c = i.call(this, t, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, o, a, s, l, u) || this;
        return c.direction = r,
        c.kernel = n,
        c.onApplyObservable.add(function(h) {
            h.setFloat2("screenSize", c.width, c.height),
            h.setVector2("direction", c.direction),
            h.setFloat("blurWidth", c.kernel)
        }),
        c
    }
    return e
}(PostProcess)
  , HighlightLayer = function(i) {
    __extends(e, i);
    function e(t, r, n) {
        var o = i.call(this, t, r) || this;
        return o.name = t,
        o.innerGlow = !0,
        o.outerGlow = !0,
        o.onBeforeBlurObservable = new Observable,
        o.onAfterBlurObservable = new Observable,
        o._instanceGlowingMeshStencilReference = e.GlowingMeshStencilReference++,
        o._meshes = {},
        o._excludedMeshes = {},
        o.neutralColor = e.NeutralColor,
        o._engine.isStencilEnable || Logger$2.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new Engine(canvas, antialias, { stencil: true }"),
        o._options = __assign({
            mainTextureRatio: .5,
            blurTextureSizeRatio: .5,
            blurHorizontalSize: 1,
            blurVerticalSize: 1,
            alphaBlendingMode: 2,
            camera: null,
            renderingGroupId: -1
        }, n),
        o._init({
            alphaBlendingMode: o._options.alphaBlendingMode,
            camera: o._options.camera,
            mainTextureFixedSize: o._options.mainTextureFixedSize,
            mainTextureRatio: o._options.mainTextureRatio,
            renderingGroupId: o._options.renderingGroupId
        }),
        o._shouldRender = !1,
        o
    }
    return Object.defineProperty(e.prototype, "blurHorizontalSize", {
        get: function() {
            return this._horizontalBlurPostprocess.kernel
        },
        set: function(t) {
            this._horizontalBlurPostprocess.kernel = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "blurVerticalSize", {
        get: function() {
            return this._verticalBlurPostprocess.kernel
        },
        set: function(t) {
            this._verticalBlurPostprocess.kernel = t
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getEffectName = function() {
        return e.EffectName
    }
    ,
    e.prototype._numInternalDraws = function() {
        return 2
    }
    ,
    e.prototype._createMergeEffect = function() {
        return this._engine.createEffect("glowMapMerge", [VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? `#define STROKE 
` : void 0)
    }
    ,
    e.prototype._createTextureAndPostProcesses = function() {
        var t = this
          , r = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio
          , n = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
        r = this._engine.needPOTTextures ? Engine.GetExponentOfTwo(r, this._maxSize) : r,
        n = this._engine.needPOTTextures ? Engine.GetExponentOfTwo(n, this._maxSize) : n;
        var o = 0;
        this._engine.getCaps().textureHalfFloatRender ? o = 2 : o = 0,
        this._blurTexture = new RenderTargetTexture("HighlightLayerBlurRTT",{
            width: r,
            height: n
        },this._scene,!1,!0,o),
        this._blurTexture.wrapU = Texture.CLAMP_ADDRESSMODE,
        this._blurTexture.wrapV = Texture.CLAMP_ADDRESSMODE,
        this._blurTexture.anisotropicFilteringLevel = 16,
        this._blurTexture.updateSamplingMode(Texture.TRILINEAR_SAMPLINGMODE),
        this._blurTexture.renderParticles = !1,
        this._blurTexture.ignoreCameraViewport = !0,
        this._textures = [this._blurTexture],
        this._options.alphaBlendingMode === 2 ? (this._downSamplePostprocess = new PassPostProcess("HighlightLayerPPP",this._options.blurTextureSizeRatio,null,Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),
        this._downSamplePostprocess.externalTextureSamplerBinding = !0,
        this._downSamplePostprocess.onApplyObservable.add(function(a) {
            a.setTexture("textureSampler", t._mainTexture)
        }),
        this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP",new Vector2(1,0),this._options.blurHorizontalSize,1,null,Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),
        this._horizontalBlurPostprocess.onApplyObservable.add(function(a) {
            a.setFloat2("screenSize", r, n)
        }),
        this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP",new Vector2(0,1),this._options.blurVerticalSize,1,null,Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),
        this._verticalBlurPostprocess.onApplyObservable.add(function(a) {
            a.setFloat2("screenSize", r, n)
        }),
        this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess]) : (this._horizontalBlurPostprocess = new BlurPostProcess("HighlightLayerHBP",new Vector2(1,0),this._options.blurHorizontalSize / 2,{
            width: r,
            height: n
        },null,Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,o),
        this._horizontalBlurPostprocess.width = r,
        this._horizontalBlurPostprocess.height = n,
        this._horizontalBlurPostprocess.externalTextureSamplerBinding = !0,
        this._horizontalBlurPostprocess.onApplyObservable.add(function(a) {
            a.setTexture("textureSampler", t._mainTexture)
        }),
        this._verticalBlurPostprocess = new BlurPostProcess("HighlightLayerVBP",new Vector2(0,1),this._options.blurVerticalSize / 2,{
            width: r,
            height: n
        },null,Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,o),
        this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess]),
        this._mainTexture.onAfterUnbindObservable.add(function() {
            t.onBeforeBlurObservable.notifyObservers(t);
            var a = t._blurTexture.renderTarget;
            a && (t._scene.postProcessManager.directRender(t._postProcesses, a, !0),
            t._engine.unBindFramebuffer(a, !0)),
            t.onAfterBlurObservable.notifyObservers(t)
        }),
        this._postProcesses.map(function(a) {
            a.autoClear = !1
        })
    }
    ,
    e.prototype.needStencil = function() {
        return !0
    }
    ,
    e.prototype.isReady = function(t, r) {
        var n = t.getMaterial()
          , o = t.getRenderingMesh();
        if (!n || !o || !this._meshes)
            return !1;
        var a = null
          , s = this._meshes[o.uniqueId];
        return s && s.glowEmissiveOnly && n && (a = n.emissiveTexture),
        i.prototype._isReady.call(this, t, r, a)
    }
    ,
    e.prototype._internalRender = function(t, r) {
        t.setTexture("textureSampler", this._blurTexture);
        var n = this._engine;
        n.cacheStencilState(),
        n.setStencilOperationPass(7681),
        n.setStencilOperationFail(7680),
        n.setStencilOperationDepthFail(7680),
        n.setStencilMask(0),
        n.setStencilBuffer(!0),
        n.setStencilFunctionReference(this._instanceGlowingMeshStencilReference),
        this.outerGlow && r === 0 && (t.setFloat("offset", 0),
        n.setStencilFunction(517),
        n.drawElementsType(Material.TriangleFillMode, 0, 6)),
        this.innerGlow && r === 1 && (t.setFloat("offset", 1),
        n.setStencilFunction(514),
        n.drawElementsType(Material.TriangleFillMode, 0, 6)),
        n.restoreStencilState()
    }
    ,
    e.prototype.shouldRender = function() {
        return i.prototype.shouldRender.call(this) ? !!this._meshes : !1
    }
    ,
    e.prototype._shouldRenderMesh = function(t) {
        return !(this._excludedMeshes && this._excludedMeshes[t.uniqueId] || !i.prototype.hasMesh.call(this, t))
    }
    ,
    e.prototype._canRenderMesh = function(t, r) {
        return !0
    }
    ,
    e.prototype._addCustomEffectDefines = function(t) {
        t.push("#define HIGHLIGHT")
    }
    ,
    e.prototype._setEmissiveTextureAndColor = function(t, r, n) {
        var o = this._meshes[t.uniqueId];
        o ? this._emissiveTextureAndColor.color.set(o.color.r, o.color.g, o.color.b, 1) : this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a),
        o && o.glowEmissiveOnly && n ? (this._emissiveTextureAndColor.texture = n.emissiveTexture,
        this._emissiveTextureAndColor.color.set(1, 1, 1, 1)) : this._emissiveTextureAndColor.texture = null
    }
    ,
    e.prototype.addExcludedMesh = function(t) {
        if (!!this._excludedMeshes) {
            var r = this._excludedMeshes[t.uniqueId];
            r || (this._excludedMeshes[t.uniqueId] = {
                mesh: t,
                beforeBind: t.onBeforeBindObservable.add(function(n) {
                    n.getEngine().setStencilBuffer(!1)
                }),
                afterRender: t.onAfterRenderObservable.add(function(n) {
                    n.getEngine().setStencilBuffer(!0)
                })
            })
        }
    }
    ,
    e.prototype.removeExcludedMesh = function(t) {
        if (!!this._excludedMeshes) {
            var r = this._excludedMeshes[t.uniqueId];
            r && (r.beforeBind && t.onBeforeBindObservable.remove(r.beforeBind),
            r.afterRender && t.onAfterRenderObservable.remove(r.afterRender)),
            this._excludedMeshes[t.uniqueId] = null
        }
    }
    ,
    e.prototype.hasMesh = function(t) {
        return !this._meshes || !i.prototype.hasMesh.call(this, t) ? !1 : this._meshes[t.uniqueId] !== void 0 && this._meshes[t.uniqueId] !== null
    }
    ,
    e.prototype.addMesh = function(t, r, n) {
        var o = this;
        if (n === void 0 && (n = !1),
        !!this._meshes) {
            var a = this._meshes[t.uniqueId];
            a ? a.color = r : (this._meshes[t.uniqueId] = {
                mesh: t,
                color: r,
                observerHighlight: t.onBeforeBindObservable.add(function(s) {
                    o.isEnabled && (o._excludedMeshes && o._excludedMeshes[s.uniqueId] ? o._defaultStencilReference(s) : s.getScene().getEngine().setStencilFunctionReference(o._instanceGlowingMeshStencilReference))
                }),
                observerDefault: t.onAfterRenderObservable.add(function(s) {
                    o.isEnabled && o._defaultStencilReference(s)
                }),
                glowEmissiveOnly: n
            },
            t.onDisposeObservable.add(function() {
                o._disposeMesh(t)
            })),
            this._shouldRender = !0
        }
    }
    ,
    e.prototype.removeMesh = function(t) {
        if (!!this._meshes) {
            var r = this._meshes[t.uniqueId];
            r && (r.observerHighlight && t.onBeforeBindObservable.remove(r.observerHighlight),
            r.observerDefault && t.onAfterRenderObservable.remove(r.observerDefault),
            delete this._meshes[t.uniqueId]),
            this._shouldRender = !1;
            for (var n in this._meshes)
                if (this._meshes[n]) {
                    this._shouldRender = !0;
                    break
                }
        }
    }
    ,
    e.prototype.removeAllMeshes = function() {
        if (!!this._meshes) {
            for (var t in this._meshes)
                if (this._meshes.hasOwnProperty(t)) {
                    var r = this._meshes[t];
                    r && this.removeMesh(r.mesh)
                }
        }
    }
    ,
    e.prototype._defaultStencilReference = function(t) {
        t.getScene().getEngine().setStencilFunctionReference(e.NormalMeshStencilReference)
    }
    ,
    e.prototype._disposeMesh = function(t) {
        this.removeMesh(t),
        this.removeExcludedMesh(t)
    }
    ,
    e.prototype.dispose = function() {
        if (this._meshes) {
            for (var t in this._meshes) {
                var r = this._meshes[t];
                r && r.mesh && (r.observerHighlight && r.mesh.onBeforeBindObservable.remove(r.observerHighlight),
                r.observerDefault && r.mesh.onAfterRenderObservable.remove(r.observerDefault))
            }
            this._meshes = null
        }
        if (this._excludedMeshes) {
            for (var t in this._excludedMeshes) {
                var r = this._excludedMeshes[t];
                r && (r.beforeBind && r.mesh.onBeforeBindObservable.remove(r.beforeBind),
                r.afterRender && r.mesh.onAfterRenderObservable.remove(r.afterRender))
            }
            this._excludedMeshes = null
        }
        i.prototype.dispose.call(this)
    }
    ,
    e.prototype.getClassName = function() {
        return "HighlightLayer"
    }
    ,
    e.prototype.serialize = function() {
        var t = SerializationHelper.Serialize(this);
        if (t.customType = "BABYLON.HighlightLayer",
        t.meshes = [],
        this._meshes)
            for (var r in this._meshes) {
                var n = this._meshes[r];
                n && t.meshes.push({
                    glowEmissiveOnly: n.glowEmissiveOnly,
                    color: n.color.asArray(),
                    meshId: n.mesh.id
                })
            }
        if (t.excludedMeshes = [],
        this._excludedMeshes)
            for (var o in this._excludedMeshes) {
                var a = this._excludedMeshes[o];
                a && t.excludedMeshes.push(a.mesh.id)
            }
        return t
    }
    ,
    e.Parse = function(t, r, n) {
        var o = SerializationHelper.Parse(function() {
            return new e(t.name,r,t.options)
        }, t, r, n), a;
        for (a = 0; a < t.excludedMeshes.length; a++) {
            var s = r.getMeshById(t.excludedMeshes[a]);
            s && o.addExcludedMesh(s)
        }
        for (a = 0; a < t.meshes.length; a++) {
            var l = t.meshes[a]
              , s = r.getMeshById(l.meshId);
            s && o.addMesh(s, Color3.FromArray(l.color), l.glowEmissiveOnly)
        }
        return o
    }
    ,
    e.EffectName = "HighlightLayer",
    e.NeutralColor = new Color4(0,0,0,0),
    e.GlowingMeshStencilReference = 2,
    e.NormalMeshStencilReference = 1,
    __decorate([serialize()], e.prototype, "innerGlow", void 0),
    __decorate([serialize()], e.prototype, "outerGlow", void 0),
    __decorate([serialize()], e.prototype, "blurHorizontalSize", null),
    __decorate([serialize()], e.prototype, "blurVerticalSize", null),
    __decorate([serialize("options")], e.prototype, "_options", void 0),
    e
}(EffectLayer);
RegisterClass("BABYLON.HighlightLayer", HighlightLayer);
var name$Q = "sharpenPixelShader"
  , shader$Q = `
varying vec2 vUV;
uniform sampler2D textureSampler;
uniform vec2 screenSize;
uniform vec2 sharpnessAmounts;
void main(void)
{
vec2 onePixel=vec2(1.0,1.0)/screenSize;
vec4 color=texture2D(textureSampler,vUV);
vec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +
texture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +
texture2D(textureSampler,vUV+onePixel*vec2(1,0)) +
texture2D(textureSampler,vUV+onePixel*vec2(0,1)) -
color*4.0;
gl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);
}`;
ShaderStore.ShadersStore[name$Q] = shader$Q;
var SharpenPostProcess = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a, s, l, u) {
        l === void 0 && (l = 0),
        u === void 0 && (u = !1);
        var c = i.call(this, t, "sharpen", ["sharpnessAmounts", "screenSize"], null, r, n, o, a, s, null, l, void 0, null, u) || this;
        return c.colorAmount = 1,
        c.edgeAmount = .3,
        c.onApply = function(h) {
            h.setFloat2("screenSize", c.width, c.height),
            h.setFloat2("sharpnessAmounts", c.edgeAmount, c.colorAmount)
        }
        ,
        c
    }
    return e.prototype.getClassName = function() {
        return "SharpenPostProcess"
    }
    ,
    e._Parse = function(t, r, n, o) {
        return SerializationHelper.Parse(function() {
            return new e(t.name,t.options,r,t.renderTargetSamplingMode,n.getEngine(),t.textureType,t.reusable)
        }, t, n, o)
    }
    ,
    __decorate([serialize()], e.prototype, "colorAmount", void 0),
    __decorate([serialize()], e.prototype, "edgeAmount", void 0),
    e
}(PostProcess);
RegisterClass("BABYLON.SharpenPostProcess", SharpenPostProcess);
var name$P = "imageProcessingPixelShader"
  , shader$P = `
varying vec2 vUV;
uniform sampler2D textureSampler;
#include<imageProcessingDeclaration>
#include<helperFunctions>
#include<imageProcessingFunctions>
void main(void)
{
vec4 result=texture2D(textureSampler,vUV);
#ifdef IMAGEPROCESSING
#ifndef FROMLINEARSPACE

result.rgb=toLinearSpace(result.rgb);
#endif
result=applyImageProcessing(result);
#else

#ifdef FROMLINEARSPACE
result=applyImageProcessing(result);
#endif
#endif
gl_FragColor=result;
}`;
ShaderStore.ShadersStore[name$P] = shader$P;
var ImageProcessingPostProcess = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a, s, l, u) {
        n === void 0 && (n = null),
        l === void 0 && (l = 0);
        var c = i.call(this, t, "imageProcessing", [], [], r, n, o, a, s, null, l, "postprocess", null, !0) || this;
        return c._fromLinearSpace = !0,
        c._defines = {
            IMAGEPROCESSING: !1,
            VIGNETTE: !1,
            VIGNETTEBLENDMODEMULTIPLY: !1,
            VIGNETTEBLENDMODEOPAQUE: !1,
            TONEMAPPING: !1,
            TONEMAPPING_ACES: !1,
            CONTRAST: !1,
            COLORCURVES: !1,
            COLORGRADING: !1,
            COLORGRADING3D: !1,
            FROMLINEARSPACE: !1,
            SAMPLER3DGREENDEPTH: !1,
            SAMPLER3DBGRMAP: !1,
            IMAGEPROCESSINGPOSTPROCESS: !1,
            EXPOSURE: !1,
            SKIPFINALCOLORCLAMP: !1
        },
        u ? (u.applyByPostProcess = !0,
        c._attachImageProcessingConfiguration(u, !0),
        c.fromLinearSpace = !1) : (c._attachImageProcessingConfiguration(null, !0),
        c.imageProcessingConfiguration.applyByPostProcess = !0),
        c.onApply = function(h) {
            c.imageProcessingConfiguration.bind(h, c.aspectRatio)
        }
        ,
        c
    }
    return Object.defineProperty(e.prototype, "imageProcessingConfiguration", {
        get: function() {
            return this._imageProcessingConfiguration
        },
        set: function(t) {
            t.applyByPostProcess = !0,
            this._attachImageProcessingConfiguration(t)
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._attachImageProcessingConfiguration = function(t, r) {
        var n = this;
        if (r === void 0 && (r = !1),
        t !== this._imageProcessingConfiguration) {
            if (this._imageProcessingConfiguration && this._imageProcessingObserver && this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),
            t)
                this._imageProcessingConfiguration = t;
            else {
                var o = null
                  , a = this.getEngine()
                  , s = this.getCamera();
                if (s)
                    o = s.getScene();
                else if (a && a.scenes) {
                    var l = a.scenes;
                    o = l[l.length - 1]
                } else
                    o = EngineStore.LastCreatedScene;
                o ? this._imageProcessingConfiguration = o.imageProcessingConfiguration : this._imageProcessingConfiguration = new ImageProcessingConfiguration
            }
            this._imageProcessingConfiguration && (this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function() {
                n._updateParameters()
            })),
            r || this._updateParameters()
        }
    }
    ,
    Object.defineProperty(e.prototype, "isSupported", {
        get: function() {
            var t = this.getEffect();
            return !t || t.isSupported
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "colorCurves", {
        get: function() {
            return this.imageProcessingConfiguration.colorCurves
        },
        set: function(t) {
            this.imageProcessingConfiguration.colorCurves = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "colorCurvesEnabled", {
        get: function() {
            return this.imageProcessingConfiguration.colorCurvesEnabled
        },
        set: function(t) {
            this.imageProcessingConfiguration.colorCurvesEnabled = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "colorGradingTexture", {
        get: function() {
            return this.imageProcessingConfiguration.colorGradingTexture
        },
        set: function(t) {
            this.imageProcessingConfiguration.colorGradingTexture = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "colorGradingEnabled", {
        get: function() {
            return this.imageProcessingConfiguration.colorGradingEnabled
        },
        set: function(t) {
            this.imageProcessingConfiguration.colorGradingEnabled = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "exposure", {
        get: function() {
            return this.imageProcessingConfiguration.exposure
        },
        set: function(t) {
            this.imageProcessingConfiguration.exposure = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "toneMappingEnabled", {
        get: function() {
            return this._imageProcessingConfiguration.toneMappingEnabled
        },
        set: function(t) {
            this._imageProcessingConfiguration.toneMappingEnabled = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "toneMappingType", {
        get: function() {
            return this._imageProcessingConfiguration.toneMappingType
        },
        set: function(t) {
            this._imageProcessingConfiguration.toneMappingType = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "contrast", {
        get: function() {
            return this.imageProcessingConfiguration.contrast
        },
        set: function(t) {
            this.imageProcessingConfiguration.contrast = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "vignetteStretch", {
        get: function() {
            return this.imageProcessingConfiguration.vignetteStretch
        },
        set: function(t) {
            this.imageProcessingConfiguration.vignetteStretch = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "vignetteCentreX", {
        get: function() {
            return this.imageProcessingConfiguration.vignetteCentreX
        },
        set: function(t) {
            this.imageProcessingConfiguration.vignetteCentreX = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "vignetteCentreY", {
        get: function() {
            return this.imageProcessingConfiguration.vignetteCentreY
        },
        set: function(t) {
            this.imageProcessingConfiguration.vignetteCentreY = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "vignetteWeight", {
        get: function() {
            return this.imageProcessingConfiguration.vignetteWeight
        },
        set: function(t) {
            this.imageProcessingConfiguration.vignetteWeight = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "vignetteColor", {
        get: function() {
            return this.imageProcessingConfiguration.vignetteColor
        },
        set: function(t) {
            this.imageProcessingConfiguration.vignetteColor = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "vignetteCameraFov", {
        get: function() {
            return this.imageProcessingConfiguration.vignetteCameraFov
        },
        set: function(t) {
            this.imageProcessingConfiguration.vignetteCameraFov = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "vignetteBlendMode", {
        get: function() {
            return this.imageProcessingConfiguration.vignetteBlendMode
        },
        set: function(t) {
            this.imageProcessingConfiguration.vignetteBlendMode = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "vignetteEnabled", {
        get: function() {
            return this.imageProcessingConfiguration.vignetteEnabled
        },
        set: function(t) {
            this.imageProcessingConfiguration.vignetteEnabled = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "fromLinearSpace", {
        get: function() {
            return this._fromLinearSpace
        },
        set: function(t) {
            this._fromLinearSpace !== t && (this._fromLinearSpace = t,
            this._updateParameters())
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getClassName = function() {
        return "ImageProcessingPostProcess"
    }
    ,
    e.prototype._updateParameters = function() {
        this._defines.FROMLINEARSPACE = this._fromLinearSpace,
        this.imageProcessingConfiguration.prepareDefines(this._defines, !0);
        var t = "";
        for (var r in this._defines)
            this._defines[r] && (t += "#define " + r + `;\r
`);
        var n = ["textureSampler"]
          , o = ["scale"];
        ImageProcessingConfiguration && (ImageProcessingConfiguration.PrepareSamplers(n, this._defines),
        ImageProcessingConfiguration.PrepareUniforms(o, this._defines)),
        this.updateEffect(t, o, n)
    }
    ,
    e.prototype.dispose = function(t) {
        i.prototype.dispose.call(this, t),
        this._imageProcessingConfiguration && this._imageProcessingObserver && this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),
        this._imageProcessingConfiguration && (this.imageProcessingConfiguration.applyByPostProcess = !1)
    }
    ,
    __decorate([serialize()], e.prototype, "_fromLinearSpace", void 0),
    e
}(PostProcess)
  , name$O = "chromaticAberrationPixelShader"
  , shader$O = `
uniform sampler2D textureSampler;

uniform float chromatic_aberration;
uniform float radialIntensity;
uniform vec2 direction;
uniform vec2 centerPosition;
uniform float screen_width;
uniform float screen_height;

varying vec2 vUV;
void main(void)
{
vec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);
vec2 directionOfEffect=direction;
if(directionOfEffect.x == 0. && directionOfEffect.y == 0.){
directionOfEffect=normalize(centered_screen_pos);
}
float radius2=centered_screen_pos.x*centered_screen_pos.x
+centered_screen_pos.y*centered_screen_pos.y;
float radius=sqrt(radius2);
vec4 original=texture2D(textureSampler,vUV);

vec3 ref_indices=vec3(-0.3,0.0,0.3);
float ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;
float ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;

vec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);
vec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);
vec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);
original.r=texture2D(textureSampler,ref_coords_r).r;
original.g=texture2D(textureSampler,ref_coords_g).g;
original.b=texture2D(textureSampler,ref_coords_b).b;
original.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);
gl_FragColor=original;
}`;
ShaderStore.ShadersStore[name$O] = shader$O;
var ChromaticAberrationPostProcess = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a, s, l, u, c, h) {
        c === void 0 && (c = 0),
        h === void 0 && (h = !1);
        var f = i.call(this, t, "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], [], o, a, s, l, u, null, c, void 0, null, h) || this;
        return f.aberrationAmount = 30,
        f.radialIntensity = 0,
        f.direction = new Vector2(.707,.707),
        f.centerPosition = new Vector2(.5,.5),
        f.screenWidth = r,
        f.screenHeight = n,
        f.onApplyObservable.add(function(d) {
            d.setFloat("chromatic_aberration", f.aberrationAmount),
            d.setFloat("screen_width", r),
            d.setFloat("screen_height", n),
            d.setFloat("radialIntensity", f.radialIntensity),
            d.setFloat2("direction", f.direction.x, f.direction.y),
            d.setFloat2("centerPosition", f.centerPosition.x, f.centerPosition.y)
        }),
        f
    }
    return e.prototype.getClassName = function() {
        return "ChromaticAberrationPostProcess"
    }
    ,
    e._Parse = function(t, r, n, o) {
        return SerializationHelper.Parse(function() {
            return new e(t.name,t.screenWidth,t.screenHeight,t.options,r,t.renderTargetSamplingMode,n.getEngine(),t.reusable,t.textureType,!1)
        }, t, n, o)
    }
    ,
    __decorate([serialize()], e.prototype, "aberrationAmount", void 0),
    __decorate([serialize()], e.prototype, "radialIntensity", void 0),
    __decorate([serialize()], e.prototype, "direction", void 0),
    __decorate([serialize()], e.prototype, "centerPosition", void 0),
    __decorate([serialize()], e.prototype, "screenWidth", void 0),
    __decorate([serialize()], e.prototype, "screenHeight", void 0),
    e
}(PostProcess);
RegisterClass("BABYLON.ChromaticAberrationPostProcess", ChromaticAberrationPostProcess);
var name$N = "grainPixelShader"
  , shader$N = `#include<helperFunctions>

uniform sampler2D textureSampler;

uniform float intensity;
uniform float animatedSeed;

varying vec2 vUV;
void main(void)
{
gl_FragColor=texture2D(textureSampler,vUV);
vec2 seed=vUV*(animatedSeed);
float grain=dither(seed,intensity);

float lum=getLuminance(gl_FragColor.rgb);
float grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;
gl_FragColor.rgb+=grain*grainAmount;
gl_FragColor.rgb=max(gl_FragColor.rgb,0.0);
}`;
ShaderStore.ShadersStore[name$N] = shader$N;
var GrainPostProcess = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a, s, l, u) {
        l === void 0 && (l = 0),
        u === void 0 && (u = !1);
        var c = i.call(this, t, "grain", ["intensity", "animatedSeed"], [], r, n, o, a, s, null, l, void 0, null, u) || this;
        return c.intensity = 30,
        c.animated = !1,
        c.onApplyObservable.add(function(h) {
            h.setFloat("intensity", c.intensity),
            h.setFloat("animatedSeed", c.animated ? Math.random() + 1 : 1)
        }),
        c
    }
    return e.prototype.getClassName = function() {
        return "GrainPostProcess"
    }
    ,
    e._Parse = function(t, r, n, o) {
        return SerializationHelper.Parse(function() {
            return new e(t.name,t.options,r,t.renderTargetSamplingMode,n.getEngine(),t.reusable)
        }, t, n, o)
    }
    ,
    __decorate([serialize()], e.prototype, "intensity", void 0),
    __decorate([serialize()], e.prototype, "animated", void 0),
    e
}(PostProcess);
RegisterClass("BABYLON.GrainPostProcess", GrainPostProcess);
var name$M = "fxaaPixelShader"
  , shader$M = `uniform sampler2D textureSampler;
uniform vec2 texelSize;
varying vec2 vUV;
varying vec2 sampleCoordS;
varying vec2 sampleCoordE;
varying vec2 sampleCoordN;
varying vec2 sampleCoordW;
varying vec2 sampleCoordNW;
varying vec2 sampleCoordSE;
varying vec2 sampleCoordNE;
varying vec2 sampleCoordSW;
const float fxaaQualitySubpix=1.0;
const float fxaaQualityEdgeThreshold=0.166;
const float fxaaQualityEdgeThresholdMin=0.0833;
const vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);
#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)
void main(){
vec2 posM;
posM.x=vUV.x;
posM.y=vUV.y;
vec4 rgbyM=texture2D(textureSampler,vUV,0.0);
float lumaM=FxaaLuma(rgbyM);
float lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));
float lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));
float lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));
float lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));
float maxSM=max(lumaS,lumaM);
float minSM=min(lumaS,lumaM);
float maxESM=max(lumaE,maxSM);
float minESM=min(lumaE,minSM);
float maxWN=max(lumaN,lumaW);
float minWN=min(lumaN,lumaW);
float rangeMax=max(maxWN,maxESM);
float rangeMin=min(minWN,minESM);
float rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;
float range=rangeMax-rangeMin;
float rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);
#ifndef MALI
if(range<rangeMaxClamped)
{
gl_FragColor=rgbyM;
return;
}
#endif
float lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));
float lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));
float lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));
float lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));
float lumaNS=lumaN+lumaS;
float lumaWE=lumaW+lumaE;
float subpixRcpRange=1.0/range;
float subpixNSWE=lumaNS+lumaWE;
float edgeHorz1=(-2.0*lumaM)+lumaNS;
float edgeVert1=(-2.0*lumaM)+lumaWE;
float lumaNESE=lumaNE+lumaSE;
float lumaNWNE=lumaNW+lumaNE;
float edgeHorz2=(-2.0*lumaE)+lumaNESE;
float edgeVert2=(-2.0*lumaN)+lumaNWNE;
float lumaNWSW=lumaNW+lumaSW;
float lumaSWSE=lumaSW+lumaSE;
float edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);
float edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);
float edgeHorz3=(-2.0*lumaW)+lumaNWSW;
float edgeVert3=(-2.0*lumaS)+lumaSWSE;
float edgeHorz=abs(edgeHorz3)+edgeHorz4;
float edgeVert=abs(edgeVert3)+edgeVert4;
float subpixNWSWNESE=lumaNWSW+lumaNESE;
float lengthSign=texelSize.x;
bool horzSpan=edgeHorz>=edgeVert;
float subpixA=subpixNSWE*2.0+subpixNWSWNESE;
if (!horzSpan)
{
lumaN=lumaW;
}
if (!horzSpan)
{
lumaS=lumaE;
}
if (horzSpan)
{
lengthSign=texelSize.y;
}
float subpixB=(subpixA*(1.0/12.0))-lumaM;
float gradientN=lumaN-lumaM;
float gradientS=lumaS-lumaM;
float lumaNN=lumaN+lumaM;
float lumaSS=lumaS+lumaM;
bool pairN=abs(gradientN)>=abs(gradientS);
float gradient=max(abs(gradientN),abs(gradientS));
if (pairN)
{
lengthSign=-lengthSign;
}
float subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);
vec2 posB;
posB.x=posM.x;
posB.y=posM.y;
vec2 offNP;
offNP.x=(!horzSpan) ? 0.0 : texelSize.x;
offNP.y=(horzSpan) ? 0.0 : texelSize.y;
if (!horzSpan)
{
posB.x+=lengthSign*0.5;
}
if (horzSpan)
{
posB.y+=lengthSign*0.5;
}
vec2 posN;
posN.x=posB.x-offNP.x*1.5;
posN.y=posB.y-offNP.y*1.5;
vec2 posP;
posP.x=posB.x+offNP.x*1.5;
posP.y=posB.y+offNP.y*1.5;
float subpixD=((-2.0)*subpixC)+3.0;
float lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));
float subpixE=subpixC*subpixC;
float lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));
if (!pairN)
{
lumaNN=lumaSS;
}
float gradientScaled=gradient*1.0/4.0;
float lumaMM=lumaM-lumaNN*0.5;
float subpixF=subpixD*subpixE;
bool lumaMLTZero=lumaMM<0.0;
lumaEndN-=lumaNN*0.5;
lumaEndP-=lumaNN*0.5;
bool doneN=abs(lumaEndN)>=gradientScaled;
bool doneP=abs(lumaEndP)>=gradientScaled;
if (!doneN)
{
posN.x-=offNP.x*3.0;
}
if (!doneN)
{
posN.y-=offNP.y*3.0;
}
bool doneNP=(!doneN) || (!doneP);
if (!doneP)
{
posP.x+=offNP.x*3.0;
}
if (!doneP)
{
posP.y+=offNP.y*3.0;
}
if (doneNP)
{
if (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));
if (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));
if (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;
if (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;
doneN=abs(lumaEndN)>=gradientScaled;
doneP=abs(lumaEndP)>=gradientScaled;
if (!doneN) posN.x-=offNP.x*12.0;
if (!doneN) posN.y-=offNP.y*12.0;
doneNP=(!doneN) || (!doneP);
if (!doneP) posP.x+=offNP.x*12.0;
if (!doneP) posP.y+=offNP.y*12.0;
}
float dstN=posM.x-posN.x;
float dstP=posP.x-posM.x;
if (!horzSpan)
{
dstN=posM.y-posN.y;
}
if (!horzSpan)
{
dstP=posP.y-posM.y;
}
bool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;
float spanLength=(dstP+dstN);
bool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;
float spanLengthRcp=1.0/spanLength;
bool directionN=dstN<dstP;
float dst=min(dstN,dstP);
bool goodSpan=directionN ? goodSpanN : goodSpanP;
float subpixG=subpixF*subpixF;
float pixelOffset=(dst*(-spanLengthRcp))+0.5;
float subpixH=subpixG*fxaaQualitySubpix;
float pixelOffsetGood=goodSpan ? pixelOffset : 0.0;
float pixelOffsetSubpix=max(pixelOffsetGood,subpixH);
if (!horzSpan)
{
posM.x+=pixelOffsetSubpix*lengthSign;
}
if (horzSpan)
{
posM.y+=pixelOffsetSubpix*lengthSign;
}
#ifdef MALI
if(range<rangeMaxClamped)
{
gl_FragColor=rgbyM;
}
else
{
gl_FragColor=texture2D(textureSampler,posM,0.0);
}
#else
gl_FragColor=texture2D(textureSampler,posM,0.0);
#endif
}`;
ShaderStore.ShadersStore[name$M] = shader$M;
var name$L = "fxaaVertexShader"
  , shader$L = `
attribute vec2 position;
uniform vec2 texelSize;

varying vec2 vUV;
varying vec2 sampleCoordS;
varying vec2 sampleCoordE;
varying vec2 sampleCoordN;
varying vec2 sampleCoordW;
varying vec2 sampleCoordNW;
varying vec2 sampleCoordSE;
varying vec2 sampleCoordNE;
varying vec2 sampleCoordSW;
const vec2 madd=vec2(0.5,0.5);
void main(void) {
vUV=(position*madd+madd);
sampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;
sampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;
sampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;
sampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;
sampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;
sampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;
sampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;
sampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;
gl_Position=vec4(position,0.0,1.0);
}`;
ShaderStore.ShadersStore[name$L] = shader$L;
var FxaaPostProcess = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a, s, l) {
        n === void 0 && (n = null),
        l === void 0 && (l = 0);
        var u = i.call(this, t, "fxaa", ["texelSize"], null, r, n, o || Texture.BILINEAR_SAMPLINGMODE, a, s, null, l, "fxaa", void 0, !0) || this
          , c = u._getDefines();
        return u.updateEffect(c),
        u.onApplyObservable.add(function(h) {
            var f = u.texelSize;
            h.setFloat2("texelSize", f.x, f.y)
        }),
        u
    }
    return e.prototype.getClassName = function() {
        return "FxaaPostProcess"
    }
    ,
    e.prototype._getDefines = function() {
        var t = this.getEngine();
        if (!t)
            return null;
        var r = t.getGlInfo();
        return r && r.renderer && r.renderer.toLowerCase().indexOf("mali") > -1 ? `#define MALI 1
` : null
    }
    ,
    e._Parse = function(t, r, n, o) {
        return SerializationHelper.Parse(function() {
            return new e(t.name,t.options,r,t.renderTargetSamplingMode,n.getEngine(),t.reusable)
        }, t, n, o)
    }
    ,
    e
}(PostProcess);
RegisterClass("BABYLON.FxaaPostProcess", FxaaPostProcess);
var PostProcessRenderPipeline = function() {
    function i(e, t) {
        this.engine = e,
        this._name = t,
        this._renderEffects = {},
        this._renderEffectsForIsolatedPass = new Array,
        this._cameras = []
    }
    return Object.defineProperty(i.prototype, "name", {
        get: function() {
            return this._name
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "cameras", {
        get: function() {
            return this._cameras
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.getClassName = function() {
        return "PostProcessRenderPipeline"
    }
    ,
    Object.defineProperty(i.prototype, "isSupported", {
        get: function() {
            for (var e in this._renderEffects)
                if (this._renderEffects.hasOwnProperty(e) && !this._renderEffects[e].isSupported)
                    return !1;
            return !0
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.addEffect = function(e) {
        this._renderEffects[e._name] = e
    }
    ,
    i.prototype._rebuild = function() {}
    ,
    i.prototype._enableEffect = function(e, t) {
        var r = this._renderEffects[e];
        !r || r._enable(Tools.MakeArray(t || this._cameras))
    }
    ,
    i.prototype._disableEffect = function(e, t) {
        var r = this._renderEffects[e];
        !r || r._disable(Tools.MakeArray(t || this._cameras))
    }
    ,
    i.prototype._attachCameras = function(e, t) {
        var r = Tools.MakeArray(e || this._cameras);
        if (!!r) {
            var n = [], o;
            for (o = 0; o < r.length; o++) {
                var a = r[o];
                if (!!a) {
                    var s = a.name;
                    this._cameras.indexOf(a) === -1 ? this._cameras[s] = a : t && n.push(o)
                }
            }
            for (o = 0; o < n.length; o++)
                r.splice(n[o], 1);
            for (var l in this._renderEffects)
                this._renderEffects.hasOwnProperty(l) && this._renderEffects[l]._attachCameras(r)
        }
    }
    ,
    i.prototype._detachCameras = function(e) {
        var t = Tools.MakeArray(e || this._cameras);
        if (!!t) {
            for (var r in this._renderEffects)
                this._renderEffects.hasOwnProperty(r) && this._renderEffects[r]._detachCameras(t);
            for (var n = 0; n < t.length; n++)
                this._cameras.splice(this._cameras.indexOf(t[n]), 1)
        }
    }
    ,
    i.prototype._update = function() {
        for (var e in this._renderEffects)
            this._renderEffects.hasOwnProperty(e) && this._renderEffects[e]._update();
        for (var t = 0; t < this._cameras.length; t++)
            if (!!this._cameras[t]) {
                var r = this._cameras[t].name;
                this._renderEffectsForIsolatedPass[r] && this._renderEffectsForIsolatedPass[r]._update()
            }
    }
    ,
    i.prototype._reset = function() {
        this._renderEffects = {},
        this._renderEffectsForIsolatedPass = new Array
    }
    ,
    i.prototype._enableMSAAOnFirstPostProcess = function(e) {
        if (!this.engine._features.supportMSAA)
            return !1;
        var t = Object.keys(this._renderEffects);
        if (t.length > 0) {
            var r = this._renderEffects[t[0]].getPostProcesses();
            r && (r[0].samples = e)
        }
        return !0
    }
    ,
    i.prototype.setPrePassRenderer = function(e) {
        return !1
    }
    ,
    i.prototype.dispose = function() {}
    ,
    __decorate([serialize()], i.prototype, "_name", void 0),
    i
}()
  , PostProcessRenderEffect = function() {
    function i(e, t, r, n) {
        this._name = t,
        this._singleInstance = n || !0,
        this._getPostProcesses = r,
        this._cameras = {},
        this._indicesForCamera = {},
        this._postProcesses = {}
    }
    return Object.defineProperty(i.prototype, "isSupported", {
        get: function() {
            for (var e in this._postProcesses)
                if (this._postProcesses.hasOwnProperty(e)) {
                    for (var t = this._postProcesses[e], r = 0; r < t.length; r++)
                        if (!t[r].isSupported)
                            return !1
                }
            return !0
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype._update = function() {}
    ,
    i.prototype._attachCameras = function(e) {
        var t = this, r, n = Tools.MakeArray(e || this._cameras);
        if (!!n)
            for (var o = 0; o < n.length; o++) {
                var a = n[o];
                if (!!a) {
                    var s = a.name;
                    if (this._singleInstance ? r = 0 : r = s,
                    !this._postProcesses[r]) {
                        var l = this._getPostProcesses();
                        l && (this._postProcesses[r] = Array.isArray(l) ? l : [l])
                    }
                    this._indicesForCamera[s] || (this._indicesForCamera[s] = []),
                    this._postProcesses[r].forEach(function(u) {
                        var c = a.attachPostProcess(u);
                        t._indicesForCamera[s].push(c)
                    }),
                    this._cameras[s] || (this._cameras[s] = a)
                }
            }
    }
    ,
    i.prototype._detachCameras = function(e) {
        var t = Tools.MakeArray(e || this._cameras);
        if (!!t)
            for (var r = 0; r < t.length; r++) {
                var n = t[r]
                  , o = n.name
                  , a = this._postProcesses[this._singleInstance ? 0 : o];
                a && a.forEach(function(s) {
                    n.detachPostProcess(s)
                }),
                this._cameras[o] && (this._cameras[o] = null)
            }
    }
    ,
    i.prototype._enable = function(e) {
        var t = this
          , r = Tools.MakeArray(e || this._cameras);
        if (!!r)
            for (var n = 0; n < r.length; n++)
                for (var o = r[n], a = o.name, s = 0; s < this._indicesForCamera[a].length; s++)
                    (o._postProcesses[this._indicesForCamera[a][s]] === void 0 || o._postProcesses[this._indicesForCamera[a][s]] === null) && this._postProcesses[this._singleInstance ? 0 : a].forEach(function(l) {
                        r[n].attachPostProcess(l, t._indicesForCamera[a][s])
                    })
    }
    ,
    i.prototype._disable = function(e) {
        var t = Tools.MakeArray(e || this._cameras);
        if (!!t)
            for (var r = 0; r < t.length; r++) {
                var n = t[r]
                  , o = n.name;
                this._postProcesses[this._singleInstance ? 0 : o].forEach(function(a) {
                    n.detachPostProcess(a)
                })
            }
    }
    ,
    i.prototype.getPostProcesses = function(e) {
        return this._singleInstance ? this._postProcesses[0] : e ? this._postProcesses[e.name] : null
    }
    ,
    i
}()
  , name$K = "circleOfConfusionPixelShader"
  , shader$K = `
uniform sampler2D depthSampler;

varying vec2 vUV;

uniform vec2 cameraMinMaxZ;

uniform float focusDistance;
uniform float cocPrecalculation;
void main(void)
{
float depth=texture2D(depthSampler,vUV).r;
float pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0;
float coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));
coc=clamp(coc,0.0,1.0);
gl_FragColor=vec4(coc,depth,coc,1.0);
}
`;
ShaderStore.ShadersStore[name$K] = shader$K;
var CircleOfConfusionPostProcess = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a, s, l, u, c) {
        u === void 0 && (u = 0),
        c === void 0 && (c = !1);
        var h = i.call(this, t, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], n, o, a, s, l, null, u, void 0, null, c) || this;
        return h.lensSize = 50,
        h.fStop = 1.4,
        h.focusDistance = 2e3,
        h.focalLength = 50,
        h._depthTexture = null,
        h._depthTexture = r,
        h.onApplyObservable.add(function(f) {
            if (!h._depthTexture) {
                Logger$2.Warn("No depth texture set on CircleOfConfusionPostProcess");
                return
            }
            f.setTexture("depthSampler", h._depthTexture);
            var d = h.lensSize / h.fStop
              , _ = d * h.focalLength / (h.focusDistance - h.focalLength);
            f.setFloat("focusDistance", h.focusDistance),
            f.setFloat("cocPrecalculation", _),
            f.setFloat2("cameraMinMaxZ", h._depthTexture.activeCamera.minZ, h._depthTexture.activeCamera.maxZ)
        }),
        h
    }
    return e.prototype.getClassName = function() {
        return "CircleOfConfusionPostProcess"
    }
    ,
    Object.defineProperty(e.prototype, "depthTexture", {
        set: function(t) {
            this._depthTexture = t
        },
        enumerable: !1,
        configurable: !0
    }),
    __decorate([serialize()], e.prototype, "lensSize", void 0),
    __decorate([serialize()], e.prototype, "fStop", void 0),
    __decorate([serialize()], e.prototype, "focusDistance", void 0),
    __decorate([serialize()], e.prototype, "focalLength", void 0),
    e
}(PostProcess);
RegisterClass("BABYLON.CircleOfConfusionPostProcess", CircleOfConfusionPostProcess);
var DepthOfFieldBlurPostProcess = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a, s, l, u, c, h, f, d, _) {
        u === void 0 && (u = null),
        _ === void 0 && (_ = !1);
        var g = i.call(this, t, n, o, a, s, 2, h, f, 0, `#define DOF 1\r
`, _) || this;
        return g.direction = n,
        g.externalTextureSamplerBinding = !!u,
        g.onApplyObservable.add(function(m) {
            u != null && m.setTextureFromPostProcess("textureSampler", u),
            m.setTextureFromPostProcessOutput("circleOfConfusionSampler", l),
            r.activeCamera && m.setFloat2("cameraMinMaxZ", r.activeCamera.minZ, r.activeCamera.maxZ)
        }),
        g
    }
    return e.prototype.getClassName = function() {
        return "DepthOfFieldBlurPostProcess"
    }
    ,
    __decorate([serialize()], e.prototype, "direction", void 0),
    e
}(BlurPostProcess);
RegisterClass("BABYLON.DepthOfFieldBlurPostProcess", DepthOfFieldBlurPostProcess);
var name$J = "depthOfFieldMergePixelShader"
  , shader$J = `uniform sampler2D textureSampler;
varying vec2 vUV;
uniform sampler2D circleOfConfusionSampler;
uniform sampler2D blurStep0;
#if BLUR_LEVEL>0
uniform sampler2D blurStep1;
#endif
#if BLUR_LEVEL>1
uniform sampler2D blurStep2;
#endif
void main(void)
{
float coc=texture2D(circleOfConfusionSampler,vUV).r;
#if BLUR_LEVEL == 0
vec4 original=texture2D(textureSampler,vUV);
vec4 blurred0=texture2D(blurStep0,vUV);
gl_FragColor=mix(original,blurred0,coc);
#endif
#if BLUR_LEVEL == 1
if(coc<0.5){
vec4 original=texture2D(textureSampler,vUV);
vec4 blurred1=texture2D(blurStep1,vUV);
gl_FragColor=mix(original,blurred1,coc/0.5);
}else{
vec4 blurred0=texture2D(blurStep0,vUV);
vec4 blurred1=texture2D(blurStep1,vUV);
gl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);
}
#endif
#if BLUR_LEVEL == 2
if(coc<0.33){
vec4 original=texture2D(textureSampler,vUV);
vec4 blurred2=texture2D(blurStep2,vUV);
gl_FragColor=mix(original,blurred2,coc/0.33);
}else if(coc<0.66){
vec4 blurred1=texture2D(blurStep1,vUV);
vec4 blurred2=texture2D(blurStep2,vUV);
gl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);
}else{
vec4 blurred0=texture2D(blurStep0,vUV);
vec4 blurred1=texture2D(blurStep1,vUV);
gl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);
}
#endif
}
`;
ShaderStore.ShadersStore[name$J] = shader$J;
var DepthOfFieldMergePostProcess = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a, s, l, u, c, h, f) {
        h === void 0 && (h = 0),
        f === void 0 && (f = !1);
        var d = i.call(this, t, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], a, s, l, u, c, null, h, void 0, null, !0) || this;
        return d.blurSteps = o,
        d.externalTextureSamplerBinding = !0,
        d.onApplyObservable.add(function(_) {
            _.setTextureFromPostProcess("textureSampler", r),
            _.setTextureFromPostProcessOutput("circleOfConfusionSampler", n),
            o.forEach(function(g, m) {
                _.setTextureFromPostProcessOutput("blurStep" + (o.length - m - 1), g)
            })
        }),
        f || d.updateEffect(),
        d
    }
    return e.prototype.getClassName = function() {
        return "DepthOfFieldMergePostProcess"
    }
    ,
    e.prototype.updateEffect = function(t, r, n, o, a, s) {
        t === void 0 && (t = null),
        r === void 0 && (r = null),
        n === void 0 && (n = null),
        t || (t = "",
        t += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + `
`),
        i.prototype.updateEffect.call(this, t, r, n, o, a, s)
    }
    ,
    e
}(PostProcess), DepthOfFieldEffectBlurLevel;
(function(i) {
    i[i.Low = 0] = "Low",
    i[i.Medium = 1] = "Medium",
    i[i.High = 2] = "High"
}
)(DepthOfFieldEffectBlurLevel || (DepthOfFieldEffectBlurLevel = {}));
var DepthOfFieldEffect = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a) {
        n === void 0 && (n = DepthOfFieldEffectBlurLevel.Low),
        o === void 0 && (o = 0),
        a === void 0 && (a = !1);
        var s = i.call(this, t.getEngine(), "depth of field", function() {
            return s._effects
        }, !0) || this;
        s._effects = [],
        s._circleOfConfusion = new CircleOfConfusionPostProcess("circleOfConfusion",r,1,null,Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,o,a),
        s._depthOfFieldBlurY = [],
        s._depthOfFieldBlurX = [];
        var l = 1
          , u = 15;
        switch (n) {
        case DepthOfFieldEffectBlurLevel.High:
            {
                l = 3,
                u = 51;
                break
            }
        case DepthOfFieldEffectBlurLevel.Medium:
            {
                l = 2,
                u = 31;
                break
            }
        default:
            {
                u = 15,
                l = 1;
                break
            }
        }
        for (var c = u / Math.pow(2, l - 1), h = 1, f = 0; f < l; f++) {
            var d = new DepthOfFieldBlurPostProcess("vertical blur",t,new Vector2(0,1),c,h,null,s._circleOfConfusion,f == 0 ? s._circleOfConfusion : null,Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,o,a);
            d.autoClear = !1,
            h = .75 / Math.pow(2, f);
            var _ = new DepthOfFieldBlurPostProcess("horizontal blur",t,new Vector2(1,0),c,h,null,s._circleOfConfusion,null,Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,o,a);
            _.autoClear = !1,
            s._depthOfFieldBlurY.push(d),
            s._depthOfFieldBlurX.push(_)
        }
        s._effects = [s._circleOfConfusion];
        for (var f = 0; f < s._depthOfFieldBlurX.length; f++)
            s._effects.push(s._depthOfFieldBlurY[f]),
            s._effects.push(s._depthOfFieldBlurX[f]);
        return s._dofMerge = new DepthOfFieldMergePostProcess("dofMerge",s._circleOfConfusion,s._circleOfConfusion,s._depthOfFieldBlurX,h,null,Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,o,a),
        s._dofMerge.autoClear = !1,
        s._effects.push(s._dofMerge),
        s
    }
    return Object.defineProperty(e.prototype, "focalLength", {
        get: function() {
            return this._circleOfConfusion.focalLength
        },
        set: function(t) {
            this._circleOfConfusion.focalLength = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "fStop", {
        get: function() {
            return this._circleOfConfusion.fStop
        },
        set: function(t) {
            this._circleOfConfusion.fStop = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "focusDistance", {
        get: function() {
            return this._circleOfConfusion.focusDistance
        },
        set: function(t) {
            this._circleOfConfusion.focusDistance = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "lensSize", {
        get: function() {
            return this._circleOfConfusion.lensSize
        },
        set: function(t) {
            this._circleOfConfusion.lensSize = t
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getClassName = function() {
        return "DepthOfFieldEffect"
    }
    ,
    Object.defineProperty(e.prototype, "depthTexture", {
        set: function(t) {
            this._circleOfConfusion.depthTexture = t
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.disposeEffects = function(t) {
        for (var r = 0; r < this._effects.length; r++)
            this._effects[r].dispose(t)
    }
    ,
    e.prototype._updateEffects = function() {
        for (var t = 0; t < this._effects.length; t++)
            this._effects[t].updateEffect()
    }
    ,
    e.prototype._isReady = function() {
        for (var t = 0; t < this._effects.length; t++)
            if (!this._effects[t].isReady())
                return !1;
        return !0
    }
    ,
    e
}(PostProcessRenderEffect)
  , name$I = "extractHighlightsPixelShader"
  , shader$I = `#include<helperFunctions>

varying vec2 vUV;
uniform sampler2D textureSampler;
uniform float threshold;
uniform float exposure;
void main(void)
{
gl_FragColor=texture2D(textureSampler,vUV);
float luma=getLuminance(gl_FragColor.rgb*exposure);
gl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;
}`;
ShaderStore.ShadersStore[name$I] = shader$I;
var ExtractHighlightsPostProcess = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a, s, l, u) {
        l === void 0 && (l = 0),
        u === void 0 && (u = !1);
        var c = i.call(this, t, "extractHighlights", ["threshold", "exposure"], null, r, n, o, a, s, null, l, void 0, null, u) || this;
        return c.threshold = .9,
        c._exposure = 1,
        c._inputPostProcess = null,
        c.onApplyObservable.add(function(h) {
            c.externalTextureSamplerBinding = !!c._inputPostProcess,
            c._inputPostProcess && h.setTextureFromPostProcess("textureSampler", c._inputPostProcess),
            h.setFloat("threshold", Math.pow(c.threshold, ToGammaSpace)),
            h.setFloat("exposure", c._exposure)
        }),
        c
    }
    return e.prototype.getClassName = function() {
        return "ExtractHighlightsPostProcess"
    }
    ,
    __decorate([serialize()], e.prototype, "threshold", void 0),
    e
}(PostProcess);
RegisterClass("BABYLON.ExtractHighlightsPostProcess", ExtractHighlightsPostProcess);
var name$H = "bloomMergePixelShader"
  , shader$H = `uniform sampler2D textureSampler;
uniform sampler2D bloomBlur;
varying vec2 vUV;
uniform float bloomWeight;
void main(void)
{
gl_FragColor=texture2D(textureSampler,vUV);
vec3 blurred=texture2D(bloomBlur,vUV).rgb;
gl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight);
}
`;
ShaderStore.ShadersStore[name$H] = shader$H;
var BloomMergePostProcess = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a, s, l, u, c, h, f) {
        h === void 0 && (h = 0),
        f === void 0 && (f = !1);
        var d = i.call(this, t, "bloomMerge", ["bloomWeight"], ["bloomBlur"], a, s, l, u, c, null, h, void 0, null, !0) || this;
        return d.weight = 1,
        d.weight = o,
        d.externalTextureSamplerBinding = !0,
        d.onApplyObservable.add(function(_) {
            _.setTextureFromPostProcess("textureSampler", r),
            _.setTextureFromPostProcessOutput("bloomBlur", n),
            _.setFloat("bloomWeight", d.weight)
        }),
        f || d.updateEffect(),
        d
    }
    return e.prototype.getClassName = function() {
        return "BloomMergePostProcess"
    }
    ,
    __decorate([serialize()], e.prototype, "weight", void 0),
    e
}(PostProcess);
RegisterClass("BABYLON.BloomMergePostProcess", BloomMergePostProcess);
var BloomEffect = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a, s) {
        a === void 0 && (a = 0),
        s === void 0 && (s = !1);
        var l = i.call(this, t.getEngine(), "bloom", function() {
            return l._effects
        }, !0) || this;
        return l.bloomScale = r,
        l._effects = [],
        l._downscale = new ExtractHighlightsPostProcess("highlights",1,null,Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,a,s),
        l._blurX = new BlurPostProcess("horizontal blur",new Vector2(1,0),10,r,null,Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,a,void 0,s),
        l._blurX.alwaysForcePOT = !0,
        l._blurX.autoClear = !1,
        l._blurY = new BlurPostProcess("vertical blur",new Vector2(0,1),10,r,null,Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,a,void 0,s),
        l._blurY.alwaysForcePOT = !0,
        l._blurY.autoClear = !1,
        l.kernel = o,
        l._effects = [l._downscale, l._blurX, l._blurY],
        l._merge = new BloomMergePostProcess("bloomMerge",l._downscale,l._blurY,n,r,null,Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,a,s),
        l._merge.autoClear = !1,
        l._effects.push(l._merge),
        l
    }
    return Object.defineProperty(e.prototype, "threshold", {
        get: function() {
            return this._downscale.threshold
        },
        set: function(t) {
            this._downscale.threshold = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "weight", {
        get: function() {
            return this._merge.weight
        },
        set: function(t) {
            this._merge.weight = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "kernel", {
        get: function() {
            return this._blurX.kernel / this.bloomScale
        },
        set: function(t) {
            this._blurX.kernel = t * this.bloomScale,
            this._blurY.kernel = t * this.bloomScale
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.disposeEffects = function(t) {
        for (var r = 0; r < this._effects.length; r++)
            this._effects[r].dispose(t)
    }
    ,
    e.prototype._updateEffects = function() {
        for (var t = 0; t < this._effects.length; t++)
            this._effects[t].updateEffect()
    }
    ,
    e.prototype._isReady = function() {
        for (var t = 0; t < this._effects.length; t++)
            if (!this._effects[t].isReady())
                return !1;
        return !0
    }
    ,
    e
}(PostProcessRenderEffect)
  , PostProcessRenderPipelineManager = function() {
    function i() {
        this._renderPipelines = {}
    }
    return Object.defineProperty(i.prototype, "supportedPipelines", {
        get: function() {
            var e = [];
            for (var t in this._renderPipelines)
                if (this._renderPipelines.hasOwnProperty(t)) {
                    var r = this._renderPipelines[t];
                    r.isSupported && e.push(r)
                }
            return e
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.addPipeline = function(e) {
        this._renderPipelines[e._name] = e
    }
    ,
    i.prototype.attachCamerasToRenderPipeline = function(e, t, r) {
        r === void 0 && (r = !1);
        var n = this._renderPipelines[e];
        !n || n._attachCameras(t, r)
    }
    ,
    i.prototype.detachCamerasFromRenderPipeline = function(e, t) {
        var r = this._renderPipelines[e];
        !r || r._detachCameras(t)
    }
    ,
    i.prototype.enableEffectInPipeline = function(e, t, r) {
        var n = this._renderPipelines[e];
        !n || n._enableEffect(t, r)
    }
    ,
    i.prototype.disableEffectInPipeline = function(e, t, r) {
        var n = this._renderPipelines[e];
        !n || n._disableEffect(t, r)
    }
    ,
    i.prototype.update = function() {
        for (var e in this._renderPipelines)
            if (this._renderPipelines.hasOwnProperty(e)) {
                var t = this._renderPipelines[e];
                t.isSupported ? t._update() : (t.dispose(),
                delete this._renderPipelines[e])
            }
    }
    ,
    i.prototype._rebuild = function() {
        for (var e in this._renderPipelines)
            if (this._renderPipelines.hasOwnProperty(e)) {
                var t = this._renderPipelines[e];
                t._rebuild()
            }
    }
    ,
    i.prototype.dispose = function() {
        for (var e in this._renderPipelines)
            if (this._renderPipelines.hasOwnProperty(e)) {
                var t = this._renderPipelines[e];
                t.dispose()
            }
    }
    ,
    i
}();
Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
    get: function() {
        if (!this._postProcessRenderPipelineManager) {
            var i = this._getComponent(SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
            i || (i = new PostProcessRenderPipelineManagerSceneComponent(this),
            this._addComponent(i)),
            this._postProcessRenderPipelineManager = new PostProcessRenderPipelineManager
        }
        return this._postProcessRenderPipelineManager
    },
    enumerable: !0,
    configurable: !0
});
var PostProcessRenderPipelineManagerSceneComponent = function() {
    function i(e) {
        this.name = SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER,
        this.scene = e
    }
    return i.prototype.register = function() {
        this.scene._gatherRenderTargetsStage.registerStep(SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets)
    }
    ,
    i.prototype.rebuild = function() {
        this.scene._postProcessRenderPipelineManager && this.scene._postProcessRenderPipelineManager._rebuild()
    }
    ,
    i.prototype.dispose = function() {
        this.scene._postProcessRenderPipelineManager && this.scene._postProcessRenderPipelineManager.dispose()
    }
    ,
    i.prototype._gatherRenderTargets = function() {
        this.scene._postProcessRenderPipelineManager && this.scene._postProcessRenderPipelineManager.update()
    }
    ,
    i
}()
  , DefaultRenderingPipeline = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a) {
        t === void 0 && (t = ""),
        r === void 0 && (r = !0),
        n === void 0 && (n = EngineStore.LastCreatedScene),
        a === void 0 && (a = !0);
        var s = i.call(this, n.getEngine(), t) || this;
        s._camerasToBeAttached = [],
        s.SharpenPostProcessId = "SharpenPostProcessEffect",
        s.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect",
        s.FxaaPostProcessId = "FxaaPostProcessEffect",
        s.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect",
        s.GrainPostProcessId = "GrainPostProcessEffect",
        s._glowLayer = null,
        s.animations = [],
        s._imageProcessingConfigurationObserver = null,
        s._sharpenEnabled = !1,
        s._bloomEnabled = !1,
        s._depthOfFieldEnabled = !1,
        s._depthOfFieldBlurLevel = DepthOfFieldEffectBlurLevel.Low,
        s._fxaaEnabled = !1,
        s._imageProcessingEnabled = !0,
        s._bloomScale = .5,
        s._chromaticAberrationEnabled = !1,
        s._grainEnabled = !1,
        s._buildAllowed = !0,
        s.onBuildObservable = new Observable,
        s._resizeObserver = null,
        s._hardwareScaleLevel = 1,
        s._bloomKernel = 64,
        s._bloomWeight = .15,
        s._bloomThreshold = .9,
        s._samples = 1,
        s._hasCleared = !1,
        s._prevPostProcess = null,
        s._prevPrevPostProcess = null,
        s._depthOfFieldSceneObserver = null,
        s._cameras = o || n.cameras,
        s._cameras = s._cameras.slice(),
        s._camerasToBeAttached = s._cameras.slice(),
        s._buildAllowed = a,
        s._scene = n;
        var l = s._scene.getEngine().getCaps();
        s._hdr = r && (l.textureHalfFloatRender || l.textureFloatRender),
        s._hdr ? l.textureHalfFloatRender ? s._defaultPipelineTextureType = 2 : l.textureFloatRender && (s._defaultPipelineTextureType = 1) : s._defaultPipelineTextureType = 0,
        n.postProcessRenderPipelineManager.addPipeline(s);
        var u = s._scene.getEngine();
        return s.sharpen = new SharpenPostProcess("sharpen",1,null,Texture.BILINEAR_SAMPLINGMODE,u,!1,s._defaultPipelineTextureType,!0),
        s._sharpenEffect = new PostProcessRenderEffect(u,s.SharpenPostProcessId,function() {
            return s.sharpen
        }
        ,!0),
        s.depthOfField = new DepthOfFieldEffect(s._scene,null,s._depthOfFieldBlurLevel,s._defaultPipelineTextureType,!0),
        s.bloom = new BloomEffect(s._scene,s._bloomScale,s._bloomWeight,s.bloomKernel,s._defaultPipelineTextureType,!0),
        s.chromaticAberration = new ChromaticAberrationPostProcess("ChromaticAberration",u.getRenderWidth(),u.getRenderHeight(),1,null,Texture.BILINEAR_SAMPLINGMODE,u,!1,s._defaultPipelineTextureType,!0),
        s._chromaticAberrationEffect = new PostProcessRenderEffect(u,s.ChromaticAberrationPostProcessId,function() {
            return s.chromaticAberration
        }
        ,!0),
        s.grain = new GrainPostProcess("Grain",1,null,Texture.BILINEAR_SAMPLINGMODE,u,!1,s._defaultPipelineTextureType,!0),
        s._grainEffect = new PostProcessRenderEffect(u,s.GrainPostProcessId,function() {
            return s.grain
        }
        ,!0),
        s._resizeObserver = u.onResizeObservable.add(function() {
            s._hardwareScaleLevel = u.getHardwareScalingLevel(),
            s.bloomKernel = s.bloomKernel
        }),
        s._imageProcessingConfigurationObserver = s._scene.imageProcessingConfiguration.onUpdateParameters.add(function() {
            s.bloom._downscale._exposure = s._scene.imageProcessingConfiguration.exposure,
            s.imageProcessingEnabled !== s._scene.imageProcessingConfiguration.isEnabled && (s._imageProcessingEnabled = s._scene.imageProcessingConfiguration.isEnabled,
            s._buildPipeline())
        }),
        s._buildPipeline(),
        s
    }
    return Object.defineProperty(e.prototype, "scene", {
        get: function() {
            return this._scene
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "sharpenEnabled", {
        get: function() {
            return this._sharpenEnabled
        },
        set: function(t) {
            this._sharpenEnabled !== t && (this._sharpenEnabled = t,
            this._buildPipeline())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "bloomKernel", {
        get: function() {
            return this._bloomKernel
        },
        set: function(t) {
            this._bloomKernel = t,
            this.bloom.kernel = t / this._hardwareScaleLevel
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "bloomWeight", {
        get: function() {
            return this._bloomWeight
        },
        set: function(t) {
            this._bloomWeight !== t && (this.bloom.weight = t,
            this._bloomWeight = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "bloomThreshold", {
        get: function() {
            return this._bloomThreshold
        },
        set: function(t) {
            this._bloomThreshold !== t && (this.bloom.threshold = t,
            this._bloomThreshold = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "bloomScale", {
        get: function() {
            return this._bloomScale
        },
        set: function(t) {
            this._bloomScale !== t && (this._bloomScale = t,
            this._rebuildBloom(),
            this._buildPipeline())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "bloomEnabled", {
        get: function() {
            return this._bloomEnabled
        },
        set: function(t) {
            this._bloomEnabled !== t && (this._bloomEnabled = t,
            this._buildPipeline())
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._rebuildBloom = function() {
        var t = this.bloom;
        this.bloom = new BloomEffect(this._scene,this.bloomScale,this._bloomWeight,this.bloomKernel,this._defaultPipelineTextureType,!1),
        this.bloom.threshold = t.threshold;
        for (var r = 0; r < this._cameras.length; r++)
            t.disposeEffects(this._cameras[r])
    }
    ,
    Object.defineProperty(e.prototype, "depthOfFieldEnabled", {
        get: function() {
            return this._depthOfFieldEnabled
        },
        set: function(t) {
            this._depthOfFieldEnabled !== t && (this._depthOfFieldEnabled = t,
            this._buildPipeline())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "depthOfFieldBlurLevel", {
        get: function() {
            return this._depthOfFieldBlurLevel
        },
        set: function(t) {
            if (this._depthOfFieldBlurLevel !== t) {
                this._depthOfFieldBlurLevel = t;
                var r = this.depthOfField;
                this.depthOfField = new DepthOfFieldEffect(this._scene,null,this._depthOfFieldBlurLevel,this._defaultPipelineTextureType,!1),
                this.depthOfField.focalLength = r.focalLength,
                this.depthOfField.focusDistance = r.focusDistance,
                this.depthOfField.fStop = r.fStop,
                this.depthOfField.lensSize = r.lensSize;
                for (var n = 0; n < this._cameras.length; n++)
                    r.disposeEffects(this._cameras[n]);
                this._buildPipeline()
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "fxaaEnabled", {
        get: function() {
            return this._fxaaEnabled
        },
        set: function(t) {
            this._fxaaEnabled !== t && (this._fxaaEnabled = t,
            this._buildPipeline())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "samples", {
        get: function() {
            return this._samples
        },
        set: function(t) {
            this._samples !== t && (this._samples = t,
            this._buildPipeline())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "imageProcessingEnabled", {
        get: function() {
            return this._imageProcessingEnabled
        },
        set: function(t) {
            this._imageProcessingEnabled !== t && (this._scene.imageProcessingConfiguration.isEnabled = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "glowLayerEnabled", {
        get: function() {
            return this._glowLayer != null
        },
        set: function(t) {
            t && !this._glowLayer ? this._glowLayer = new GlowLayer("",this._scene) : !t && this._glowLayer && (this._glowLayer.dispose(),
            this._glowLayer = null)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "glowLayer", {
        get: function() {
            return this._glowLayer
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "chromaticAberrationEnabled", {
        get: function() {
            return this._chromaticAberrationEnabled
        },
        set: function(t) {
            this._chromaticAberrationEnabled !== t && (this._chromaticAberrationEnabled = t,
            this._buildPipeline())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "grainEnabled", {
        get: function() {
            return this._grainEnabled
        },
        set: function(t) {
            this._grainEnabled !== t && (this._grainEnabled = t,
            this._buildPipeline())
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getClassName = function() {
        return "DefaultRenderingPipeline"
    }
    ,
    e.prototype.prepare = function() {
        var t = this._buildAllowed;
        this._buildAllowed = !0,
        this._buildPipeline(),
        this._buildAllowed = t
    }
    ,
    e.prototype._setAutoClearAndTextureSharing = function(t, r) {
        r === void 0 && (r = !1),
        this._hasCleared ? t.autoClear = !1 : (t.autoClear = !0,
        this._scene.autoClear = !1,
        this._hasCleared = !0),
        r || (this._prevPrevPostProcess ? t.shareOutputWith(this._prevPrevPostProcess) : t.useOwnOutput(),
        this._prevPostProcess && (this._prevPrevPostProcess = this._prevPostProcess),
        this._prevPostProcess = t)
    }
    ,
    e.prototype._buildPipeline = function() {
        var t = this;
        if (!!this._buildAllowed) {
            this._scene.autoClear = !0;
            var r = this._scene.getEngine();
            if (this._disposePostProcesses(),
            this._cameras !== null && (this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras),
            this._cameras = this._camerasToBeAttached.slice()),
            this._reset(),
            this._prevPostProcess = null,
            this._prevPrevPostProcess = null,
            this._hasCleared = !1,
            this.depthOfFieldEnabled) {
                if (this._cameras.length > 1) {
                    for (var n = 0, o = this._cameras; n < o.length; n++) {
                        var a = o[n]
                          , s = this._scene.enableDepthRenderer(a);
                        s.useOnlyInActiveCamera = !0
                    }
                    this._depthOfFieldSceneObserver = this._scene.onAfterRenderTargetsRenderObservable.add(function(l) {
                        t._cameras.indexOf(l.activeCamera) > -1 && (t.depthOfField.depthTexture = l.enableDepthRenderer(l.activeCamera).getDepthMap())
                    })
                } else {
                    this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
                    var s = this._scene.enableDepthRenderer(this._cameras[0]);
                    this.depthOfField.depthTexture = s.getDepthMap()
                }
                this.depthOfField._isReady() || this.depthOfField._updateEffects(),
                this.addEffect(this.depthOfField),
                this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], !0)
            } else
                this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
            this.bloomEnabled && (this.bloom._isReady() || this.bloom._updateEffects(),
            this.addEffect(this.bloom),
            this._setAutoClearAndTextureSharing(this.bloom._effects[0], !0)),
            this._imageProcessingEnabled && (this.imageProcessing = new ImageProcessingPostProcess("imageProcessing",1,null,Texture.BILINEAR_SAMPLINGMODE,r,!1,this._defaultPipelineTextureType),
            this._hdr ? (this.addEffect(new PostProcessRenderEffect(r,this.ImageProcessingPostProcessId,function() {
                return t.imageProcessing
            }
            ,!0)),
            this._setAutoClearAndTextureSharing(this.imageProcessing)) : this._scene.imageProcessingConfiguration.applyByPostProcess = !1,
            (!this.cameras || this.cameras.length === 0) && (this._scene.imageProcessingConfiguration.applyByPostProcess = !1),
            this.imageProcessing.getEffect() || this.imageProcessing._updateParameters()),
            this.sharpenEnabled && (this.sharpen.isReady() || this.sharpen.updateEffect(),
            this.addEffect(this._sharpenEffect),
            this._setAutoClearAndTextureSharing(this.sharpen)),
            this.grainEnabled && (this.grain.isReady() || this.grain.updateEffect(),
            this.addEffect(this._grainEffect),
            this._setAutoClearAndTextureSharing(this.grain)),
            this.chromaticAberrationEnabled && (this.chromaticAberration.isReady() || this.chromaticAberration.updateEffect(),
            this.addEffect(this._chromaticAberrationEffect),
            this._setAutoClearAndTextureSharing(this.chromaticAberration)),
            this.fxaaEnabled && (this.fxaa = new FxaaPostProcess("fxaa",1,null,Texture.BILINEAR_SAMPLINGMODE,r,!1,this._defaultPipelineTextureType),
            this.addEffect(new PostProcessRenderEffect(r,this.FxaaPostProcessId,function() {
                return t.fxaa
            }
            ,!0)),
            this._setAutoClearAndTextureSharing(this.fxaa, !0)),
            this._cameras !== null && this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras),
            this._scene.activeCameras && this._scene.activeCameras.length > 1 && (this._scene.autoClear = !0),
            !this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1 && Logger$2.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0"),
            this.onBuildObservable.notifyObservers(this)
        }
    }
    ,
    e.prototype._disposePostProcesses = function(t) {
        t === void 0 && (t = !1);
        for (var r = 0; r < this._cameras.length; r++) {
            var n = this._cameras[r];
            this.imageProcessing && this.imageProcessing.dispose(n),
            this.fxaa && this.fxaa.dispose(n),
            t && (this.sharpen && this.sharpen.dispose(n),
            this.depthOfField && (this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver),
            this.depthOfField.disposeEffects(n)),
            this.bloom && this.bloom.disposeEffects(n),
            this.chromaticAberration && this.chromaticAberration.dispose(n),
            this.grain && this.grain.dispose(n),
            this._glowLayer && this._glowLayer.dispose())
        }
        this.imageProcessing = null,
        this.fxaa = null,
        t && (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)
    }
    ,
    e.prototype.addCamera = function(t) {
        this._camerasToBeAttached.push(t),
        this._buildPipeline()
    }
    ,
    e.prototype.removeCamera = function(t) {
        var r = this._camerasToBeAttached.indexOf(t);
        this._camerasToBeAttached.splice(r, 1),
        this._buildPipeline()
    }
    ,
    e.prototype.dispose = function() {
        this.onBuildObservable.clear(),
        this._disposePostProcesses(!0),
        this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras),
        this._scene.autoClear = !0,
        this._resizeObserver && (this._scene.getEngine().onResizeObservable.remove(this._resizeObserver),
        this._resizeObserver = null),
        this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver),
        i.prototype.dispose.call(this)
    }
    ,
    e.prototype.serialize = function() {
        var t = SerializationHelper.Serialize(this);
        return t.customType = "DefaultRenderingPipeline",
        t
    }
    ,
    e.Parse = function(t, r, n) {
        return SerializationHelper.Parse(function() {
            return new e(t._name,t._name._hdr,r)
        }, t, r, n)
    }
    ,
    __decorate([serialize()], e.prototype, "sharpenEnabled", null),
    __decorate([serialize()], e.prototype, "bloomKernel", null),
    __decorate([serialize()], e.prototype, "_bloomWeight", void 0),
    __decorate([serialize()], e.prototype, "_bloomThreshold", void 0),
    __decorate([serialize()], e.prototype, "_hdr", void 0),
    __decorate([serialize()], e.prototype, "bloomWeight", null),
    __decorate([serialize()], e.prototype, "bloomThreshold", null),
    __decorate([serialize()], e.prototype, "bloomScale", null),
    __decorate([serialize()], e.prototype, "bloomEnabled", null),
    __decorate([serialize()], e.prototype, "depthOfFieldEnabled", null),
    __decorate([serialize()], e.prototype, "depthOfFieldBlurLevel", null),
    __decorate([serialize()], e.prototype, "fxaaEnabled", null),
    __decorate([serialize()], e.prototype, "samples", null),
    __decorate([serialize()], e.prototype, "imageProcessingEnabled", null),
    __decorate([serialize()], e.prototype, "glowLayerEnabled", null),
    __decorate([serialize()], e.prototype, "chromaticAberrationEnabled", null),
    __decorate([serialize()], e.prototype, "grainEnabled", null),
    e
}(PostProcessRenderPipeline);
RegisterClass("BABYLON.DefaultRenderingPipeline", DefaultRenderingPipeline);
var Constants = function() {
    function i() {}
    return i.ALPHA_DISABLE = 0,
    i.ALPHA_ADD = 1,
    i.ALPHA_COMBINE = 2,
    i.ALPHA_SUBTRACT = 3,
    i.ALPHA_MULTIPLY = 4,
    i.ALPHA_MAXIMIZED = 5,
    i.ALPHA_ONEONE = 6,
    i.ALPHA_PREMULTIPLIED = 7,
    i.ALPHA_PREMULTIPLIED_PORTERDUFF = 8,
    i.ALPHA_INTERPOLATE = 9,
    i.ALPHA_SCREENMODE = 10,
    i.ALPHA_ONEONE_ONEONE = 11,
    i.ALPHA_ALPHATOCOLOR = 12,
    i.ALPHA_REVERSEONEMINUS = 13,
    i.ALPHA_SRC_DSTONEMINUSSRCALPHA = 14,
    i.ALPHA_ONEONE_ONEZERO = 15,
    i.ALPHA_EXCLUSION = 16,
    i.ALPHA_LAYER_ACCUMULATE = 17,
    i.ALPHA_EQUATION_ADD = 0,
    i.ALPHA_EQUATION_SUBSTRACT = 1,
    i.ALPHA_EQUATION_REVERSE_SUBTRACT = 2,
    i.ALPHA_EQUATION_MAX = 3,
    i.ALPHA_EQUATION_MIN = 4,
    i.ALPHA_EQUATION_DARKEN = 5,
    i.DELAYLOADSTATE_NONE = 0,
    i.DELAYLOADSTATE_LOADED = 1,
    i.DELAYLOADSTATE_LOADING = 2,
    i.DELAYLOADSTATE_NOTLOADED = 4,
    i.NEVER = 512,
    i.ALWAYS = 519,
    i.LESS = 513,
    i.EQUAL = 514,
    i.LEQUAL = 515,
    i.GREATER = 516,
    i.GEQUAL = 518,
    i.NOTEQUAL = 517,
    i.KEEP = 7680,
    i.ZERO = 0,
    i.REPLACE = 7681,
    i.INCR = 7682,
    i.DECR = 7683,
    i.INVERT = 5386,
    i.INCR_WRAP = 34055,
    i.DECR_WRAP = 34056,
    i.TEXTURE_CLAMP_ADDRESSMODE = 0,
    i.TEXTURE_WRAP_ADDRESSMODE = 1,
    i.TEXTURE_MIRROR_ADDRESSMODE = 2,
    i.TEXTURE_CREATIONFLAG_STORAGE = 1,
    i.TEXTUREFORMAT_ALPHA = 0,
    i.TEXTUREFORMAT_LUMINANCE = 1,
    i.TEXTUREFORMAT_LUMINANCE_ALPHA = 2,
    i.TEXTUREFORMAT_RGB = 4,
    i.TEXTUREFORMAT_RGBA = 5,
    i.TEXTUREFORMAT_RED = 6,
    i.TEXTUREFORMAT_R = 6,
    i.TEXTUREFORMAT_RG = 7,
    i.TEXTUREFORMAT_RED_INTEGER = 8,
    i.TEXTUREFORMAT_R_INTEGER = 8,
    i.TEXTUREFORMAT_RG_INTEGER = 9,
    i.TEXTUREFORMAT_RGB_INTEGER = 10,
    i.TEXTUREFORMAT_RGBA_INTEGER = 11,
    i.TEXTUREFORMAT_BGRA = 12,
    i.TEXTUREFORMAT_DEPTH24_STENCIL8 = 13,
    i.TEXTUREFORMAT_DEPTH32_FLOAT = 14,
    i.TEXTUREFORMAT_DEPTH16 = 15,
    i.TEXTUREFORMAT_DEPTH24 = 16,
    i.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM = 36492,
    i.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT = 36495,
    i.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT = 36494,
    i.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5 = 33779,
    i.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3 = 33778,
    i.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1 = 33777,
    i.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1 = 33776,
    i.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4 = 37808,
    i.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL = 36196,
    i.TEXTURETYPE_UNSIGNED_BYTE = 0,
    i.TEXTURETYPE_UNSIGNED_INT = 0,
    i.TEXTURETYPE_FLOAT = 1,
    i.TEXTURETYPE_HALF_FLOAT = 2,
    i.TEXTURETYPE_BYTE = 3,
    i.TEXTURETYPE_SHORT = 4,
    i.TEXTURETYPE_UNSIGNED_SHORT = 5,
    i.TEXTURETYPE_INT = 6,
    i.TEXTURETYPE_UNSIGNED_INTEGER = 7,
    i.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8,
    i.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9,
    i.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10,
    i.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11,
    i.TEXTURETYPE_UNSIGNED_INT_24_8 = 12,
    i.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13,
    i.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14,
    i.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15,
    i.TEXTURETYPE_UNDEFINED = 16,
    i.TEXTURE_NEAREST_SAMPLINGMODE = 1,
    i.TEXTURE_NEAREST_NEAREST = 1,
    i.TEXTURE_BILINEAR_SAMPLINGMODE = 2,
    i.TEXTURE_LINEAR_LINEAR = 2,
    i.TEXTURE_TRILINEAR_SAMPLINGMODE = 3,
    i.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3,
    i.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4,
    i.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5,
    i.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6,
    i.TEXTURE_NEAREST_LINEAR = 7,
    i.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 8,
    i.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9,
    i.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10,
    i.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 11,
    i.TEXTURE_LINEAR_NEAREST = 12,
    i.TEXTURE_EXPLICIT_MODE = 0,
    i.TEXTURE_SPHERICAL_MODE = 1,
    i.TEXTURE_PLANAR_MODE = 2,
    i.TEXTURE_CUBIC_MODE = 3,
    i.TEXTURE_PROJECTION_MODE = 4,
    i.TEXTURE_SKYBOX_MODE = 5,
    i.TEXTURE_INVCUBIC_MODE = 6,
    i.TEXTURE_EQUIRECTANGULAR_MODE = 7,
    i.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8,
    i.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9,
    i.TEXTURE_FILTERING_QUALITY_OFFLINE = 4096,
    i.TEXTURE_FILTERING_QUALITY_HIGH = 64,
    i.TEXTURE_FILTERING_QUALITY_MEDIUM = 16,
    i.TEXTURE_FILTERING_QUALITY_LOW = 8,
    i.SCALEMODE_FLOOR = 1,
    i.SCALEMODE_NEAREST = 2,
    i.SCALEMODE_CEILING = 3,
    i.MATERIAL_TextureDirtyFlag = 1,
    i.MATERIAL_LightDirtyFlag = 2,
    i.MATERIAL_FresnelDirtyFlag = 4,
    i.MATERIAL_AttributesDirtyFlag = 8,
    i.MATERIAL_MiscDirtyFlag = 16,
    i.MATERIAL_PrePassDirtyFlag = 32,
    i.MATERIAL_AllDirtyFlag = 63,
    i.MATERIAL_TriangleFillMode = 0,
    i.MATERIAL_WireFrameFillMode = 1,
    i.MATERIAL_PointFillMode = 2,
    i.MATERIAL_PointListDrawMode = 3,
    i.MATERIAL_LineListDrawMode = 4,
    i.MATERIAL_LineLoopDrawMode = 5,
    i.MATERIAL_LineStripDrawMode = 6,
    i.MATERIAL_TriangleStripDrawMode = 7,
    i.MATERIAL_TriangleFanDrawMode = 8,
    i.MATERIAL_ClockWiseSideOrientation = 0,
    i.MATERIAL_CounterClockWiseSideOrientation = 1,
    i.ACTION_NothingTrigger = 0,
    i.ACTION_OnPickTrigger = 1,
    i.ACTION_OnLeftPickTrigger = 2,
    i.ACTION_OnRightPickTrigger = 3,
    i.ACTION_OnCenterPickTrigger = 4,
    i.ACTION_OnPickDownTrigger = 5,
    i.ACTION_OnDoublePickTrigger = 6,
    i.ACTION_OnPickUpTrigger = 7,
    i.ACTION_OnPickOutTrigger = 16,
    i.ACTION_OnLongPressTrigger = 8,
    i.ACTION_OnPointerOverTrigger = 9,
    i.ACTION_OnPointerOutTrigger = 10,
    i.ACTION_OnEveryFrameTrigger = 11,
    i.ACTION_OnIntersectionEnterTrigger = 12,
    i.ACTION_OnIntersectionExitTrigger = 13,
    i.ACTION_OnKeyDownTrigger = 14,
    i.ACTION_OnKeyUpTrigger = 15,
    i.PARTICLES_BILLBOARDMODE_Y = 2,
    i.PARTICLES_BILLBOARDMODE_ALL = 7,
    i.PARTICLES_BILLBOARDMODE_STRETCHED = 8,
    i.MESHES_CULLINGSTRATEGY_STANDARD = 0,
    i.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1,
    i.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION = 2,
    i.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY = 3,
    i.SCENELOADER_NO_LOGGING = 0,
    i.SCENELOADER_MINIMAL_LOGGING = 1,
    i.SCENELOADER_SUMMARY_LOGGING = 2,
    i.SCENELOADER_DETAILED_LOGGING = 3,
    i.PREPASS_IRRADIANCE_TEXTURE_TYPE = 0,
    i.PREPASS_POSITION_TEXTURE_TYPE = 1,
    i.PREPASS_VELOCITY_TEXTURE_TYPE = 2,
    i.PREPASS_REFLECTIVITY_TEXTURE_TYPE = 3,
    i.PREPASS_COLOR_TEXTURE_TYPE = 4,
    i.PREPASS_DEPTH_TEXTURE_TYPE = 5,
    i.PREPASS_NORMAL_TEXTURE_TYPE = 6,
    i.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE = 7,
    i.BUFFER_CREATIONFLAG_READ = 1,
    i.BUFFER_CREATIONFLAG_WRITE = 2,
    i.BUFFER_CREATIONFLAG_READWRITE = 3,
    i.BUFFER_CREATIONFLAG_UNIFORM = 4,
    i.BUFFER_CREATIONFLAG_VERTEX = 8,
    i.BUFFER_CREATIONFLAG_INDEX = 16,
    i.BUFFER_CREATIONFLAG_STORAGE = 32,
    i.RENDERPASS_MAIN = 0,
    i.INPUT_ALT_KEY = 18,
    i.INPUT_CTRL_KEY = 17,
    i.INPUT_META_KEY1 = 91,
    i.INPUT_META_KEY2 = 92,
    i.INPUT_META_KEY3 = 93,
    i.INPUT_SHIFT_KEY = 16,
    i.SNAPSHOTRENDERING_STANDARD = 0,
    i.SNAPSHOTRENDERING_FAST = 1,
    i.PERSPECTIVE_CAMERA = 0,
    i.ORTHOGRAPHIC_CAMERA = 1,
    i.FOVMODE_VERTICAL_FIXED = 0,
    i.FOVMODE_HORIZONTAL_FIXED = 1,
    i.RIG_MODE_NONE = 0,
    i.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10,
    i.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11,
    i.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12,
    i.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13,
    i.RIG_MODE_STEREOSCOPIC_INTERLACED = 14,
    i.RIG_MODE_VR = 20,
    i.RIG_MODE_WEBVR = 21,
    i.RIG_MODE_CUSTOM = 22,
    i.MAX_SUPPORTED_UV_SETS = 6,
    i.GL_ALPHA_EQUATION_ADD = 32774,
    i.GL_ALPHA_EQUATION_MIN = 32775,
    i.GL_ALPHA_EQUATION_MAX = 32776,
    i.GL_ALPHA_EQUATION_SUBTRACT = 32778,
    i.GL_ALPHA_EQUATION_REVERSE_SUBTRACT = 32779,
    i.GL_ALPHA_FUNCTION_SRC = 768,
    i.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR = 769,
    i.GL_ALPHA_FUNCTION_SRC_ALPHA = 770,
    i.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA = 771,
    i.GL_ALPHA_FUNCTION_DST_ALPHA = 772,
    i.GL_ALPHA_FUNCTION_ONE_MINUS_DST_ALPHA = 773,
    i.GL_ALPHA_FUNCTION_DST_COLOR = 774,
    i.GL_ALPHA_FUNCTION_ONE_MINUS_DST_COLOR = 775,
    i.GL_ALPHA_FUNCTION_SRC_ALPHA_SATURATED = 776,
    i.GL_ALPHA_FUNCTION_CONSTANT_COLOR = 32769,
    i.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_COLOR = 32770,
    i.GL_ALPHA_FUNCTION_CONSTANT_ALPHA = 32771,
    i.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_ALPHA = 32772,
    i
}()
  , name$G = "imageProcessingCompatibility"
  , shader$G = `#ifdef IMAGEPROCESSINGPOSTPROCESS
gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(2.2));
#endif`;
ShaderStore.IncludesShadersStore[name$G] = shader$G;
var name$F = "gridPixelShader"
  , shader$F = `#extension GL_OES_standard_derivatives : enable
#define SQRT2 1.41421356
#define PI 3.14159
precision highp float;
uniform float visibility;
uniform vec3 mainColor;
uniform vec3 lineColor;
uniform vec4 gridControl;
uniform vec3 gridOffset;

varying vec3 vPosition;
varying vec3 vNormal;
#include<fogFragmentDeclaration>

#ifdef OPACITY
varying vec2 vOpacityUV;
uniform sampler2D opacitySampler;
uniform vec2 vOpacityInfos;
#endif
float getDynamicVisibility(float position) {

float majorGridFrequency=gridControl.y;
if (floor(position+0.5) == floor(position/majorGridFrequency+0.5)*majorGridFrequency)
{
return 1.0;
}
return gridControl.z;
}
float getAnisotropicAttenuation(float differentialLength) {
const float maxNumberOfLines=10.0;
return clamp(1.0/(differentialLength+1.0)-1.0/maxNumberOfLines,0.0,1.0);
}
float isPointOnLine(float position,float differentialLength) {
float fractionPartOfPosition=position-floor(position+0.5);
fractionPartOfPosition/=differentialLength;
fractionPartOfPosition=clamp(fractionPartOfPosition,-1.,1.);
float result=0.5+0.5*cos(fractionPartOfPosition*PI);
return result;
}
float contributionOnAxis(float position) {
float differentialLength=length(vec2(dFdx(position),dFdy(position)));
differentialLength*=SQRT2;

float result=isPointOnLine(position,differentialLength);

float dynamicVisibility=getDynamicVisibility(position);
result*=dynamicVisibility;

float anisotropicAttenuation=getAnisotropicAttenuation(differentialLength);
result*=anisotropicAttenuation;
return result;
}
float normalImpactOnAxis(float x) {
float normalImpact=clamp(1.0-3.0*abs(x*x*x),0.0,1.0);
return normalImpact;
}
void main(void) {

float gridRatio=gridControl.x;
vec3 gridPos=(vPosition+gridOffset.xyz)/gridRatio;

float x=contributionOnAxis(gridPos.x);
float y=contributionOnAxis(gridPos.y);
float z=contributionOnAxis(gridPos.z);

vec3 normal=normalize(vNormal);
x*=normalImpactOnAxis(normal.x);
y*=normalImpactOnAxis(normal.y);
z*=normalImpactOnAxis(normal.z);
#ifdef MAX_LINE

float grid=clamp(max(max(x,y),z),0.,1.);
#else

float grid=clamp(x+y+z,0.,1.);
#endif

vec3 color=mix(mainColor,lineColor,grid);
#ifdef FOG
#include<fogFragment>
#endif
float opacity=1.0;
#ifdef TRANSPARENT
opacity=clamp(grid,0.08,gridControl.w*grid);
#endif
#ifdef OPACITY
opacity*=texture2D(opacitySampler,vOpacityUV).a;
#endif

gl_FragColor=vec4(color.rgb,opacity*visibility);
#ifdef TRANSPARENT
#ifdef PREMULTIPLYALPHA
gl_FragColor.rgb*=opacity;
#endif
#else
#endif
#include<imageProcessingCompatibility>
}
`;
ShaderStore.ShadersStore[name$F] = shader$F;
var name$E = "gridVertexShader"
  , shader$E = `precision highp float;

attribute vec3 position;
attribute vec3 normal;
#ifdef UV1
attribute vec2 uv;
#endif
#ifdef UV2
attribute vec2 uv2;
#endif
#include<instancesDeclaration>

uniform mat4 projection;
uniform mat4 view;

varying vec3 vPosition;
varying vec3 vNormal;
#include<fogVertexDeclaration>
#ifdef OPACITY
varying vec2 vOpacityUV;
uniform mat4 opacityMatrix;
uniform vec2 vOpacityInfos;
#endif
void main(void) {
#include<instancesVertex>
vec4 worldPos=finalWorld*vec4(position,1.0);
#include<fogVertex>
vec4 cameraSpacePosition=view*worldPos;
gl_Position=projection*cameraSpacePosition;
#ifdef OPACITY
#ifndef UV1
vec2 uv=vec2(0.,0.);
#endif
#ifndef UV2
vec2 uv2=vec2(0.,0.);
#endif
if (vOpacityInfos.x == 0.)
{
vOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));
}
else
{
vOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));
}
#endif
vPosition=position;
vNormal=normal;
}`;
ShaderStore.ShadersStore[name$E] = shader$E;
var GridMaterialDefines = function(i) {
    __extends(e, i);
    function e() {
        var t = i.call(this) || this;
        return t.OPACITY = !1,
        t.TRANSPARENT = !1,
        t.FOG = !1,
        t.PREMULTIPLYALPHA = !1,
        t.MAX_LINE = !1,
        t.UV1 = !1,
        t.UV2 = !1,
        t.INSTANCES = !1,
        t.THIN_INSTANCES = !1,
        t.IMAGEPROCESSINGPOSTPROCESS = !1,
        t.SKIPFINALCOLORCLAMP = !1,
        t.rebuild(),
        t
    }
    return e
}(MaterialDefines)
  , GridMaterial = function(i) {
    __extends(e, i);
    function e(t, r) {
        var n = i.call(this, t, r) || this;
        return n.mainColor = Color3.Black(),
        n.lineColor = Color3.Teal(),
        n.gridRatio = 1,
        n.gridOffset = Vector3.Zero(),
        n.majorUnitFrequency = 10,
        n.minorUnitVisibility = .33,
        n.opacity = 1,
        n.preMultiplyAlpha = !1,
        n.useMaxLine = !1,
        n._gridControl = new Vector4(n.gridRatio,n.majorUnitFrequency,n.minorUnitVisibility,n.opacity),
        n
    }
    return e.prototype.needAlphaBlending = function() {
        return this.opacity < 1 || this._opacityTexture && this._opacityTexture.isReady()
    }
    ,
    e.prototype.needAlphaBlendingForMesh = function(t) {
        return t.visibility < 1 || this.needAlphaBlending()
    }
    ,
    e.prototype.isReadyForSubMesh = function(t, r, n) {
        if (this.isFrozen && r.effect && r.effect._wasPreviouslyReady)
            return !0;
        r.materialDefines || (r.materialDefines = new GridMaterialDefines);
        var o = r.materialDefines
          , a = this.getScene();
        if (this._isReadyForSubMesh(r))
            return !0;
        if (o.TRANSPARENT !== this.opacity < 1 && (o.TRANSPARENT = !o.TRANSPARENT,
        o.markAsUnprocessed()),
        o.PREMULTIPLYALPHA != this.preMultiplyAlpha && (o.PREMULTIPLYALPHA = !o.PREMULTIPLYALPHA,
        o.markAsUnprocessed()),
        o.MAX_LINE !== this.useMaxLine && (o.MAX_LINE = !o.MAX_LINE,
        o.markAsUnprocessed()),
        o._areTexturesDirty && (o._needUVs = !1,
        a.texturesEnabled && this._opacityTexture && MaterialFlags.OpacityTextureEnabled))
            if (this._opacityTexture.isReady())
                o._needUVs = !0,
                o.OPACITY = !0;
            else
                return !1;
        if (MaterialHelper.PrepareDefinesForMisc(t, a, !1, !1, this.fogEnabled, !1, o),
        MaterialHelper.PrepareDefinesForFrameBoundValues(a, a.getEngine(), o, !!n),
        o.isDirty) {
            o.markAsProcessed(),
            a.resetCachedMaterial(),
            MaterialHelper.PrepareDefinesForAttributes(t, o, !1, !1);
            var s = [VertexBuffer.PositionKind, VertexBuffer.NormalKind];
            o.UV1 && s.push(VertexBuffer.UVKind),
            o.UV2 && s.push(VertexBuffer.UV2Kind),
            o.IMAGEPROCESSINGPOSTPROCESS = a.imageProcessingConfiguration.applyByPostProcess,
            MaterialHelper.PrepareAttributesForInstances(s, o);
            var l = o.toString();
            r.setEffect(a.getEngine().createEffect("grid", s, ["projection", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view", "opacityMatrix", "vOpacityInfos", "visibility"], ["opacitySampler"], l, void 0, this.onCompiled, this.onError), o, this._materialContext)
        }
        return !r.effect || !r.effect.isReady() ? !1 : (o._renderId = a.getRenderId(),
        r.effect._wasPreviouslyReady = !0,
        !0)
    }
    ,
    e.prototype.bindForSubMesh = function(t, r, n) {
        var o = this.getScene()
          , a = n.materialDefines;
        if (!!a) {
            var s = n.effect;
            !s || (this._activeEffect = s,
            this._activeEffect.setFloat("visibility", r.visibility),
            (!a.INSTANCES || a.THIN_INSTANCE) && this.bindOnlyWorldMatrix(t),
            this._activeEffect.setMatrix("view", o.getViewMatrix()),
            this._activeEffect.setMatrix("projection", o.getProjectionMatrix()),
            this._mustRebind(o, s) && (this._activeEffect.setColor3("mainColor", this.mainColor),
            this._activeEffect.setColor3("lineColor", this.lineColor),
            this._activeEffect.setVector3("gridOffset", this.gridOffset),
            this._gridControl.x = this.gridRatio,
            this._gridControl.y = Math.round(this.majorUnitFrequency),
            this._gridControl.z = this.minorUnitVisibility,
            this._gridControl.w = this.opacity,
            this._activeEffect.setVector4("gridControl", this._gridControl),
            this._opacityTexture && MaterialFlags.OpacityTextureEnabled && (this._activeEffect.setTexture("opacitySampler", this._opacityTexture),
            this._activeEffect.setFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level),
            this._activeEffect.setMatrix("opacityMatrix", this._opacityTexture.getTextureMatrix()))),
            MaterialHelper.BindFogParameters(o, r, this._activeEffect),
            this._afterBind(r, this._activeEffect))
        }
    }
    ,
    e.prototype.dispose = function(t) {
        i.prototype.dispose.call(this, t)
    }
    ,
    e.prototype.clone = function(t) {
        var r = this;
        return SerializationHelper.Clone(function() {
            return new e(t,r.getScene())
        }, this)
    }
    ,
    e.prototype.serialize = function() {
        var t = SerializationHelper.Serialize(this);
        return t.customType = "BABYLON.GridMaterial",
        t
    }
    ,
    e.prototype.getClassName = function() {
        return "GridMaterial"
    }
    ,
    e.Parse = function(t, r, n) {
        return SerializationHelper.Parse(function() {
            return new e(t.name,r)
        }, t, r, n)
    }
    ,
    __decorate([serializeAsColor3()], e.prototype, "mainColor", void 0),
    __decorate([serializeAsColor3()], e.prototype, "lineColor", void 0),
    __decorate([serialize()], e.prototype, "gridRatio", void 0),
    __decorate([serializeAsVector3()], e.prototype, "gridOffset", void 0),
    __decorate([serialize()], e.prototype, "majorUnitFrequency", void 0),
    __decorate([serialize()], e.prototype, "minorUnitVisibility", void 0),
    __decorate([serialize()], e.prototype, "opacity", void 0),
    __decorate([serialize()], e.prototype, "preMultiplyAlpha", void 0),
    __decorate([serialize()], e.prototype, "useMaxLine", void 0),
    __decorate([serializeAsTexture("opacityTexture")], e.prototype, "_opacityTexture", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "opacityTexture", void 0),
    e
}(PushMaterial);
RegisterClass("BABYLON.GridMaterial", GridMaterial);
var SceneInstrumentation = function() {
    function i(e) {
        var t = this;
        this.scene = e,
        this._captureActiveMeshesEvaluationTime = !1,
        this._activeMeshesEvaluationTime = new PerfCounter,
        this._captureRenderTargetsRenderTime = !1,
        this._renderTargetsRenderTime = new PerfCounter,
        this._registerBeforeRenderTime = new PerfCounter,
        this._onBeforeRegisterBeforeRenderObserver = null,
        this._onAfterRegisterBeforeRenderObserver = null,
        this._RTT1Time = new PerfCounter,
        this._onBeforeRTT1Observer = null,
        this._onAfterRTT1Observer = null,
        this._registerAfterRenderTime = new PerfCounter,
        this._onBeforeRegisterAfterRenderObserver = null,
        this._onAfterRegisterAfterRenderObserver = null,
        this._captureFrameTime = !1,
        this._frameTime = new PerfCounter,
        this._captureRenderTime = !1,
        this._renderTime = new PerfCounter,
        this._captureInterFrameTime = !1,
        this._interFrameTime = new PerfCounter,
        this._captureParticlesRenderTime = !1,
        this._particlesRenderTime = new PerfCounter,
        this._captureSpritesRenderTime = !1,
        this._spritesRenderTime = new PerfCounter,
        this._capturePhysicsTime = !1,
        this._physicsTime = new PerfCounter,
        this._captureAnimationsTime = !1,
        this._animationsTime = new PerfCounter,
        this._captureCameraRenderTime = !1,
        this._cameraRenderTime = new PerfCounter,
        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,
        this._onBeforeAnimationsObserver = e.onBeforeAnimationsObservable.add(function() {
            t._captureActiveMeshesEvaluationTime && t._activeMeshesEvaluationTime.fetchNewFrame(),
            t._captureRenderTargetsRenderTime && t._renderTargetsRenderTime.fetchNewFrame(),
            t._captureFrameTime && (Tools.StartPerformanceCounter("Scene rendering"),
            t._frameTime.beginMonitoring()),
            t._captureInterFrameTime && t._interFrameTime.endMonitoring(),
            t._captureParticlesRenderTime && t._particlesRenderTime.fetchNewFrame(),
            t._captureSpritesRenderTime && t._spritesRenderTime.fetchNewFrame(),
            t._captureAnimationsTime && t._animationsTime.beginMonitoring(),
            t.scene.getEngine()._drawCalls.fetchNewFrame()
        }),
        this._onAfterRenderObserver = e.onAfterRenderObservable.add(function() {
            t._captureFrameTime && (Tools.EndPerformanceCounter("Scene rendering"),
            t._frameTime.endMonitoring()),
            t._captureRenderTime && t._renderTime.endMonitoring(!1),
            t._captureInterFrameTime && t._interFrameTime.beginMonitoring()
        }),
        this._onBeforeRegisterBeforeRenderObserver = e.onBeforeRunRegisterBeforeRenderObservable.add(function() {
            t._registerBeforeRenderTime.beginMonitoring()
        }),
        this._onAfterRegisterBeforeRenderObserver = e.onAfterRunRegisterBeforeRenderObservable.add(function() {
            t._registerBeforeRenderTime.endMonitoring()
        }),
        this._onBeforeRegisterAfterRenderObserver = e.onBeforeRunRegisterAfterRenderObservable.add(function() {
            t._registerAfterRenderTime.beginMonitoring()
        }),
        this._onAfterRegisterAfterRenderObserver = e.onAfterRunRegisterAfterRenderObservable.add(function() {
            t._registerAfterRenderTime.endMonitoring()
        }),
        this._onBeforeRTT1Observer = e.onBeforeRTT1Observable.add(function() {
            t._RTT1Time.beginMonitoring()
        }),
        this._onAfterRTT1Observer = e.onAfterRTT1Observable.add(function() {
            t._RTT1Time.endMonitoring()
        })
    }
    return Object.defineProperty(i.prototype, "activeMeshesEvaluationTimeCounter", {
        get: function() {
            return this._activeMeshesEvaluationTime
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "captureActiveMeshesEvaluationTime", {
        get: function() {
            return this._captureActiveMeshesEvaluationTime
        },
        set: function(e) {
            var t = this;
            e !== this._captureActiveMeshesEvaluationTime && (this._captureActiveMeshesEvaluationTime = e,
            e ? (this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function() {
                Tools.StartPerformanceCounter("Active meshes evaluation"),
                t._activeMeshesEvaluationTime.beginMonitoring()
            }),
            this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function() {
                Tools.EndPerformanceCounter("Active meshes evaluation"),
                t._activeMeshesEvaluationTime.endMonitoring()
            })) : (this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver),
            this._onBeforeActiveMeshesEvaluationObserver = null,
            this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver),
            this._onAfterActiveMeshesEvaluationObserver = null))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "renderTargetsRenderTimeCounter", {
        get: function() {
            return this._renderTargetsRenderTime
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "registerBeforeTimeCounter", {
        get: function() {
            return this._registerBeforeRenderTime
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "getRTT1TimeCounter", {
        get: function() {
            return this._RTT1Time
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "registerAfterTimeCounter", {
        get: function() {
            return this._registerAfterRenderTime
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "captureRenderTargetsRenderTime", {
        get: function() {
            return this._captureRenderTargetsRenderTime
        },
        set: function(e) {
            var t = this;
            e !== this._captureRenderTargetsRenderTime && (this._captureRenderTargetsRenderTime = e,
            e ? (this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function() {
                Tools.StartPerformanceCounter("Render targets rendering"),
                t._renderTargetsRenderTime.beginMonitoring()
            }),
            this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function() {
                Tools.EndPerformanceCounter("Render targets rendering"),
                t._renderTargetsRenderTime.endMonitoring(!1)
            })) : (this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver),
            this._onBeforeRenderTargetsRenderObserver = null,
            this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver),
            this._onAfterRenderTargetsRenderObserver = null))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "particlesRenderTimeCounter", {
        get: function() {
            return this._particlesRenderTime
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "captureParticlesRenderTime", {
        get: function() {
            return this._captureParticlesRenderTime
        },
        set: function(e) {
            var t = this;
            e !== this._captureParticlesRenderTime && (this._captureParticlesRenderTime = e,
            e ? (this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function() {
                Tools.StartPerformanceCounter("Particles"),
                t._particlesRenderTime.beginMonitoring()
            }),
            this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function() {
                Tools.EndPerformanceCounter("Particles"),
                t._particlesRenderTime.endMonitoring(!1)
            })) : (this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver),
            this._onBeforeParticlesRenderingObserver = null,
            this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver),
            this._onAfterParticlesRenderingObserver = null))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "spritesRenderTimeCounter", {
        get: function() {
            return this._spritesRenderTime
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "captureSpritesRenderTime", {
        get: function() {
            return this._captureSpritesRenderTime
        },
        set: function(e) {
            var t = this;
            e !== this._captureSpritesRenderTime && (this._captureSpritesRenderTime = e,
            this.scene.spriteManagers && (e ? (this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function() {
                Tools.StartPerformanceCounter("Sprites"),
                t._spritesRenderTime.beginMonitoring()
            }),
            this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function() {
                Tools.EndPerformanceCounter("Sprites"),
                t._spritesRenderTime.endMonitoring(!1)
            })) : (this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver),
            this._onBeforeSpritesRenderingObserver = null,
            this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver),
            this._onAfterSpritesRenderingObserver = null)))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "physicsTimeCounter", {
        get: function() {
            return this._physicsTime
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "capturePhysicsTime", {
        get: function() {
            return this._capturePhysicsTime
        },
        set: function(e) {
            var t = this;
            e !== this._capturePhysicsTime && (!this.scene.onBeforePhysicsObservable || (this._capturePhysicsTime = e,
            e ? (this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function() {
                Tools.StartPerformanceCounter("Physics"),
                t._physicsTime.beginMonitoring()
            }),
            this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function() {
                Tools.EndPerformanceCounter("Physics"),
                t._physicsTime.endMonitoring()
            })) : (this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver),
            this._onBeforePhysicsObserver = null,
            this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver),
            this._onAfterPhysicsObserver = null)))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "animationsTimeCounter", {
        get: function() {
            return this._animationsTime
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "captureAnimationsTime", {
        get: function() {
            return this._captureAnimationsTime
        },
        set: function(e) {
            var t = this;
            e !== this._captureAnimationsTime && (this._captureAnimationsTime = e,
            e ? this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function() {
                t._animationsTime.endMonitoring()
            }) : (this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver),
            this._onAfterAnimationsObserver = null))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "frameTimeCounter", {
        get: function() {
            return this._frameTime
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "captureFrameTime", {
        get: function() {
            return this._captureFrameTime
        },
        set: function(e) {
            this._captureFrameTime = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "interFrameTimeCounter", {
        get: function() {
            return this._interFrameTime
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "captureInterFrameTime", {
        get: function() {
            return this._captureInterFrameTime
        },
        set: function(e) {
            this._captureInterFrameTime = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "renderTimeCounter", {
        get: function() {
            return this._renderTime
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "captureRenderTime", {
        get: function() {
            return this._captureRenderTime
        },
        set: function(e) {
            var t = this;
            e !== this._captureRenderTime && (this._captureRenderTime = e,
            e ? (this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function() {
                t._renderTime.beginMonitoring(),
                Tools.StartPerformanceCounter("Main render")
            }),
            this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function() {
                t._renderTime.endMonitoring(!1),
                Tools.EndPerformanceCounter("Main render")
            })) : (this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver),
            this._onBeforeDrawPhaseObserver = null,
            this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver),
            this._onAfterDrawPhaseObserver = null))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "cameraRenderTimeCounter", {
        get: function() {
            return this._cameraRenderTime
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "captureCameraRenderTime", {
        get: function() {
            return this._captureCameraRenderTime
        },
        set: function(e) {
            var t = this;
            e !== this._captureCameraRenderTime && (this._captureCameraRenderTime = e,
            e ? (this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function(r) {
                t._cameraRenderTime.beginMonitoring(),
                Tools.StartPerformanceCounter("Rendering camera " + r.name)
            }),
            this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function(r) {
                t._cameraRenderTime.endMonitoring(!1),
                Tools.EndPerformanceCounter("Rendering camera " + r.name)
            })) : (this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),
            this._onBeforeCameraRenderObserver = null,
            this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),
            this._onAfterCameraRenderObserver = null))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "drawCallsCounter", {
        get: function() {
            return this.scene.getEngine()._drawCalls
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.dispose = function() {
        this.scene.onBeforeRunRegisterBeforeRenderObservable.remove(this._onBeforeRegisterBeforeRenderObserver),
        this._onBeforeRegisterBeforeRenderObserver = null,
        this.scene.onAfterRunRegisterBeforeRenderObservable.remove(this._onAfterRegisterBeforeRenderObserver),
        this._onAfterRegisterBeforeRenderObserver = null,
        this.scene.onBeforeRunRegisterAfterRenderObservable.remove(this._onBeforeRegisterAfterRenderObserver),
        this._onBeforeRegisterAfterRenderObserver = null,
        this.scene.onAfterRunRegisterAfterRenderObservable.remove(this._onAfterRegisterAfterRenderObserver),
        this._onAfterRegisterAfterRenderObserver = null,
        this.scene.onBeforeRTT1Observable.remove(this._onBeforeRTT1Observer),
        this._onBeforeRTT1Observer = null,
        this.scene.onAfterRTT1Observable.remove(this._onAfterRTT1Observer),
        this._onAfterRTT1Observer = null,
        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,
        this._onBeforeSpritesRenderingObserver && (this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver),
        this._onBeforeSpritesRenderingObserver = null),
        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,
        this._onBeforePhysicsObserver && (this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver),
        this._onBeforePhysicsObserver = null),
        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
    }
    ,
    i
}()
  , EngineInstrumentation = function() {
    function i(e) {
        this.engine = e,
        this._captureGPUFrameTime = !1,
        this._captureShaderCompilationTime = !1,
        this._shaderCompilationTime = new PerfCounter,
        this._onBeginFrameObserver = null,
        this._onEndFrameObserver = null,
        this._onBeforeShaderCompilationObserver = null,
        this._onAfterShaderCompilationObserver = null
    }
    return Object.defineProperty(i.prototype, "gpuFrameTimeCounter", {
        get: function() {
            return this.engine.getGPUFrameTimeCounter()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "captureGPUFrameTime", {
        get: function() {
            return this._captureGPUFrameTime
        },
        set: function(e) {
            e !== this._captureGPUFrameTime && (this._captureGPUFrameTime = e,
            this.engine.captureGPUFrameTime(e))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "shaderCompilationTimeCounter", {
        get: function() {
            return this._shaderCompilationTime
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "captureShaderCompilationTime", {
        get: function() {
            return this._captureShaderCompilationTime
        },
        set: function(e) {
            var t = this;
            e !== this._captureShaderCompilationTime && (this._captureShaderCompilationTime = e,
            e ? (this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function() {
                t._shaderCompilationTime.fetchNewFrame(),
                t._shaderCompilationTime.beginMonitoring()
            }),
            this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function() {
                t._shaderCompilationTime.endMonitoring()
            })) : (this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver),
            this._onBeforeShaderCompilationObserver = null,
            this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver),
            this._onAfterShaderCompilationObserver = null))
        },
        enumerable: !1,
        configurable: !0
    }),
    i.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
    }
    ,
    i
}()
  , KeepAssets = function(i) {
    __extends(e, i);
    function e() {
        return i !== null && i.apply(this, arguments) || this
    }
    return e
}(AbstractScene)
  , InstantiatedEntries = function() {
    function i() {
        this.rootNodes = [],
        this.skeletons = [],
        this.animationGroups = []
    }
    return i
}()
  , AssetContainer = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this) || this;
        return r._wasAddedToScene = !1,
        r.scene = t,
        r.sounds = [],
        r.effectLayers = [],
        r.layers = [],
        r.lensFlareSystems = [],
        r.proceduralTextures = [],
        r.reflectionProbes = [],
        t.onDisposeObservable.add(function() {
            r._wasAddedToScene || r.dispose()
        }),
        r._onContextRestoredObserver = t.getEngine().onContextRestoredObservable.add(function() {
            for (var n = 0, o = r.geometries; n < o.length; n++) {
                var a = o[n];
                a._rebuild()
            }
            for (var s = 0, l = r.meshes; s < l.length; s++) {
                var u = l[s];
                u._rebuild()
            }
            for (var c = 0, h = r.particleSystems; c < h.length; c++) {
                var f = h[c];
                f.rebuild()
            }
            for (var d = 0, _ = r.textures; d < _.length; d++) {
                var g = _[d];
                g._rebuild()
            }
        }),
        r
    }
    return e.prototype.instantiateModelsToScene = function(t, r, n) {
        var o = this;
        r === void 0 && (r = !1);
        var a = {}
          , s = {}
          , l = new InstantiatedEntries
          , u = []
          , c = [];
        n || (n = {
            doNotInstantiate: !0
        });
        var h = function(f, d) {
            if (a[f.uniqueId] = d.uniqueId,
            s[d.uniqueId] = d,
            t && (d.name = t(f.name)),
            d instanceof Mesh) {
                var _ = d;
                if (_.morphTargetManager) {
                    var g = f.morphTargetManager;
                    _.morphTargetManager = g.clone();
                    for (var m = 0; m < g.numTargets; m++) {
                        var v = g.getTarget(m)
                          , y = _.morphTargetManager.getTarget(m);
                        a[v.uniqueId] = y.uniqueId,
                        s[y.uniqueId] = y
                    }
                }
            }
        };
        return this.transformNodes.forEach(function(f) {
            if (!f.parent) {
                var d = f.instantiateHierarchy(null, n, function(_, g) {
                    h(_, g)
                });
                d && l.rootNodes.push(d)
            }
        }),
        this.meshes.forEach(function(f) {
            if (!f.parent) {
                var d = f.instantiateHierarchy(null, n, function(_, g) {
                    if (h(_, g),
                    g.material) {
                        var m = g;
                        if (m.material)
                            if (r) {
                                var v = _.material;
                                if (c.indexOf(v) === -1) {
                                    var y = v.clone(t ? t(v.name) : "Clone of " + v.name);
                                    if (c.push(v),
                                    a[v.uniqueId] = y.uniqueId,
                                    s[y.uniqueId] = y,
                                    v.getClassName() === "MultiMaterial") {
                                        for (var b = v, T = 0, C = b.subMaterials; T < C.length; T++) {
                                            var A = C[T];
                                            !A || (y = A.clone(t ? t(A.name) : "Clone of " + A.name),
                                            c.push(A),
                                            a[A.uniqueId] = y.uniqueId,
                                            s[y.uniqueId] = y)
                                        }
                                        b.subMaterials = b.subMaterials.map(function(S) {
                                            return S && s[a[S.uniqueId]]
                                        })
                                    }
                                }
                                m.getClassName() !== "InstancedMesh" && (m.material = s[a[v.uniqueId]])
                            } else
                                m.material.getClassName() === "MultiMaterial" ? o.scene.multiMaterials.indexOf(m.material) === -1 && o.scene.addMultiMaterial(m.material) : o.scene.materials.indexOf(m.material) === -1 && o.scene.addMaterial(m.material)
                    }
                });
                d && l.rootNodes.push(d)
            }
        }),
        this.skeletons.forEach(function(f) {
            var d = f.clone(t ? t(f.name) : "Clone of " + f.name);
            f.overrideMesh && (d.overrideMesh = s[a[f.overrideMesh.uniqueId]]);
            for (var _ = 0, g = o.meshes; _ < g.length; _++) {
                var m = g[_];
                if (m.skeleton === f && !m.isAnInstance) {
                    var v = s[a[m.uniqueId]];
                    if (v.isAnInstance || (v.skeleton = d,
                    u.indexOf(d) !== -1))
                        continue;
                    u.push(d);
                    for (var y = 0, b = d.bones; y < b.length; y++) {
                        var T = b[y];
                        T._linkedTransformNode && (T._linkedTransformNode = s[a[T._linkedTransformNode.uniqueId]])
                    }
                }
            }
            l.skeletons.push(d)
        }),
        this.animationGroups.forEach(function(f) {
            var d = f.clone(f.name, function(_) {
                var g = s[a[_.uniqueId]];
                return g || _
            });
            l.animationGroups.push(d)
        }),
        l
    }
    ,
    e.prototype.addAllToScene = function() {
        var t = this;
        this._wasAddedToScene = !0,
        this.cameras.forEach(function(a) {
            t.scene.addCamera(a)
        }),
        this.lights.forEach(function(a) {
            t.scene.addLight(a)
        }),
        this.meshes.forEach(function(a) {
            t.scene.addMesh(a)
        }),
        this.skeletons.forEach(function(a) {
            t.scene.addSkeleton(a)
        }),
        this.animations.forEach(function(a) {
            t.scene.addAnimation(a)
        }),
        this.animationGroups.forEach(function(a) {
            t.scene.addAnimationGroup(a)
        }),
        this.multiMaterials.forEach(function(a) {
            t.scene.addMultiMaterial(a)
        }),
        this.materials.forEach(function(a) {
            t.scene.addMaterial(a)
        }),
        this.morphTargetManagers.forEach(function(a) {
            t.scene.addMorphTargetManager(a)
        }),
        this.geometries.forEach(function(a) {
            t.scene.addGeometry(a)
        }),
        this.transformNodes.forEach(function(a) {
            t.scene.addTransformNode(a)
        }),
        this.actionManagers.forEach(function(a) {
            t.scene.addActionManager(a)
        }),
        this.textures.forEach(function(a) {
            t.scene.addTexture(a)
        }),
        this.reflectionProbes.forEach(function(a) {
            t.scene.addReflectionProbe(a)
        }),
        this.environmentTexture && (this.scene.environmentTexture = this.environmentTexture);
        for (var r = 0, n = this.scene._serializableComponents; r < n.length; r++) {
            var o = n[r];
            o.addFromContainer(this)
        }
        this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),
        this._onContextRestoredObserver = null
    }
    ,
    e.prototype.removeAllFromScene = function() {
        var t = this;
        this._wasAddedToScene = !1,
        this.cameras.forEach(function(a) {
            t.scene.removeCamera(a)
        }),
        this.lights.forEach(function(a) {
            t.scene.removeLight(a)
        }),
        this.meshes.forEach(function(a) {
            t.scene.removeMesh(a)
        }),
        this.skeletons.forEach(function(a) {
            t.scene.removeSkeleton(a)
        }),
        this.animations.forEach(function(a) {
            t.scene.removeAnimation(a)
        }),
        this.animationGroups.forEach(function(a) {
            t.scene.removeAnimationGroup(a)
        }),
        this.multiMaterials.forEach(function(a) {
            t.scene.removeMultiMaterial(a)
        }),
        this.materials.forEach(function(a) {
            t.scene.removeMaterial(a)
        }),
        this.morphTargetManagers.forEach(function(a) {
            t.scene.removeMorphTargetManager(a)
        }),
        this.geometries.forEach(function(a) {
            t.scene.removeGeometry(a)
        }),
        this.transformNodes.forEach(function(a) {
            t.scene.removeTransformNode(a)
        }),
        this.actionManagers.forEach(function(a) {
            t.scene.removeActionManager(a)
        }),
        this.textures.forEach(function(a) {
            t.scene.removeTexture(a)
        }),
        this.reflectionProbes.forEach(function(a) {
            t.scene.removeReflectionProbe(a)
        }),
        this.environmentTexture === this.scene.environmentTexture && (this.scene.environmentTexture = null);
        for (var r = 0, n = this.scene._serializableComponents; r < n.length; r++) {
            var o = n[r];
            o.removeFromContainer(this)
        }
    }
    ,
    e.prototype.dispose = function() {
        this.cameras.slice(0).forEach(function(o) {
            o.dispose()
        }),
        this.cameras = [],
        this.lights.slice(0).forEach(function(o) {
            o.dispose()
        }),
        this.lights = [],
        this.meshes.slice(0).forEach(function(o) {
            o.dispose()
        }),
        this.meshes = [],
        this.skeletons.slice(0).forEach(function(o) {
            o.dispose()
        }),
        this.skeletons = [],
        this.animationGroups.slice(0).forEach(function(o) {
            o.dispose()
        }),
        this.animationGroups = [],
        this.multiMaterials.slice(0).forEach(function(o) {
            o.dispose()
        }),
        this.multiMaterials = [],
        this.materials.slice(0).forEach(function(o) {
            o.dispose()
        }),
        this.materials = [],
        this.geometries.slice(0).forEach(function(o) {
            o.dispose()
        }),
        this.geometries = [],
        this.transformNodes.slice(0).forEach(function(o) {
            o.dispose()
        }),
        this.transformNodes = [],
        this.actionManagers.slice(0).forEach(function(o) {
            o.dispose()
        }),
        this.actionManagers = [],
        this.textures.slice(0).forEach(function(o) {
            o.dispose()
        }),
        this.textures = [],
        this.reflectionProbes.slice(0).forEach(function(o) {
            o.dispose()
        }),
        this.reflectionProbes = [],
        this.environmentTexture && (this.environmentTexture.dispose(),
        this.environmentTexture = null);
        for (var t = 0, r = this.scene._serializableComponents; t < r.length; t++) {
            var n = r[t];
            n.removeFromContainer(this, !0)
        }
        this._onContextRestoredObserver && (this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),
        this._onContextRestoredObserver = null)
    }
    ,
    e.prototype._moveAssets = function(t, r, n) {
        if (!!t)
            for (var o = 0, a = t; o < a.length; o++) {
                var s = a[o]
                  , l = !0;
                if (n)
                    for (var u = 0, c = n; u < c.length; u++) {
                        var h = c[u];
                        if (s === h) {
                            l = !1;
                            break
                        }
                    }
                l && (r.push(s),
                s._parentContainer = this)
            }
    }
    ,
    e.prototype.moveAllFromScene = function(t) {
        this._wasAddedToScene = !1,
        t === void 0 && (t = new KeepAssets);
        for (var r in this)
            this.hasOwnProperty(r) && (this[r] = this[r] || (r === "environmentTexture" ? null : []),
            this._moveAssets(this.scene[r], this[r], t[r]));
        this.environmentTexture = this.scene.environmentTexture,
        this.removeAllFromScene()
    }
    ,
    e.prototype.createRootMesh = function() {
        var t = new Mesh("assetContainerRootMesh",this.scene);
        return this.meshes.forEach(function(r) {
            r.parent || t.addChild(r)
        }),
        this.meshes.unshift(t),
        t
    }
    ,
    e.prototype.mergeAnimationsTo = function(t, r, n) {
        if (t === void 0 && (t = EngineStore.LastCreatedScene),
        n === void 0 && (n = null),
        !t)
            return Logger$2.Error("No scene available to merge animations to"),
            [];
        var o = n || function(l) {
            var u = null
              , c = l.animations.length ? l.animations[0].targetProperty : ""
              , h = l.name.split(".").join("").split("_primitive")[0];
            switch (c) {
            case "position":
            case "rotationQuaternion":
                u = t.getTransformNodeByName(l.name) || t.getTransformNodeByName(h);
                break;
            case "influence":
                u = t.getMorphTargetByName(l.name) || t.getMorphTargetByName(h);
                break;
            default:
                u = t.getNodeByName(l.name) || t.getNodeByName(h)
            }
            return u
        }
          , a = this.getNodes();
        a.forEach(function(l) {
            var u = o(l);
            if (u !== null) {
                for (var c = function(_) {
                    for (var g = u.animations.filter(function(T) {
                        return T.targetProperty === _.targetProperty
                    }), m = 0, v = g; m < v.length; m++) {
                        var y = v[m]
                          , b = u.animations.indexOf(y, 0);
                        b > -1 && u.animations.splice(b, 1)
                    }
                }, h = 0, f = l.animations; h < f.length; h++) {
                    var d = f[h];
                    c(d)
                }
                u.animations = u.animations.concat(l.animations)
            }
        });
        var s = new Array;
        return this.animationGroups.slice().forEach(function(l) {
            s.push(l.clone(l.name, o)),
            l.animatables.forEach(function(u) {
                u.stop()
            })
        }),
        r.forEach(function(l) {
            var u = o(l.target);
            u && (t.beginAnimation(u, l.fromFrame, l.toFrame, l.loopAnimation, l.speedRatio, l.onAnimationEnd ? l.onAnimationEnd : void 0, void 0, !0, void 0, l.onAnimationLoop ? l.onAnimationLoop : void 0),
            t.stopAnimation(l.target))
        }),
        s
    }
    ,
    e
}(AbstractScene)
  , Sound = function() {
    function i(e, t, r, n, o) {
        var a = this;
        n === void 0 && (n = null);
        var s, l, u, c, h;
        if (this.autoplay = !1,
        this._loop = !1,
        this.useCustomAttenuation = !1,
        this.isPlaying = !1,
        this.isPaused = !1,
        this.spatialSound = !1,
        this.refDistance = 1,
        this.rolloffFactor = 1,
        this.maxDistance = 100,
        this.distanceModel = "linear",
        this.metadata = null,
        this.onEndedObservable = new Observable,
        this._panningModel = "equalpower",
        this._playbackRate = 1,
        this._streaming = !1,
        this._startTime = 0,
        this._startOffset = 0,
        this._position = Vector3.Zero(),
        this._localDirection = new Vector3(1,0,0),
        this._volume = 1,
        this._isReadyToPlay = !1,
        this._isDirectional = !1,
        this._coneInnerAngle = 360,
        this._coneOuterAngle = 360,
        this._coneOuterGain = 0,
        this._isOutputConnected = !1,
        this._urlType = "Unknown",
        this.name = e,
        this._scene = r,
        i._SceneComponentInitialization(r),
        this._readyToPlayCallback = n,
        this._customAttenuationFunction = function(v, y, b, T, C) {
            return y < b ? v * (1 - y / b) : 0
        }
        ,
        o && (this.autoplay = o.autoplay || !1,
        this._loop = o.loop || !1,
        o.volume !== void 0 && (this._volume = o.volume),
        this.spatialSound = (s = o.spatialSound) !== null && s !== void 0 ? s : !1,
        this.maxDistance = (l = o.maxDistance) !== null && l !== void 0 ? l : 100,
        this.useCustomAttenuation = (u = o.useCustomAttenuation) !== null && u !== void 0 ? u : !1,
        this.rolloffFactor = o.rolloffFactor || 1,
        this.refDistance = o.refDistance || 1,
        this.distanceModel = o.distanceModel || "linear",
        this._playbackRate = o.playbackRate || 1,
        this._streaming = (c = o.streaming) !== null && c !== void 0 ? c : !1,
        this._length = o.length,
        this._offset = o.offset),
        ((h = Engine.audioEngine) === null || h === void 0 ? void 0 : h.canUseWebAudio) && Engine.audioEngine.audioContext) {
            this._soundGain = Engine.audioEngine.audioContext.createGain(),
            this._soundGain.gain.value = this._volume,
            this._inputAudioNode = this._soundGain,
            this._outputAudioNode = this._soundGain,
            this.spatialSound && this._createSpatialParameters(),
            this._scene.mainSoundTrack.addSound(this);
            var f = !0;
            if (t)
                try {
                    typeof t == "string" ? this._urlType = "String" : t instanceof ArrayBuffer ? this._urlType = "ArrayBuffer" : t instanceof HTMLMediaElement ? this._urlType = "MediaElement" : t instanceof MediaStream ? this._urlType = "MediaStream" : Array.isArray(t) && (this._urlType = "Array");
                    var d = []
                      , _ = !1;
                    switch (this._urlType) {
                    case "MediaElement":
                        this._streaming = !0,
                        this._isReadyToPlay = !0,
                        this._streamingSource = Engine.audioEngine.audioContext.createMediaElementSource(t),
                        this.autoplay && this.play(0, this._offset, this._length),
                        this._readyToPlayCallback && this._readyToPlayCallback();
                        break;
                    case "MediaStream":
                        this._streaming = !0,
                        this._isReadyToPlay = !0,
                        this._streamingSource = Engine.audioEngine.audioContext.createMediaStreamSource(t),
                        this.autoplay && this.play(0, this._offset, this._length),
                        this._readyToPlayCallback && this._readyToPlayCallback();
                        break;
                    case "ArrayBuffer":
                        t.byteLength > 0 && (_ = !0,
                        this._soundLoaded(t));
                        break;
                    case "String":
                        d.push(t);
                    case "Array":
                        d.length === 0 && (d = t);
                        for (var g = 0; g < d.length; g++) {
                            var m = d[g];
                            if (_ = o && o.skipCodecCheck || m.indexOf(".mp3", m.length - 4) !== -1 && Engine.audioEngine.isMP3supported || m.indexOf(".ogg", m.length - 4) !== -1 && Engine.audioEngine.isOGGsupported || m.indexOf(".wav", m.length - 4) !== -1 || m.indexOf(".m4a", m.length - 4) !== -1 || m.indexOf("blob:") !== -1,
                            _) {
                                this._streaming ? (this._htmlAudioElement = new Audio(m),
                                this._htmlAudioElement.controls = !1,
                                this._htmlAudioElement.loop = this.loop,
                                Tools.SetCorsBehavior(m, this._htmlAudioElement),
                                this._htmlAudioElement.preload = "auto",
                                this._htmlAudioElement.addEventListener("canplaythrough", function() {
                                    a._isReadyToPlay = !0,
                                    a.autoplay && a.play(0, a._offset, a._length),
                                    a._readyToPlayCallback && a._readyToPlayCallback()
                                }),
                                document.body.appendChild(this._htmlAudioElement),
                                this._htmlAudioElement.load()) : this._scene._loadFile(m, function(v) {
                                    a._soundLoaded(v)
                                }, void 0, !0, !0, function(v) {
                                    v && Logger$2.Error("XHR " + v.status + " error on: " + m + "."),
                                    Logger$2.Error("Sound creation aborted."),
                                    a._scene.mainSoundTrack.removeSound(a)
                                });
                                break
                            }
                        }
                        break;
                    default:
                        f = !1;
                        break
                    }
                    f ? _ || (this._isReadyToPlay = !0,
                    this._readyToPlayCallback && window.setTimeout(function() {
                        a._readyToPlayCallback && a._readyToPlayCallback()
                    }, 1e3)) : Logger$2.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.")
                } catch {
                    Logger$2.Error("Unexpected error. Sound creation aborted."),
                    this._scene.mainSoundTrack.removeSound(this)
                }
        } else
            this._scene.mainSoundTrack.addSound(this),
            Engine.audioEngine && !Engine.audioEngine.WarnedWebAudioUnsupported && (Logger$2.Error("Web Audio is not supported by your browser."),
            Engine.audioEngine.WarnedWebAudioUnsupported = !0),
            this._readyToPlayCallback && window.setTimeout(function() {
                a._readyToPlayCallback && a._readyToPlayCallback()
            }, 1e3)
    }
    return Object.defineProperty(i.prototype, "loop", {
        get: function() {
            return this._loop
        },
        set: function(e) {
            e !== this._loop && (this._loop = e,
            this.updateOptions({
                loop: e
            }))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "currentTime", {
        get: function() {
            var e;
            if (this._htmlAudioElement)
                return this._htmlAudioElement.currentTime;
            var t = this._startOffset;
            return this.isPlaying && ((e = Engine.audioEngine) === null || e === void 0 ? void 0 : e.audioContext) && (t += Engine.audioEngine.audioContext.currentTime - this._startTime),
            t
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.dispose = function() {
        var e;
        !((e = Engine.audioEngine) === null || e === void 0) && e.canUseWebAudio && (this.isPlaying && this.stop(),
        this._isReadyToPlay = !1,
        this.soundTrackId === -1 ? this._scene.mainSoundTrack.removeSound(this) : this._scene.soundTracks && this._scene.soundTracks[this.soundTrackId].removeSound(this),
        this._soundGain && (this._soundGain.disconnect(),
        this._soundGain = null),
        this._soundPanner && (this._soundPanner.disconnect(),
        this._soundPanner = null),
        this._soundSource && (this._soundSource.disconnect(),
        this._soundSource = null),
        this._audioBuffer = null,
        this._htmlAudioElement && (this._htmlAudioElement.pause(),
        this._htmlAudioElement.src = "",
        document.body.removeChild(this._htmlAudioElement)),
        this._streamingSource && this._streamingSource.disconnect(),
        this._connectedTransformNode && this._registerFunc && (this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),
        this._connectedTransformNode = null))
    }
    ,
    i.prototype.isReady = function() {
        return this._isReadyToPlay
    }
    ,
    i.prototype.getClassName = function() {
        return "Sound"
    }
    ,
    i.prototype._soundLoaded = function(e) {
        var t = this, r;
        !(!((r = Engine.audioEngine) === null || r === void 0) && r.audioContext) || Engine.audioEngine.audioContext.decodeAudioData(e, function(n) {
            t._audioBuffer = n,
            t._isReadyToPlay = !0,
            t.autoplay && t.play(0, t._offset, t._length),
            t._readyToPlayCallback && t._readyToPlayCallback()
        }, function(n) {
            Logger$2.Error("Error while decoding audio data for: " + t.name + " / Error: " + n)
        })
    }
    ,
    i.prototype.setAudioBuffer = function(e) {
        var t;
        !((t = Engine.audioEngine) === null || t === void 0) && t.canUseWebAudio && (this._audioBuffer = e,
        this._isReadyToPlay = !0)
    }
    ,
    i.prototype.updateOptions = function(e) {
        var t, r, n, o, a, s, l, u, c;
        e && (this.loop = (t = e.loop) !== null && t !== void 0 ? t : this.loop,
        this.maxDistance = (r = e.maxDistance) !== null && r !== void 0 ? r : this.maxDistance,
        this.useCustomAttenuation = (n = e.useCustomAttenuation) !== null && n !== void 0 ? n : this.useCustomAttenuation,
        this.rolloffFactor = (o = e.rolloffFactor) !== null && o !== void 0 ? o : this.rolloffFactor,
        this.refDistance = (a = e.refDistance) !== null && a !== void 0 ? a : this.refDistance,
        this.distanceModel = (s = e.distanceModel) !== null && s !== void 0 ? s : this.distanceModel,
        this._playbackRate = (l = e.playbackRate) !== null && l !== void 0 ? l : this._playbackRate,
        this._length = (u = e.length) !== null && u !== void 0 ? u : void 0,
        this._offset = (c = e.offset) !== null && c !== void 0 ? c : void 0,
        this._updateSpatialParameters(),
        this.isPlaying && (this._streaming && this._htmlAudioElement ? (this._htmlAudioElement.playbackRate = this._playbackRate,
        this._htmlAudioElement.loop !== this.loop && (this._htmlAudioElement.loop = this.loop)) : this._soundSource && (this._soundSource.playbackRate.value = this._playbackRate,
        this._soundSource.loop !== this.loop && (this._soundSource.loop = this.loop),
        this._offset !== void 0 && this._soundSource.loopStart !== this._offset && (this._soundSource.loopStart = this._offset),
        this._length !== void 0 && this._length !== this._soundSource.loopEnd && (this._soundSource.loopEnd = (this._offset | 0) + this._length))))
    }
    ,
    i.prototype._createSpatialParameters = function() {
        var e;
        ((e = Engine.audioEngine) === null || e === void 0 ? void 0 : e.canUseWebAudio) && Engine.audioEngine.audioContext && (this._scene.headphone && (this._panningModel = "HRTF"),
        this._soundPanner = Engine.audioEngine.audioContext.createPanner(),
        this._soundPanner && this._outputAudioNode && (this._updateSpatialParameters(),
        this._soundPanner.connect(this._outputAudioNode),
        this._inputAudioNode = this._soundPanner))
    }
    ,
    i.prototype._updateSpatialParameters = function() {
        this.spatialSound && this._soundPanner && (this.useCustomAttenuation ? (this._soundPanner.distanceModel = "linear",
        this._soundPanner.maxDistance = Number.MAX_VALUE,
        this._soundPanner.refDistance = 1,
        this._soundPanner.rolloffFactor = 1,
        this._soundPanner.panningModel = this._panningModel) : (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))
    }
    ,
    i.prototype.switchPanningModelToHRTF = function() {
        this._panningModel = "HRTF",
        this._switchPanningModel()
    }
    ,
    i.prototype.switchPanningModelToEqualPower = function() {
        this._panningModel = "equalpower",
        this._switchPanningModel()
    }
    ,
    i.prototype._switchPanningModel = function() {
        var e;
        ((e = Engine.audioEngine) === null || e === void 0 ? void 0 : e.canUseWebAudio) && this.spatialSound && this._soundPanner && (this._soundPanner.panningModel = this._panningModel)
    }
    ,
    i.prototype.connectToSoundTrackAudioNode = function(e) {
        var t;
        ((t = Engine.audioEngine) === null || t === void 0 ? void 0 : t.canUseWebAudio) && this._outputAudioNode && (this._isOutputConnected && this._outputAudioNode.disconnect(),
        this._outputAudioNode.connect(e),
        this._isOutputConnected = !0)
    }
    ,
    i.prototype.setDirectionalCone = function(e, t, r) {
        if (t < e) {
            Logger$2.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
            return
        }
        this._coneInnerAngle = e,
        this._coneOuterAngle = t,
        this._coneOuterGain = r,
        this._isDirectional = !0,
        this.isPlaying && this.loop && (this.stop(),
        this.play(0, this._offset, this._length))
    }
    ,
    Object.defineProperty(i.prototype, "directionalConeInnerAngle", {
        get: function() {
            return this._coneInnerAngle
        },
        set: function(e) {
            var t;
            if (e != this._coneInnerAngle) {
                if (this._coneOuterAngle < e) {
                    Logger$2.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
                    return
                }
                this._coneInnerAngle = e,
                ((t = Engine.audioEngine) === null || t === void 0 ? void 0 : t.canUseWebAudio) && this.spatialSound && this._soundPanner && (this._soundPanner.coneInnerAngle = this._coneInnerAngle)
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "directionalConeOuterAngle", {
        get: function() {
            return this._coneOuterAngle
        },
        set: function(e) {
            var t;
            if (e != this._coneOuterAngle) {
                if (e < this._coneInnerAngle) {
                    Logger$2.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
                    return
                }
                this._coneOuterAngle = e,
                ((t = Engine.audioEngine) === null || t === void 0 ? void 0 : t.canUseWebAudio) && this.spatialSound && this._soundPanner && (this._soundPanner.coneOuterAngle = this._coneOuterAngle)
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.setPosition = function(e) {
        var t;
        e.equals(this._position) || (this._position.copyFrom(e),
        ((t = Engine.audioEngine) === null || t === void 0 ? void 0 : t.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))
    }
    ,
    i.prototype.setLocalDirectionToMesh = function(e) {
        var t;
        this._localDirection = e,
        ((t = Engine.audioEngine) === null || t === void 0 ? void 0 : t.canUseWebAudio) && this._connectedTransformNode && this.isPlaying && this._updateDirection()
    }
    ,
    i.prototype._updateDirection = function() {
        if (!(!this._connectedTransformNode || !this._soundPanner)) {
            var e = this._connectedTransformNode.getWorldMatrix()
              , t = Vector3.TransformNormal(this._localDirection, e);
            t.normalize(),
            this._soundPanner.setOrientation(t.x, t.y, t.z)
        }
    }
    ,
    i.prototype.updateDistanceFromListener = function() {
        var e;
        if (((e = Engine.audioEngine) === null || e === void 0 ? void 0 : e.canUseWebAudio) && this._connectedTransformNode && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
            var t = this._connectedTransformNode.getDistanceToCamera(this._scene.activeCamera);
            this._soundGain.gain.value = this._customAttenuationFunction(this._volume, t, this.maxDistance, this.refDistance, this.rolloffFactor)
        }
    }
    ,
    i.prototype.setAttenuationFunction = function(e) {
        this._customAttenuationFunction = e
    }
    ,
    i.prototype.play = function(e, t, r) {
        var n = this, o, a, s, l;
        if (this._isReadyToPlay && this._scene.audioEnabled && ((o = Engine.audioEngine) === null || o === void 0 ? void 0 : o.audioContext))
            try {
                this._startOffset < 0 && (e = -this._startOffset,
                this._startOffset = 0);
                var u = e ? ((a = Engine.audioEngine) === null || a === void 0 ? void 0 : a.audioContext.currentTime) + e : (s = Engine.audioEngine) === null || s === void 0 ? void 0 : s.audioContext.currentTime;
                if ((!this._soundSource || !this._streamingSource) && 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),
                this._isDirectional && (this._soundPanner.coneInnerAngle = this._coneInnerAngle,
                this._soundPanner.coneOuterAngle = this._coneOuterAngle,
                this._soundPanner.coneOuterGain = this._coneOuterGain,
                this._connectedTransformNode ? this._updateDirection() : this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z))),
                this._streaming) {
                    if (this._streamingSource || (this._streamingSource = Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement),
                    this._htmlAudioElement.onended = function() {
                        n._onended()
                    }
                    ,
                    this._htmlAudioElement.playbackRate = this._playbackRate),
                    this._streamingSource.disconnect(),
                    this._inputAudioNode && this._streamingSource.connect(this._inputAudioNode),
                    this._htmlAudioElement) {
                        var c = function() {
                            var h, f;
                            if (!((h = Engine.audioEngine) === null || h === void 0) && h.unlocked) {
                                var d = n._htmlAudioElement.play();
                                d !== void 0 && d.catch(function(_) {
                                    var g, m;
                                    (g = Engine.audioEngine) === null || g === void 0 || g.lock(),
                                    (n.loop || n.autoplay) && ((m = Engine.audioEngine) === null || m === void 0 || m.onAudioUnlockedObservable.addOnce(function() {
                                        c()
                                    }))
                                })
                            } else
                                (n.loop || n.autoplay) && ((f = Engine.audioEngine) === null || f === void 0 || f.onAudioUnlockedObservable.addOnce(function() {
                                    c()
                                }))
                        };
                        c()
                    }
                } else {
                    var c = function() {
                        var f, d, _;
                        if (!((f = Engine.audioEngine) === null || f === void 0) && f.audioContext) {
                            if (r = r || n._length,
                            t = t || n._offset,
                            n._soundSource) {
                                var g = n._soundSource;
                                g.onended = function() {
                                    g.disconnect()
                                }
                            }
                            if (n._soundSource = (d = Engine.audioEngine) === null || d === void 0 ? void 0 : d.audioContext.createBufferSource(),
                            n._soundSource && n._inputAudioNode) {
                                n._soundSource.buffer = n._audioBuffer,
                                n._soundSource.connect(n._inputAudioNode),
                                n._soundSource.loop = n.loop,
                                t !== void 0 && (n._soundSource.loopStart = t),
                                r !== void 0 && (n._soundSource.loopEnd = (t | 0) + r),
                                n._soundSource.playbackRate.value = n._playbackRate,
                                n._soundSource.onended = function() {
                                    n._onended()
                                }
                                ,
                                u = e ? ((_ = Engine.audioEngine) === null || _ === void 0 ? void 0 : _.audioContext.currentTime) + e : Engine.audioEngine.audioContext.currentTime;
                                var m = n.isPaused ? n._startOffset % n._soundSource.buffer.duration : t || 0;
                                n._soundSource.start(u, m, n.loop ? void 0 : r)
                            }
                        }
                    };
                    ((l = Engine.audioEngine) === null || l === void 0 ? void 0 : l.audioContext.state) === "suspended" ? setTimeout(function() {
                        var f;
                        ((f = Engine.audioEngine) === null || f === void 0 ? void 0 : f.audioContext.state) === "suspended" ? (Engine.audioEngine.lock(),
                        (n.loop || n.autoplay) && Engine.audioEngine.onAudioUnlockedObservable.addOnce(function() {
                            c()
                        })) : c()
                    }, 500) : c()
                }
                this._startTime = u,
                this.isPlaying = !0,
                this.isPaused = !1
            } catch (h) {
                Logger$2.Error("Error while trying to play audio: " + this.name + ", " + h.message)
            }
    }
    ,
    i.prototype._onended = function() {
        this.isPlaying = !1,
        this._startOffset = 0,
        this.onended && this.onended(),
        this.onEndedObservable.notifyObservers(this)
    }
    ,
    i.prototype.stop = function(e) {
        var t = this, r;
        if (this.isPlaying) {
            if (this._streaming)
                this._htmlAudioElement ? (this._htmlAudioElement.pause(),
                this._htmlAudioElement.currentTime > 0 && (this._htmlAudioElement.currentTime = 0)) : this._streamingSource.disconnect(),
                this.isPlaying = !1;
            else if (((r = Engine.audioEngine) === null || r === void 0 ? void 0 : r.audioContext) && this._soundSource) {
                var n = e ? Engine.audioEngine.audioContext.currentTime + e : void 0;
                this._soundSource.stop(n),
                n === void 0 ? (this.isPlaying = !1,
                this._soundSource.onended = function() {}
                ) : this._soundSource.onended = function() {
                    t.isPlaying = !1
                }
                ,
                this.isPaused || (this._startOffset = 0)
            }
        }
    }
    ,
    i.prototype.pause = function() {
        var e;
        this.isPlaying && (this.isPaused = !0,
        this._streaming ? (this._htmlAudioElement ? this._htmlAudioElement.pause() : this._streamingSource.disconnect(),
        this.isPlaying = !1) : !((e = Engine.audioEngine) === null || e === void 0) && e.audioContext && (this.stop(0),
        this._startOffset += Engine.audioEngine.audioContext.currentTime - this._startTime))
    }
    ,
    i.prototype.setVolume = function(e, t) {
        var r;
        ((r = Engine.audioEngine) === null || r === void 0 ? void 0 : r.canUseWebAudio) && this._soundGain && (t && Engine.audioEngine.audioContext ? (this._soundGain.gain.cancelScheduledValues(Engine.audioEngine.audioContext.currentTime),
        this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, Engine.audioEngine.audioContext.currentTime),
        this._soundGain.gain.linearRampToValueAtTime(e, Engine.audioEngine.audioContext.currentTime + t)) : this._soundGain.gain.value = e),
        this._volume = e
    }
    ,
    i.prototype.setPlaybackRate = function(e) {
        this._playbackRate = e,
        this.isPlaying && (this._streaming && this._htmlAudioElement ? this._htmlAudioElement.playbackRate = this._playbackRate : this._soundSource && (this._soundSource.playbackRate.value = this._playbackRate))
    }
    ,
    i.prototype.getVolume = function() {
        return this._volume
    }
    ,
    i.prototype.attachToMesh = function(e) {
        var t = this;
        this._connectedTransformNode && this._registerFunc && (this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),
        this._registerFunc = null),
        this._connectedTransformNode = e,
        this.spatialSound || (this.spatialSound = !0,
        this._createSpatialParameters(),
        this.isPlaying && this.loop && (this.stop(),
        this.play(0, this._offset, this._length))),
        this._onRegisterAfterWorldMatrixUpdate(this._connectedTransformNode),
        this._registerFunc = function(r) {
            return t._onRegisterAfterWorldMatrixUpdate(r)
        }
        ,
        this._connectedTransformNode.registerAfterWorldMatrixUpdate(this._registerFunc)
    }
    ,
    i.prototype.detachFromMesh = function() {
        this._connectedTransformNode && this._registerFunc && (this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),
        this._registerFunc = null,
        this._connectedTransformNode = null)
    }
    ,
    i.prototype._onRegisterAfterWorldMatrixUpdate = function(e) {
        var t;
        if (!e.getBoundingInfo)
            this.setPosition(e.absolutePosition);
        else {
            var r = e
              , n = r.getBoundingInfo();
            this.setPosition(n.boundingSphere.centerWorld)
        }
        ((t = Engine.audioEngine) === null || t === void 0 ? void 0 : t.canUseWebAudio) && this._isDirectional && this.isPlaying && this._updateDirection()
    }
    ,
    i.prototype.clone = function() {
        var e = this;
        if (this._streaming)
            return null;
        var t = function() {
            e._isReadyToPlay ? (n._audioBuffer = e.getAudioBuffer(),
            n._isReadyToPlay = !0,
            n.autoplay && n.play(0, e._offset, e._length)) : window.setTimeout(t, 300)
        }
          , r = {
            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
        }
          , n = new i(this.name + "_cloned",new ArrayBuffer(0),this._scene,null,r);
        return this.useCustomAttenuation && n.setAttenuationFunction(this._customAttenuationFunction),
        n.setPosition(this._position),
        n.setPlaybackRate(this._playbackRate),
        t(),
        n
    }
    ,
    i.prototype.getAudioBuffer = function() {
        return this._audioBuffer
    }
    ,
    i.prototype.getSoundSource = function() {
        return this._soundSource
    }
    ,
    i.prototype.getSoundGain = function() {
        return this._soundGain
    }
    ,
    i.prototype.serialize = function() {
        var e = {
            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,
            metadata: this.metadata
        };
        return this.spatialSound && (this._connectedTransformNode && (e.connectedMeshId = this._connectedTransformNode.id),
        e.position = this._position.asArray(),
        e.refDistance = this.refDistance,
        e.distanceModel = this.distanceModel,
        e.isDirectional = this._isDirectional,
        e.localDirectionToMesh = this._localDirection.asArray(),
        e.coneInnerAngle = this._coneInnerAngle,
        e.coneOuterAngle = this._coneOuterAngle,
        e.coneOuterGain = this._coneOuterGain),
        e
    }
    ,
    i.Parse = function(e, t, r, n) {
        var o = e.name, a;
        e.url ? a = r + e.url : a = r + o;
        var s = {
            autoplay: e.autoplay,
            loop: e.loop,
            volume: e.volume,
            spatialSound: e.spatialSound,
            maxDistance: e.maxDistance,
            rolloffFactor: e.rolloffFactor,
            refDistance: e.refDistance,
            distanceModel: e.distanceModel,
            playbackRate: e.playbackRate
        }, l;
        if (!n)
            l = new i(o,a,t,function() {
                t._removePendingData(l)
            }
            ,s),
            t._addPendingData(l);
        else {
            var u = function() {
                n._isReadyToPlay ? (l._audioBuffer = n.getAudioBuffer(),
                l._isReadyToPlay = !0,
                l.autoplay && l.play(0, l._offset, l._length)) : window.setTimeout(u, 300)
            };
            l = new i(o,new ArrayBuffer(0),t,null,s),
            u()
        }
        if (e.position) {
            var c = Vector3.FromArray(e.position);
            l.setPosition(c)
        }
        if (e.isDirectional && (l.setDirectionalCone(e.coneInnerAngle || 360, e.coneOuterAngle || 360, e.coneOuterGain || 0),
        e.localDirectionToMesh)) {
            var h = Vector3.FromArray(e.localDirectionToMesh);
            l.setLocalDirectionToMesh(h)
        }
        if (e.connectedMeshId) {
            var f = t.getMeshById(e.connectedMeshId);
            f && l.attachToMesh(f)
        }
        return e.metadata && (l.metadata = e.metadata),
        l
    }
    ,
    i._SceneComponentInitialization = function(e) {
        throw _WarnImport("AudioSceneComponent")
    }
    ,
    i
}()
  , ThinSprite = function() {
    function i() {
        this.width = 1,
        this.height = 1,
        this.angle = 0,
        this.invertU = !1,
        this.invertV = !1,
        this.isVisible = !0,
        this._animationStarted = !1,
        this._loopAnimation = !1,
        this._fromIndex = 0,
        this._toIndex = 0,
        this._delay = 0,
        this._direction = 1,
        this._time = 0,
        this._onBaseAnimationEnd = null,
        this.position = {
            x: 1,
            y: 1,
            z: 1
        },
        this.color = {
            r: 1,
            g: 1,
            b: 1,
            a: 1
        }
    }
    return Object.defineProperty(i.prototype, "animationStarted", {
        get: function() {
            return this._animationStarted
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "fromIndex", {
        get: function() {
            return this._fromIndex
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "toIndex", {
        get: function() {
            return this._toIndex
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "loopAnimation", {
        get: function() {
            return this._loopAnimation
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "delay", {
        get: function() {
            return Math.max(this._delay, 1)
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.playAnimation = function(e, t, r, n, o) {
        this._fromIndex = e,
        this._toIndex = t,
        this._loopAnimation = r,
        this._delay = n || 1,
        this._animationStarted = !0,
        this._onBaseAnimationEnd = o,
        e < t ? this._direction = 1 : (this._direction = -1,
        this._toIndex = e,
        this._fromIndex = t),
        this.cellIndex = e,
        this._time = 0
    }
    ,
    i.prototype.stopAnimation = function() {
        this._animationStarted = !1
    }
    ,
    i.prototype._animate = function(e) {
        !this._animationStarted || (this._time += e,
        this._time > this._delay && (this._time = this._time % this._delay,
        this.cellIndex += this._direction,
        (this._direction > 0 && this.cellIndex > this._toIndex || this._direction < 0 && this.cellIndex < this._fromIndex) && (this._loopAnimation ? this.cellIndex = this._direction > 0 ? this._fromIndex : this._toIndex : (this.cellIndex = this._toIndex,
        this._animationStarted = !1,
        this._onBaseAnimationEnd && this._onBaseAnimationEnd()))))
    }
    ,
    i
}()
  , Sprite = function(i) {
    __extends(e, i);
    function e(t, r) {
        var n = i.call(this) || this;
        return n.name = t,
        n.animations = new Array,
        n.isPickable = !1,
        n.useAlphaForPicking = !1,
        n.onDisposeObservable = new Observable,
        n._onAnimationEnd = null,
        n._endAnimation = function() {
            n._onAnimationEnd && n._onAnimationEnd(),
            n.disposeWhenFinishedAnimating && n.dispose()
        }
        ,
        n.color = new Color4(1,1,1,1),
        n.position = Vector3.Zero(),
        n._manager = r,
        n._manager.sprites.push(n),
        n.uniqueId = n._manager.scene.getUniqueId(),
        n
    }
    return Object.defineProperty(e.prototype, "size", {
        get: function() {
            return this.width
        },
        set: function(t) {
            this.width = t,
            this.height = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "manager", {
        get: function() {
            return this._manager
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getClassName = function() {
        return "Sprite"
    }
    ,
    Object.defineProperty(e.prototype, "fromIndex", {
        get: function() {
            return this._fromIndex
        },
        set: function(t) {
            this.playAnimation(t, this._toIndex, this._loopAnimation, this._delay, this._onAnimationEnd)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "toIndex", {
        get: function() {
            return this._toIndex
        },
        set: function(t) {
            this.playAnimation(this._fromIndex, t, this._loopAnimation, this._delay, this._onAnimationEnd)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "loopAnimation", {
        get: function() {
            return this._loopAnimation
        },
        set: function(t) {
            this.playAnimation(this._fromIndex, this._toIndex, t, this._delay, this._onAnimationEnd)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "delay", {
        get: function() {
            return Math.max(this._delay, 1)
        },
        set: function(t) {
            this.playAnimation(this._fromIndex, this._toIndex, this._loopAnimation, t, this._onAnimationEnd)
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.playAnimation = function(t, r, n, o, a) {
        a === void 0 && (a = null),
        this._onAnimationEnd = a,
        i.prototype.playAnimation.call(this, t, r, n, o, this._endAnimation)
    }
    ,
    e.prototype.dispose = function() {
        for (var t = 0; t < this._manager.sprites.length; t++)
            this._manager.sprites[t] == this && this._manager.sprites.splice(t, 1);
        this.onDisposeObservable.notifyObservers(this),
        this.onDisposeObservable.clear()
    }
    ,
    e.prototype.serialize = function() {
        var t = {};
        return t.name = this.name,
        t.position = this.position.asArray(),
        t.color = this.color.asArray(),
        t.width = this.width,
        t.height = this.height,
        t.angle = this.angle,
        t.cellIndex = this.cellIndex,
        t.cellRef = this.cellRef,
        t.invertU = this.invertU,
        t.invertV = this.invertV,
        t.disposeWhenFinishedAnimating = this.disposeWhenFinishedAnimating,
        t.isPickable = this.isPickable,
        t.isVisible = this.isVisible,
        t.useAlphaForPicking = this.useAlphaForPicking,
        t.animationStarted = this.animationStarted,
        t.fromIndex = this.fromIndex,
        t.toIndex = this.toIndex,
        t.loopAnimation = this.loopAnimation,
        t.delay = this.delay,
        t
    }
    ,
    e.Parse = function(t, r) {
        var n = new e(t.name,r);
        return n.position = Vector3.FromArray(t.position),
        n.color = Color4.FromArray(t.color),
        n.width = t.width,
        n.height = t.height,
        n.angle = t.angle,
        n.cellIndex = t.cellIndex,
        n.cellRef = t.cellRef,
        n.invertU = t.invertU,
        n.invertV = t.invertV,
        n.disposeWhenFinishedAnimating = t.disposeWhenFinishedAnimating,
        n.isPickable = t.isPickable,
        n.isVisible = t.isVisible,
        n.useAlphaForPicking = t.useAlphaForPicking,
        n.fromIndex = t.fromIndex,
        n.toIndex = t.toIndex,
        n.loopAnimation = t.loopAnimation,
        n.delay = t.delay,
        t.animationStarted && n.playAnimation(n.fromIndex, n.toIndex, n.loopAnimation, n.delay),
        n
    }
    ,
    e
}(ThinSprite);
Scene.prototype._internalPickSprites = function(i, e, t, r) {
    if (!PickingInfo)
        return null;
    var n = null;
    if (!r) {
        if (!this.activeCamera)
            return null;
        r = this.activeCamera
    }
    if (this.spriteManagers.length > 0)
        for (var o = 0; o < this.spriteManagers.length; o++) {
            var a = this.spriteManagers[o];
            if (!!a.isPickable) {
                var s = a.intersects(i, r, e, t);
                if (!(!s || !s.hit) && !(!t && n != null && s.distance >= n.distance) && (n = s,
                t))
                    break
            }
        }
    return n || new PickingInfo
}
;
Scene.prototype._internalMultiPickSprites = function(i, e, t) {
    if (!PickingInfo)
        return null;
    var r = new Array;
    if (!t) {
        if (!this.activeCamera)
            return null;
        t = this.activeCamera
    }
    if (this.spriteManagers.length > 0)
        for (var n = 0; n < this.spriteManagers.length; n++) {
            var o = this.spriteManagers[n];
            if (!!o.isPickable) {
                var a = o.multiIntersects(i, t, e);
                a !== null && (r = r.concat(a))
            }
        }
    return r
}
;
Scene.prototype.pickSprite = function(i, e, t, r, n) {
    if (!this._tempSpritePickingRay)
        return null;
    this.createPickingRayInCameraSpaceToRef(i, e, this._tempSpritePickingRay, n);
    var o = this._internalPickSprites(this._tempSpritePickingRay, t, r, n);
    return o && (o.ray = this.createPickingRayInCameraSpace(i, e, n)),
    o
}
;
Scene.prototype.pickSpriteWithRay = function(i, e, t, r) {
    if (!this._tempSpritePickingRay)
        return null;
    if (!r) {
        if (!this.activeCamera)
            return null;
        r = this.activeCamera
    }
    Ray.TransformToRef(i, r.getViewMatrix(), this._tempSpritePickingRay);
    var n = this._internalPickSprites(this._tempSpritePickingRay, e, t, r);
    return n && (n.ray = i),
    n
}
;
Scene.prototype.multiPickSprite = function(i, e, t, r) {
    return this.createPickingRayInCameraSpaceToRef(i, e, this._tempSpritePickingRay, r),
    this._internalMultiPickSprites(this._tempSpritePickingRay, t, r)
}
;
Scene.prototype.multiPickSpriteWithRay = function(i, e, t) {
    if (!this._tempSpritePickingRay)
        return null;
    if (!t) {
        if (!this.activeCamera)
            return null;
        t = this.activeCamera
    }
    return Ray.TransformToRef(i, t.getViewMatrix(), this._tempSpritePickingRay),
    this._internalMultiPickSprites(this._tempSpritePickingRay, e, t)
}
;
Scene.prototype.setPointerOverSprite = function(i) {
    this._pointerOverSprite !== i && (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.processTrigger(10, ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this)),
    this._pointerOverSprite = i,
    this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.processTrigger(9, ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this)))
}
;
Scene.prototype.getPointerOverSprite = function() {
    return this._pointerOverSprite
}
;
var SpriteSceneComponent = function() {
    function i(e) {
        this.name = SceneComponentConstants.NAME_SPRITE,
        this.scene = e,
        this.scene.spriteManagers = new Array,
        this.scene._tempSpritePickingRay = Ray ? Ray.Zero() : null,
        this.scene.onBeforeSpritesRenderingObservable = new Observable,
        this.scene.onAfterSpritesRenderingObservable = new Observable,
        this._spritePredicate = function(t) {
            return t.actionManager ? t.isPickable && t.actionManager.hasPointerTriggers : !1
        }
    }
    return i.prototype.register = function() {
        this.scene._pointerMoveStage.registerStep(SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove),
        this.scene._pointerDownStage.registerStep(SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown),
        this.scene._pointerUpStage.registerStep(SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp)
    }
    ,
    i.prototype.rebuild = function() {}
    ,
    i.prototype.dispose = function() {
        this.scene.onBeforeSpritesRenderingObservable.clear(),
        this.scene.onAfterSpritesRenderingObservable.clear();
        for (var e = this.scene.spriteManagers; e.length; )
            e[0].dispose()
    }
    ,
    i.prototype._pickSpriteButKeepRay = function(e, t, r, n, o) {
        var a = this.scene.pickSprite(t, r, this._spritePredicate, n, o);
        return a && (a.ray = e ? e.ray : null),
        a
    }
    ,
    i.prototype._pointerMove = function(e, t, r, n, o) {
        var a = this.scene;
        return n ? a.setPointerOverSprite(null) : (r = this._pickSpriteButKeepRay(r, e, t, !1, a.cameraToUseForPointers || void 0),
        r && r.hit && r.pickedSprite ? (a.setPointerOverSprite(r.pickedSprite),
        !a.doNotHandleCursors && o && (a._pointerOverSprite && a._pointerOverSprite.actionManager && a._pointerOverSprite.actionManager.hoverCursor ? o.style.cursor = a._pointerOverSprite.actionManager.hoverCursor : o.style.cursor = a.hoverCursor)) : a.setPointerOverSprite(null)),
        r
    }
    ,
    i.prototype._pointerDown = function(e, t, r, n) {
        var o = this.scene;
        if (o._pickedDownSprite = null,
        o.spriteManagers.length > 0 && (r = o.pickSprite(e, t, this._spritePredicate, !1, o.cameraToUseForPointers || void 0),
        r && r.hit && r.pickedSprite && r.pickedSprite.actionManager)) {
            switch (o._pickedDownSprite = r.pickedSprite,
            n.button) {
            case 0:
                r.pickedSprite.actionManager.processTrigger(2, ActionEvent.CreateNewFromSprite(r.pickedSprite, o, n));
                break;
            case 1:
                r.pickedSprite.actionManager.processTrigger(4, ActionEvent.CreateNewFromSprite(r.pickedSprite, o, n));
                break;
            case 2:
                r.pickedSprite.actionManager.processTrigger(3, ActionEvent.CreateNewFromSprite(r.pickedSprite, o, n));
                break
            }
            r.pickedSprite.actionManager && r.pickedSprite.actionManager.processTrigger(5, ActionEvent.CreateNewFromSprite(r.pickedSprite, o, n))
        }
        return r
    }
    ,
    i.prototype._pointerUp = function(e, t, r, n) {
        var o = this.scene;
        if (o.spriteManagers.length > 0) {
            var a = o.pickSprite(e, t, this._spritePredicate, !1, o.cameraToUseForPointers || void 0);
            a && (a.hit && a.pickedSprite && a.pickedSprite.actionManager && (a.pickedSprite.actionManager.processTrigger(7, ActionEvent.CreateNewFromSprite(a.pickedSprite, o, n)),
            a.pickedSprite.actionManager && (this.scene._inputManager._isPointerSwiping() || a.pickedSprite.actionManager.processTrigger(1, ActionEvent.CreateNewFromSprite(a.pickedSprite, o, n)))),
            o._pickedDownSprite && o._pickedDownSprite.actionManager && o._pickedDownSprite !== a.pickedSprite && o._pickedDownSprite.actionManager.processTrigger(16, ActionEvent.CreateNewFromSprite(o._pickedDownSprite, o, n)))
        }
        return r
    }
    ,
    i
}()
  , name$D = "spritesPixelShader"
  , shader$D = `uniform bool alphaTest;
varying vec4 vColor;

varying vec2 vUV;
uniform sampler2D diffuseSampler;

#include<fogFragmentDeclaration>
void main(void) {
vec4 color=texture2D(diffuseSampler,vUV);
if (alphaTest)
{
if (color.a<0.95)
discard;
}
color*=vColor;
#include<fogFragment>
gl_FragColor=color;
#include<imageProcessingCompatibility>
}`;
ShaderStore.ShadersStore[name$D] = shader$D;
var name$C = "spritesVertexShader"
  , shader$C = `
attribute vec4 position;
attribute vec2 options;
attribute vec2 offsets;
attribute vec2 inverts;
attribute vec4 cellInfo;
attribute vec4 color;

uniform mat4 view;
uniform mat4 projection;

varying vec2 vUV;
varying vec4 vColor;
#include<fogVertexDeclaration>
void main(void) {
vec3 viewPos=(view*vec4(position.xyz,1.0)).xyz;
vec2 cornerPos;
float angle=position.w;
vec2 size=vec2(options.x,options.y);
vec2 offset=offsets.xy;
cornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;

vec3 rotatedCorner;
rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);
rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);
rotatedCorner.z=0.;

viewPos+=rotatedCorner;
gl_Position=projection*vec4(viewPos,1.0);

vColor=color;

vec2 uvOffset=vec2(abs(offset.x-inverts.x),abs(1.0-offset.y-inverts.y));
vec2 uvPlace=cellInfo.xy;
vec2 uvSize=cellInfo.zw;
vUV.x=uvPlace.x+uvSize.x*uvOffset.x;
vUV.y=uvPlace.y+uvSize.y*uvOffset.y;

#ifdef FOG
vFogDistance=viewPos;
#endif
}`;
ShaderStore.ShadersStore[name$C] = shader$C;
var SpriteRenderer = function() {
    function i(e, t, r, n) {
        r === void 0 && (r = .01),
        n === void 0 && (n = null),
        this.blendMode = 2,
        this.autoResetAlpha = !0,
        this.disableDepthWrite = !1,
        this.fogEnabled = !0,
        this._useVAO = !1,
        this._useInstancing = !1,
        this._vertexBuffers = {},
        this._capacity = t,
        this._epsilon = r,
        this._engine = e,
        this._useInstancing = e.getCaps().instancedArrays,
        this._useVAO = e.getCaps().vertexArrayObject && !e.disableVertexArrayObjects,
        this._scene = n,
        this._drawWrapperBase = new DrawWrapper(e),
        this._drawWrapperFog = new DrawWrapper(e),
        this._drawWrapperDepth = new DrawWrapper(e,!1),
        this._drawWrapperFogDepth = new DrawWrapper(e,!1),
        this._useInstancing || this._buildIndexBuffer(),
        this._drawWrapperBase.drawContext && (this._drawWrapperBase.drawContext.useInstancing = this._useInstancing),
        this._drawWrapperFog.drawContext && (this._drawWrapperFog.drawContext.useInstancing = this._useInstancing),
        this._drawWrapperDepth.drawContext && (this._drawWrapperDepth.drawContext.useInstancing = this._useInstancing),
        this._drawWrapperFogDepth.drawContext && (this._drawWrapperFogDepth.drawContext.useInstancing = this._useInstancing),
        this._vertexBufferSize = this._useInstancing ? 16 : 18,
        this._vertexData = new Float32Array(t * this._vertexBufferSize * (this._useInstancing ? 1 : 4)),
        this._buffer = new Buffer(e,this._vertexData,!0,this._vertexBufferSize);
        var o = this._buffer.createVertexBuffer(VertexBuffer.PositionKind, 0, 4, this._vertexBufferSize, this._useInstancing), a = this._buffer.createVertexBuffer("options", 4, 2, this._vertexBufferSize, this._useInstancing), s = 6, l;
        if (this._useInstancing) {
            var u = new Float32Array([0, 0, 1, 0, 0, 1, 1, 1]);
            this._spriteBuffer = new Buffer(e,u,!1,2),
            l = this._spriteBuffer.createVertexBuffer("offsets", 0, 2)
        } else
            l = this._buffer.createVertexBuffer("offsets", s, 2, this._vertexBufferSize, this._useInstancing),
            s += 2;
        var c = this._buffer.createVertexBuffer("inverts", s, 2, this._vertexBufferSize, this._useInstancing)
          , h = this._buffer.createVertexBuffer("cellInfo", s + 2, 4, this._vertexBufferSize, this._useInstancing)
          , f = this._buffer.createVertexBuffer(VertexBuffer.ColorKind, s + 6, 4, this._vertexBufferSize, this._useInstancing);
        this._vertexBuffers[VertexBuffer.PositionKind] = o,
        this._vertexBuffers.options = a,
        this._vertexBuffers.offsets = l,
        this._vertexBuffers.inverts = c,
        this._vertexBuffers.cellInfo = h,
        this._vertexBuffers[VertexBuffer.ColorKind] = f,
        this._drawWrapperBase.effect = this._engine.createEffect("sprites", [VertexBuffer.PositionKind, "options", "offsets", "inverts", "cellInfo", VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], ""),
        this._drawWrapperDepth.effect = this._drawWrapperBase.effect,
        this._drawWrapperDepth.materialContext = this._drawWrapperBase.materialContext,
        this._scene && (this._drawWrapperFog.effect = this._scene.getEngine().createEffect("sprites", [VertexBuffer.PositionKind, "options", "offsets", "inverts", "cellInfo", VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG"),
        this._drawWrapperFogDepth.effect = this._drawWrapperFog.effect,
        this._drawWrapperFogDepth.materialContext = this._drawWrapperFog.materialContext)
    }
    return Object.defineProperty(i.prototype, "capacity", {
        get: function() {
            return this._capacity
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.render = function(e, t, r, n, o) {
        if (o === void 0 && (o = null),
        !(!this.texture || !this.texture.isReady() || !e.length)) {
            var a = this._drawWrapperBase
              , s = this._drawWrapperDepth
              , l = !1;
            this.fogEnabled && this._scene && this._scene.fogEnabled && this._scene.fogMode !== 0 && (a = this._drawWrapperFog,
            s = this._drawWrapperFogDepth,
            l = !0);
            var u = a.effect;
            if (!!u.isReady()) {
                for (var c = this._engine, h = !!(this._scene && this._scene.useRightHandedSystem), f = this.texture.getBaseSize(), d = Math.min(this._capacity, e.length), _ = 0, g = !0, m = 0; m < d; m++) {
                    var v = e[m];
                    !v || !v.isVisible || (g = !1,
                    v._animate(t),
                    this._appendSpriteVertex(_++, v, 0, 0, f, h, o),
                    this._useInstancing || (this._appendSpriteVertex(_++, v, 1, 0, f, h, o),
                    this._appendSpriteVertex(_++, v, 1, 1, f, h, o),
                    this._appendSpriteVertex(_++, v, 0, 1, f, h, o)))
                }
                if (!g) {
                    this._buffer.update(this._vertexData);
                    var y = c.depthCullingState.cull || !0
                      , b = c.depthCullingState.zOffset
                      , T = c.depthCullingState.zOffsetUnits;
                    if (c.setState(y, b, !1, !1, void 0, void 0, T),
                    c.enableEffect(a),
                    u.setTexture("diffuseSampler", this.texture),
                    u.setMatrix("view", r),
                    u.setMatrix("projection", n),
                    l) {
                        var C = this._scene;
                        u.setFloat4("vFogInfos", C.fogMode, C.fogStart, C.fogEnd, C.fogDensity),
                        u.setColor3("vFogColor", C.fogColor)
                    }
                    this._useVAO ? (this._vertexArrayObject || (this._vertexArrayObject = c.recordVertexArrayObject(this._vertexBuffers, this._indexBuffer, u)),
                    c.bindVertexArrayObject(this._vertexArrayObject, this._indexBuffer)) : c.bindBuffers(this._vertexBuffers, this._indexBuffer, u),
                    c.depthCullingState.depthFunc = c.useReverseDepthBuffer ? 518 : 515,
                    this.disableDepthWrite || (u.setBool("alphaTest", !0),
                    c.setColorWrite(!1),
                    c.enableEffect(s),
                    this._useInstancing ? c.drawArraysType(7, 0, 4, _) : c.drawElementsType(0, 0, _ / 4 * 6),
                    c.enableEffect(a),
                    c.setColorWrite(!0),
                    u.setBool("alphaTest", !1)),
                    c.setAlphaMode(this.blendMode),
                    this._useInstancing ? c.drawArraysType(7, 0, 4, _) : c.drawElementsType(0, 0, _ / 4 * 6),
                    this.autoResetAlpha && c.setAlphaMode(0),
                    h && this._scene.getEngine().setState(y, b, !1, !0, void 0, void 0, T),
                    c.unbindInstanceAttributes()
                }
            }
        }
    }
    ,
    i.prototype._appendSpriteVertex = function(e, t, r, n, o, a, s) {
        var l = e * this._vertexBufferSize;
        if (r === 0 ? r = this._epsilon : r === 1 && (r = 1 - this._epsilon),
        n === 0 ? n = this._epsilon : n === 1 && (n = 1 - this._epsilon),
        s)
            s(t, o);
        else {
            t.cellIndex || (t.cellIndex = 0);
            var u = o.width / this.cellWidth
              , c = t.cellIndex / u >> 0;
            t._xOffset = (t.cellIndex - c * u) * this.cellWidth / o.width,
            t._yOffset = c * this.cellHeight / o.height,
            t._xSize = this.cellWidth,
            t._ySize = this.cellHeight
        }
        this._vertexData[l] = t.position.x,
        this._vertexData[l + 1] = t.position.y,
        this._vertexData[l + 2] = t.position.z,
        this._vertexData[l + 3] = t.angle,
        this._vertexData[l + 4] = t.width,
        this._vertexData[l + 5] = t.height,
        this._useInstancing ? l -= 2 : (this._vertexData[l + 6] = r,
        this._vertexData[l + 7] = n),
        a ? this._vertexData[l + 8] = t.invertU ? 0 : 1 : this._vertexData[l + 8] = t.invertU ? 1 : 0,
        this._vertexData[l + 9] = t.invertV ? 1 : 0,
        this._vertexData[l + 10] = t._xOffset,
        this._vertexData[l + 11] = t._yOffset,
        this._vertexData[l + 12] = t._xSize / o.width,
        this._vertexData[l + 13] = t._ySize / o.height,
        this._vertexData[l + 14] = t.color.r,
        this._vertexData[l + 15] = t.color.g,
        this._vertexData[l + 16] = t.color.b,
        this._vertexData[l + 17] = t.color.a
    }
    ,
    i.prototype._buildIndexBuffer = function() {
        for (var e = [], t = 0, r = 0; r < this._capacity; r++)
            e.push(t),
            e.push(t + 1),
            e.push(t + 2),
            e.push(t),
            e.push(t + 2),
            e.push(t + 3),
            t += 4;
        this._indexBuffer = this._engine.createIndexBuffer(e)
    }
    ,
    i.prototype.rebuild = function() {
        var e;
        this._indexBuffer && this._buildIndexBuffer(),
        this._useVAO && (this._vertexArrayObject = void 0),
        this._buffer._rebuild();
        for (var t in this._vertexBuffers) {
            var r = this._vertexBuffers[t];
            r._rebuild()
        }
        (e = this._spriteBuffer) === null || e === void 0 || e._rebuild()
    }
    ,
    i.prototype.dispose = function() {
        this._buffer && (this._buffer.dispose(),
        this._buffer = null),
        this._spriteBuffer && (this._spriteBuffer.dispose(),
        this._spriteBuffer = null),
        this._indexBuffer && (this._engine._releaseBuffer(this._indexBuffer),
        this._indexBuffer = null),
        this._vertexArrayObject && (this._engine.releaseVertexArrayObject(this._vertexArrayObject),
        this._vertexArrayObject = null),
        this.texture && (this.texture.dispose(),
        this.texture = null),
        this._drawWrapperBase.dispose(),
        this._drawWrapperFog.dispose(),
        this._drawWrapperDepth.dispose(),
        this._drawWrapperFogDepth.dispose()
    }
    ,
    i
}()
  , SpriteManager = function() {
    function i(e, t, r, n, o, a, s, l, u) {
        var c = this;
        a === void 0 && (a = .01),
        s === void 0 && (s = Texture.TRILINEAR_SAMPLINGMODE),
        l === void 0 && (l = !1),
        u === void 0 && (u = null),
        this.name = e,
        this.sprites = new Array,
        this.renderingGroupId = 0,
        this.layerMask = 268435455,
        this.isPickable = !1,
        this.onDisposeObservable = new Observable,
        this._disableDepthWrite = !1,
        this._packedAndReady = !1,
        this._customUpdate = function(f, d) {
            f.cellRef || (f.cellIndex = 0);
            var _ = f.cellIndex;
            typeof _ == "number" && isFinite(_) && Math.floor(_) === _ && (f.cellRef = c._spriteMap[f.cellIndex]),
            f._xOffset = c._cellData[f.cellRef].frame.x / d.width,
            f._yOffset = c._cellData[f.cellRef].frame.y / d.height,
            f._xSize = c._cellData[f.cellRef].frame.w,
            f._ySize = c._cellData[f.cellRef].frame.h
        }
        ,
        o || (o = Engine.LastCreatedScene),
        o._getComponent(SceneComponentConstants.NAME_SPRITE) || o._addComponent(new SpriteSceneComponent(o)),
        this._fromPacked = l,
        this._scene = o;
        var h = this._scene.getEngine();
        if (this._spriteRenderer = new SpriteRenderer(h,r,a,o),
        n.width && n.height)
            this.cellWidth = n.width,
            this.cellHeight = n.height;
        else if (n !== void 0)
            this.cellWidth = n,
            this.cellHeight = n;
        else {
            this._spriteRenderer = null;
            return
        }
        this._scene.spriteManagers.push(this),
        this.uniqueId = this.scene.getUniqueId(),
        t && (this.texture = new Texture(t,o,!0,!1,s)),
        this._fromPacked && this._makePacked(t, u)
    }
    return Object.defineProperty(i.prototype, "onDispose", {
        set: function(e) {
            this._onDisposeObserver && this.onDisposeObservable.remove(this._onDisposeObserver),
            this._onDisposeObserver = this.onDisposeObservable.add(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "children", {
        get: function() {
            return this.sprites
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "scene", {
        get: function() {
            return this._scene
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "capacity", {
        get: function() {
            return this._spriteRenderer.capacity
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "texture", {
        get: function() {
            return this._spriteRenderer.texture
        },
        set: function(e) {
            e.wrapU = Texture.CLAMP_ADDRESSMODE,
            e.wrapV = Texture.CLAMP_ADDRESSMODE,
            this._spriteRenderer.texture = e,
            this._textureContent = null
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "cellWidth", {
        get: function() {
            return this._spriteRenderer.cellWidth
        },
        set: function(e) {
            this._spriteRenderer.cellWidth = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "cellHeight", {
        get: function() {
            return this._spriteRenderer.cellHeight
        },
        set: function(e) {
            this._spriteRenderer.cellHeight = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "fogEnabled", {
        get: function() {
            return this._spriteRenderer.fogEnabled
        },
        set: function(e) {
            this._spriteRenderer.fogEnabled = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "blendMode", {
        get: function() {
            return this._spriteRenderer.blendMode
        },
        set: function(e) {
            this._spriteRenderer.blendMode = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "disableDepthWrite", {
        get: function() {
            return this._disableDepthWrite
        },
        set: function(e) {
            this._disableDepthWrite = e,
            this._spriteRenderer.disableDepthWrite = e
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.getClassName = function() {
        return "SpriteManager"
    }
    ,
    i.prototype._makePacked = function(e, t) {
        var r = this;
        if (t !== null)
            try {
                var n = void 0;
                if (typeof t == "string" ? n = JSON.parse(t) : n = t,
                n.frames.length) {
                    for (var o = {}, a = 0; a < n.frames.length; a++) {
                        var s = n.frames[a];
                        if (typeof Object.keys(s)[0] != "string")
                            throw new Error("Invalid JSON Format.  Check the frame values and make sure the name is the first parameter.");
                        var l = s[Object.keys(s)[0]];
                        o[l] = s
                    }
                    n.frames = o
                }
                var u = Reflect.ownKeys(n.frames);
                this._spriteMap = u,
                this._packedAndReady = !0,
                this._cellData = n.frames
            } catch {
                throw this._fromPacked = !1,
                this._packedAndReady = !1,
                new Error("Invalid JSON from string. Spritesheet managed with constant cell size.")
            }
        else {
            var c = /\./g
              , h = void 0;
            do
                h = c.lastIndex,
                c.test(e);
            while (c.lastIndex > 0);
            var f = e.substring(0, h - 1) + ".json"
              , d = new XMLHttpRequest;
            d.open("GET", f, !0),
            d.onerror = function() {
                Logger$2.Error("JSON ERROR: Unable to load JSON file."),
                r._fromPacked = !1,
                r._packedAndReady = !1
            }
            ,
            d.onload = function() {
                try {
                    var _ = JSON.parse(d.response)
                      , g = Reflect.ownKeys(_.frames);
                    r._spriteMap = g,
                    r._packedAndReady = !0,
                    r._cellData = _.frames
                } catch {
                    throw r._fromPacked = !1,
                    r._packedAndReady = !1,
                    new Error("Invalid JSON format. Please check documentation for format specifications.")
                }
            }
            ,
            d.send()
        }
    }
    ,
    i.prototype._checkTextureAlpha = function(e, t, r, n, o) {
        if (!e.useAlphaForPicking || !this.texture)
            return !0;
        var a = this.texture.getSize();
        this._textureContent || (this._textureContent = new Uint8Array(a.width * a.height * 4),
        this.texture.readPixels(0, 0, this._textureContent));
        var s = TmpVectors.Vector3[0];
        s.copyFrom(t.direction),
        s.normalize(),
        s.scaleInPlace(r),
        s.addInPlace(t.origin);
        var l = (s.x - n.x) / (o.x - n.x) - .5
          , u = 1 - (s.y - n.y) / (o.y - n.y) - .5
          , c = e.angle
          , h = .5 + (l * Math.cos(c) - u * Math.sin(c))
          , f = .5 + (l * Math.sin(c) + u * Math.cos(c))
          , d = e._xOffset * a.width + h * e._xSize | 0
          , _ = e._yOffset * a.height + f * e._ySize | 0
          , g = this._textureContent[(d + _ * a.width) * 4 + 3];
        return g > .5
    }
    ,
    i.prototype.intersects = function(e, t, r, n) {
        for (var o = Math.min(this.capacity, this.sprites.length), a = Vector3.Zero(), s = Vector3.Zero(), l = Number.MAX_VALUE, u = null, c = TmpVectors.Vector3[0], h = TmpVectors.Vector3[1], f = t.getViewMatrix(), d = e, _ = e, g = 0; g < o; g++) {
            var m = this.sprites[g];
            if (!!m) {
                if (r) {
                    if (!r(m))
                        continue
                } else if (!m.isPickable)
                    continue;
                if (Vector3.TransformCoordinatesToRef(m.position, f, h),
                m.angle ? (Matrix.TranslationToRef(-h.x, -h.y, 0, TmpVectors.Matrix[1]),
                Matrix.TranslationToRef(h.x, h.y, 0, TmpVectors.Matrix[2]),
                Matrix.RotationZToRef(m.angle, TmpVectors.Matrix[3]),
                TmpVectors.Matrix[1].multiplyToRef(TmpVectors.Matrix[3], TmpVectors.Matrix[4]),
                TmpVectors.Matrix[4].multiplyToRef(TmpVectors.Matrix[2], TmpVectors.Matrix[0]),
                d = e.clone(),
                Vector3.TransformCoordinatesToRef(e.origin, TmpVectors.Matrix[0], d.origin),
                Vector3.TransformNormalToRef(e.direction, TmpVectors.Matrix[0], d.direction)) : d = e,
                a.copyFromFloats(h.x - m.width / 2, h.y - m.height / 2, h.z),
                s.copyFromFloats(h.x + m.width / 2, h.y + m.height / 2, h.z),
                d.intersectsBoxMinMax(a, s)) {
                    var v = Vector3.Distance(h, d.origin);
                    if (l > v) {
                        if (!this._checkTextureAlpha(m, d, v, a, s))
                            continue;
                        if (_ = d,
                        l = v,
                        u = m,
                        n)
                            break
                    }
                }
            }
        }
        if (u) {
            var y = new PickingInfo;
            f.invertToRef(TmpVectors.Matrix[0]),
            y.hit = !0,
            y.pickedSprite = u,
            y.distance = l;
            var b = TmpVectors.Vector3[2];
            return b.copyFrom(_.direction),
            b.normalize(),
            b.scaleInPlace(l),
            _.origin.addToRef(b, c),
            y.pickedPoint = Vector3.TransformCoordinates(c, TmpVectors.Matrix[0]),
            y
        }
        return null
    }
    ,
    i.prototype.multiIntersects = function(e, t, r) {
        for (var n = Math.min(this.capacity, this.sprites.length), o = Vector3.Zero(), a = Vector3.Zero(), s, l = [], u = TmpVectors.Vector3[0].copyFromFloats(0, 0, 0), c = TmpVectors.Vector3[1].copyFromFloats(0, 0, 0), h = t.getViewMatrix(), f = 0; f < n; f++) {
            var d = this.sprites[f];
            if (!!d) {
                if (r) {
                    if (!r(d))
                        continue
                } else if (!d.isPickable)
                    continue;
                if (Vector3.TransformCoordinatesToRef(d.position, h, c),
                o.copyFromFloats(c.x - d.width / 2, c.y - d.height / 2, c.z),
                a.copyFromFloats(c.x + d.width / 2, c.y + d.height / 2, c.z),
                e.intersectsBoxMinMax(o, a)) {
                    if (s = Vector3.Distance(c, e.origin),
                    !this._checkTextureAlpha(d, e, s, o, a))
                        continue;
                    var _ = new PickingInfo;
                    l.push(_),
                    h.invertToRef(TmpVectors.Matrix[0]),
                    _.hit = !0,
                    _.pickedSprite = d,
                    _.distance = s;
                    var g = TmpVectors.Vector3[2];
                    g.copyFrom(e.direction),
                    g.normalize(),
                    g.scaleInPlace(s),
                    e.origin.addToRef(g, u),
                    _.pickedPoint = Vector3.TransformCoordinates(u, TmpVectors.Matrix[0])
                }
            }
        }
        return l
    }
    ,
    i.prototype.render = function() {
        if (!(this._fromPacked && (!this._packedAndReady || !this._spriteMap || !this._cellData))) {
            var e = 16.6;
            this._packedAndReady ? this._spriteRenderer.render(this.sprites, e, this._scene.getViewMatrix(), this._scene.getProjectionMatrix(), this._customUpdate) : this._spriteRenderer.render(this.sprites, e, this._scene.getViewMatrix(), this._scene.getProjectionMatrix())
        }
    }
    ,
    i.prototype.rebuild = function() {
        var e;
        (e = this._spriteRenderer) === null || e === void 0 || e.rebuild()
    }
    ,
    i.prototype.dispose = function() {
        this._spriteRenderer && (this._spriteRenderer.dispose(),
        this._spriteRenderer = null),
        this._textureContent = null;
        var e = this._scene.spriteManagers.indexOf(this);
        this._scene.spriteManagers.splice(e, 1),
        this.onDisposeObservable.notifyObservers(this),
        this.onDisposeObservable.clear()
    }
    ,
    i.prototype.serialize = function(e) {
        e === void 0 && (e = !1);
        var t = {};
        t.name = this.name,
        t.capacity = this.capacity,
        t.cellWidth = this.cellWidth,
        t.cellHeight = this.cellHeight,
        this.texture && (e ? t.texture = this.texture.serialize() : (t.textureUrl = this.texture.name,
        t.invertY = this.texture._invertY)),
        t.sprites = [];
        for (var r = 0, n = this.sprites; r < n.length; r++) {
            var o = n[r];
            t.sprites.push(o.serialize())
        }
        return t
    }
    ,
    i.Parse = function(e, t, r) {
        var n = new i(e.name,"",e.capacity,{
            width: e.cellWidth,
            height: e.cellHeight
        },t);
        e.texture ? n.texture = Texture.Parse(e.texture, t, r) : e.textureName && (n.texture = new Texture(r + e.textureUrl,t,!1,e.invertY !== void 0 ? e.invertY : !0));
        for (var o = 0, a = e.sprites; o < a.length; o++) {
            var s = a[o];
            Sprite.Parse(s, n)
        }
        return n
    }
    ,
    i.ParseFromFileAsync = function(e, t, r, n) {
        return n === void 0 && (n = ""),
        new Promise(function(o, a) {
            var s = new WebRequest;
            s.addEventListener("readystatechange", function() {
                if (s.readyState == 4)
                    if (s.status == 200) {
                        var l = JSON.parse(s.responseText)
                          , u = i.Parse(l, r || Engine.LastCreatedScene, n);
                        e && (u.name = e),
                        o(u)
                    } else
                        a("Unable to load the sprite manager")
            }),
            s.open("GET", t),
            s.send()
        }
        )
    }
    ,
    i.CreateFromSnippetAsync = function(e, t, r) {
        var n = this;
        return r === void 0 && (r = ""),
        e === "_BLANK" ? Promise.resolve(new i("Default sprite manager","//playground.babylonjs.com/textures/player.png",500,64,t)) : new Promise(function(o, a) {
            var s = new WebRequest;
            s.addEventListener("readystatechange", function() {
                if (s.readyState == 4)
                    if (s.status == 200) {
                        var l = JSON.parse(JSON.parse(s.responseText).jsonPayload)
                          , u = JSON.parse(l.spriteManager)
                          , c = i.Parse(u, t || Engine.LastCreatedScene, r);
                        c.snippetId = e,
                        o(c)
                    } else
                        a("Unable to load the snippet " + e)
            }),
            s.open("GET", n.SnippetUrl + "/" + e.replace(/#/g, "/")),
            s.send()
        }
        )
    }
    ,
    i.SnippetUrl = "https://snippet.babylonjs.com",
    i
}()
  , UtilityLayerRenderer = function() {
    function i(e, t) {
        var r = this;
        t === void 0 && (t = !0),
        this.originalScene = e,
        this._pointerCaptures = {},
        this._lastPointerEvents = {},
        this._sharedGizmoLight = null,
        this._renderCamera = null,
        this.pickUtilitySceneFirst = !0,
        this.shouldRender = !0,
        this.onlyCheckPointerDownEvents = !0,
        this.processAllEvents = !1,
        this.pickingEnabled = !0,
        this.onPointerOutObservable = new Observable,
        this.utilityLayerScene = new Scene(e.getEngine(),{
            virtual: !0
        }),
        this.utilityLayerScene.useRightHandedSystem = e.useRightHandedSystem,
        this.utilityLayerScene._allowPostProcessClearColor = !1,
        this.utilityLayerScene.detachControl(),
        t && (this._originalPointerObserver = e.onPrePointerObservable.add(function(n, o) {
            if (!!r.utilityLayerScene.activeCamera && !!r.pickingEnabled && !(!r.processAllEvents && n.type !== PointerEventTypes.POINTERMOVE && n.type !== PointerEventTypes.POINTERUP && n.type !== PointerEventTypes.POINTERDOWN && n.type !== PointerEventTypes.POINTERDOUBLETAP)) {
                r.utilityLayerScene.pointerX = e.pointerX,
                r.utilityLayerScene.pointerY = e.pointerY;
                var a = n.event;
                if (e.isPointerCaptured(a.pointerId)) {
                    r._pointerCaptures[a.pointerId] = !1;
                    return
                }
                var s = function(h) {
                    var f = null;
                    if (n.nearInteractionPickingInfo)
                        n.nearInteractionPickingInfo.pickedMesh.getScene() == h ? f = n.nearInteractionPickingInfo : f = new PickingInfo;
                    else {
                        var d = null;
                        r._renderCamera && (d = h._activeCamera,
                        h._activeCamera = r._renderCamera,
                        n.ray = null),
                        f = n.ray ? h.pickWithRay(n.ray) : h.pick(e.pointerX, e.pointerY),
                        d && (h._activeCamera = d)
                    }
                    return f
                }
                  , l = s(r.utilityLayerScene);
                if (!n.ray && l && (n.ray = l.ray),
                r.utilityLayerScene.onPrePointerObservable.notifyObservers(n),
                r.onlyCheckPointerDownEvents && n.type != PointerEventTypes.POINTERDOWN) {
                    n.skipOnPointerObservable || r.utilityLayerScene.onPointerObservable.notifyObservers(new PointerInfo(n.type,n.event,l), n.type),
                    n.type === PointerEventTypes.POINTERUP && r._pointerCaptures[a.pointerId] && (r._pointerCaptures[a.pointerId] = !1);
                    return
                }
                if (r.utilityLayerScene.autoClearDepthAndStencil || r.pickUtilitySceneFirst)
                    l && l.hit && (n.skipOnPointerObservable || r.utilityLayerScene.onPointerObservable.notifyObservers(new PointerInfo(n.type,n.event,l), n.type),
                    n.skipOnPointerObservable = !0);
                else {
                    var u = s(e)
                      , c = n.event;
                    u && l && (l.distance === 0 && u.pickedMesh ? r.mainSceneTrackerPredicate && r.mainSceneTrackerPredicate(u.pickedMesh) ? (r._notifyObservers(n, u, c),
                    n.skipOnPointerObservable = !0) : n.type === PointerEventTypes.POINTERDOWN ? r._pointerCaptures[c.pointerId] = !0 : (n.type === PointerEventTypes.POINTERMOVE || n.type === PointerEventTypes.POINTERUP) && (r._lastPointerEvents[c.pointerId] && (r.onPointerOutObservable.notifyObservers(c.pointerId),
                    delete r._lastPointerEvents[c.pointerId]),
                    r._notifyObservers(n, u, c)) : !r._pointerCaptures[c.pointerId] && (l.distance < u.distance || u.distance === 0) ? (r._notifyObservers(n, l, c),
                    n.skipOnPointerObservable || (n.skipOnPointerObservable = l.distance > 0)) : !r._pointerCaptures[c.pointerId] && l.distance > u.distance && (r.mainSceneTrackerPredicate && r.mainSceneTrackerPredicate(u.pickedMesh) ? (r._notifyObservers(n, u, c),
                    n.skipOnPointerObservable = !0) : (n.type === PointerEventTypes.POINTERMOVE || n.type === PointerEventTypes.POINTERUP) && (r._lastPointerEvents[c.pointerId] && (r.onPointerOutObservable.notifyObservers(c.pointerId),
                    delete r._lastPointerEvents[c.pointerId]),
                    r._notifyObservers(n, l, c))),
                    n.type === PointerEventTypes.POINTERUP && r._pointerCaptures[c.pointerId] && (r._pointerCaptures[c.pointerId] = !1))
                }
            }
        }),
        this._originalPointerObserver && e.onPrePointerObservable.makeObserverTopPriority(this._originalPointerObserver)),
        this.utilityLayerScene.autoClear = !1,
        this._afterRenderObserver = this.originalScene.onAfterCameraRenderObservable.add(function(n) {
            r.shouldRender && n == r.getRenderCamera() && r.render()
        }),
        this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function() {
            r.dispose()
        }),
        this._updateCamera()
    }
    return i.prototype.getRenderCamera = function(e) {
        if (this._renderCamera)
            return this._renderCamera;
        var t = void 0;
        return this.originalScene.activeCameras && this.originalScene.activeCameras.length > 1 ? t = this.originalScene.activeCameras[this.originalScene.activeCameras.length - 1] : t = this.originalScene.activeCamera,
        e && t && t.isRigCamera ? t.rigParent : t
    }
    ,
    i.prototype.setRenderCamera = function(e) {
        this._renderCamera = e
    }
    ,
    i.prototype._getSharedGizmoLight = function() {
        return this._sharedGizmoLight || (this._sharedGizmoLight = new HemisphericLight("shared gizmo light",new Vector3(0,1,0),this.utilityLayerScene),
        this._sharedGizmoLight.intensity = 2,
        this._sharedGizmoLight.groundColor = Color3.Gray()),
        this._sharedGizmoLight
    }
    ,
    Object.defineProperty(i, "DefaultUtilityLayer", {
        get: function() {
            return i._DefaultUtilityLayer == null ? i._CreateDefaultUtilityLayerFromScene(EngineStore.LastCreatedScene) : i._DefaultUtilityLayer
        },
        enumerable: !1,
        configurable: !0
    }),
    i._CreateDefaultUtilityLayerFromScene = function(e) {
        return i._DefaultUtilityLayer = new i(e),
        i._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function() {
            i._DefaultUtilityLayer = null
        }),
        i._DefaultUtilityLayer
    }
    ,
    Object.defineProperty(i, "DefaultKeepDepthUtilityLayer", {
        get: function() {
            return i._DefaultKeepDepthUtilityLayer == null && (i._DefaultKeepDepthUtilityLayer = new i(EngineStore.LastCreatedScene),
            i._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = !1,
            i._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function() {
                i._DefaultKeepDepthUtilityLayer = null
            })),
            i._DefaultKeepDepthUtilityLayer
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype._notifyObservers = function(e, t, r) {
        e.skipOnPointerObservable || (this.utilityLayerScene.onPointerObservable.notifyObservers(new PointerInfo(e.type,e.event,t), e.type),
        this._lastPointerEvents[r.pointerId] = !0)
    }
    ,
    i.prototype.render = function() {
        if (this._updateCamera(),
        this.utilityLayerScene.activeCamera) {
            var e = this.utilityLayerScene.activeCamera.getScene()
              , t = this.utilityLayerScene.activeCamera;
            t._scene = this.utilityLayerScene,
            t.leftCamera && (t.leftCamera._scene = this.utilityLayerScene),
            t.rightCamera && (t.rightCamera._scene = this.utilityLayerScene),
            this.utilityLayerScene.render(!1),
            t._scene = e,
            t.leftCamera && (t.leftCamera._scene = e),
            t.rightCamera && (t.rightCamera._scene = e)
        }
    }
    ,
    i.prototype.dispose = function() {
        this.onPointerOutObservable.clear(),
        this._afterRenderObserver && this.originalScene.onAfterCameraRenderObservable.remove(this._afterRenderObserver),
        this._sceneDisposeObserver && this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver),
        this._originalPointerObserver && this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver),
        this.utilityLayerScene.dispose()
    }
    ,
    i.prototype._updateCamera = function() {
        this.utilityLayerScene.cameraToUseForPointers = this.getRenderCamera(),
        this.utilityLayerScene.activeCamera = this.getRenderCamera()
    }
    ,
    i._DefaultUtilityLayer = null,
    i._DefaultKeepDepthUtilityLayer = null,
    i
}()
  , BaseSixDofDragBehavior = function() {
    function i() {
        this._attachedToElement = !1,
        this._virtualMeshesInfo = {},
        this._tmpVector = new Vector3,
        this._tmpQuaternion = new Quaternion,
        this._dragType = {
            NONE: 0,
            DRAG: 1,
            DRAG_WITH_CONTROLLER: 2,
            NEAR_DRAG: 3
        },
        this._moving = !1,
        this._dragging = this._dragType.NONE,
        this.draggableMeshes = null,
        this.zDragFactor = 3,
        this.currentDraggingPointerIds = [],
        this.detachCameraControls = !0,
        this.onDragStartObservable = new Observable,
        this.onDragObservable = new Observable,
        this.onDragEndObservable = new Observable,
        this.allowMultiPointer = !0
    }
    return Object.defineProperty(i.prototype, "currentDraggingPointerId", {
        get: function() {
            return this.currentDraggingPointerIds[0] !== void 0 ? this.currentDraggingPointerIds[0] : -1
        },
        set: function(e) {
            this.currentDraggingPointerIds[0] = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "currentDraggingPointerID", {
        get: function() {
            return this.currentDraggingPointerId
        },
        set: function(e) {
            this.currentDraggingPointerId = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "name", {
        get: function() {
            return "BaseSixDofDrag"
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "isMoving", {
        get: function() {
            return this._moving
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.init = function() {}
    ,
    Object.defineProperty(i.prototype, "_pointerCamera", {
        get: function() {
            return this._scene.cameraToUseForPointers ? this._scene.cameraToUseForPointers : this._scene.activeCamera
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype._createVirtualMeshInfo = function() {
        var e = new AbstractMesh("",i._virtualScene);
        e.rotationQuaternion = new Quaternion;
        var t = new AbstractMesh("",i._virtualScene);
        t.rotationQuaternion = new Quaternion;
        var r = new AbstractMesh("",i._virtualScene);
        return r.rotationQuaternion = new Quaternion,
        {
            dragging: !1,
            moving: !1,
            dragMesh: e,
            originMesh: t,
            pivotMesh: r,
            startingPivotPosition: new Vector3,
            startingPivotOrientation: new Quaternion,
            startingPosition: new Vector3,
            startingOrientation: new Quaternion,
            lastOriginPosition: new Vector3,
            lastDragPosition: new Vector3
        }
    }
    ,
    i.prototype._resetVirtualMeshesPosition = function() {
        for (var e = 0; e < this.currentDraggingPointerIds.length; e++)
            this._virtualMeshesInfo[this.currentDraggingPointerIds[e]].pivotMesh.position.copyFrom(this._ownerNode.getAbsolutePivotPoint()),
            this._virtualMeshesInfo[this.currentDraggingPointerIds[e]].pivotMesh.rotationQuaternion.copyFrom(this._ownerNode.rotationQuaternion),
            this._virtualMeshesInfo[this.currentDraggingPointerIds[e]].startingPivotPosition.copyFrom(this._virtualMeshesInfo[this.currentDraggingPointerIds[e]].pivotMesh.position),
            this._virtualMeshesInfo[this.currentDraggingPointerIds[e]].startingPivotOrientation.copyFrom(this._virtualMeshesInfo[this.currentDraggingPointerIds[e]].pivotMesh.rotationQuaternion),
            this._virtualMeshesInfo[this.currentDraggingPointerIds[e]].startingPosition.copyFrom(this._virtualMeshesInfo[this.currentDraggingPointerIds[e]].dragMesh.position),
            this._virtualMeshesInfo[this.currentDraggingPointerIds[e]].startingOrientation.copyFrom(this._virtualMeshesInfo[this.currentDraggingPointerIds[e]].dragMesh.rotationQuaternion)
    }
    ,
    i.prototype._pointerUpdate2D = function(e, t, r) {
        this._pointerCamera && this._pointerCamera.cameraRigMode == Camera$1.RIG_MODE_NONE && !this._pointerCamera._isLeftCamera && !this._pointerCamera._isRightCamera && (e.origin.copyFrom(this._pointerCamera.globalPosition),
        r = 0);
        var n = this._virtualMeshesInfo[t]
          , o = TmpVectors.Vector3[0];
        e.origin.subtractToRef(n.lastOriginPosition, o),
        n.lastOriginPosition.copyFrom(e.origin);
        var a = -Vector3.Dot(o, e.direction);
        n.originMesh.addChild(n.dragMesh),
        n.originMesh.addChild(n.pivotMesh),
        this._applyZOffset(n.dragMesh, a, r),
        this._applyZOffset(n.pivotMesh, a, r),
        n.originMesh.position.copyFrom(e.origin);
        var s = TmpVectors.Vector3[0];
        e.origin.addToRef(e.direction, s),
        n.originMesh.lookAt(s),
        n.originMesh.removeChild(n.dragMesh),
        n.originMesh.removeChild(n.pivotMesh)
    }
    ,
    i.prototype._pointerUpdateXR = function(e, t, r, n) {
        var o = this._virtualMeshesInfo[r];
        o.originMesh.position.copyFrom(e.position),
        this._dragging === this._dragType.NEAR_DRAG && t ? o.originMesh.rotationQuaternion.copyFrom(t.rotationQuaternion) : o.originMesh.rotationQuaternion.copyFrom(e.rotationQuaternion);
        var a = TmpVectors.Vector3[0]
          , s = TmpVectors.Vector3[1];
        a.copyFrom(this._pointerCamera.getForwardRay().direction),
        o.originMesh.position.subtractToRef(o.lastOriginPosition, s),
        o.lastOriginPosition.copyFrom(o.originMesh.position);
        var l = s.length();
        s.normalize(),
        o.pivotMesh.computeWorldMatrix(!0),
        o.dragMesh.computeWorldMatrix(!0);
        var u = TmpVectors.Vector3[2]
          , c = TmpVectors.Vector3[3];
        o.dragMesh.absolutePosition.subtractToRef(this._pointerCamera.globalPosition, u),
        o.dragMesh.absolutePosition.subtractToRef(o.originMesh.position, c);
        var h = c.length();
        u.normalize(),
        c.normalize();
        var f = Math.abs(Vector3.Dot(s, c)) * Vector3.Dot(s, a)
          , d = f * n * l * h;
        d + h < .1 && (d = Math.min(h, .1)),
        c.scaleInPlace(d),
        c.addToRef(o.pivotMesh.absolutePosition, this._tmpVector),
        o.pivotMesh.setAbsolutePosition(this._tmpVector),
        c.addToRef(o.dragMesh.absolutePosition, this._tmpVector),
        o.dragMesh.setAbsolutePosition(this._tmpVector)
    }
    ,
    i.prototype.attach = function(e) {
        var t = this;
        this._ownerNode = e,
        this._scene = this._ownerNode.getScene(),
        i._virtualScene || (i._virtualScene = new Scene(this._scene.getEngine(),{
            virtual: !0
        }),
        i._virtualScene.detachControl());
        var r = function(n) {
            return t._ownerNode === n || n.isDescendantOf(t._ownerNode) && (!t.draggableMeshes || t.draggableMeshes.indexOf(n) !== -1)
        };
        this._pointerObserver = this._scene.onPointerObservable.add(function(n, o) {
            var a = n.event.pointerId;
            t._virtualMeshesInfo[a] || (t._virtualMeshesInfo[a] = t._createVirtualMeshInfo());
            var s = t._virtualMeshesInfo[a]
              , l = n.event.pointerType === "xr";
            if (n.type == PointerEventTypes.POINTERDOWN) {
                if (!s.dragging && n.pickInfo && n.pickInfo.hit && n.pickInfo.pickedMesh && n.pickInfo.pickedPoint && n.pickInfo.ray && (!l || n.pickInfo.aimTransform) && r(n.pickInfo.pickedMesh)) {
                    if (!t.allowMultiPointer && t.currentDraggingPointerIds.length > 0)
                        return;
                    t._pointerCamera && t._pointerCamera.cameraRigMode === Camera$1.RIG_MODE_NONE && !t._pointerCamera._isLeftCamera && !t._pointerCamera._isRightCamera && n.pickInfo.ray.origin.copyFrom(t._pointerCamera.globalPosition),
                    t._ownerNode.computeWorldMatrix(!0);
                    var u = t._virtualMeshesInfo[a];
                    l ? (t._dragging = n.pickInfo.originMesh ? t._dragType.NEAR_DRAG : t._dragType.DRAG_WITH_CONTROLLER,
                    u.originMesh.position.copyFrom(n.pickInfo.aimTransform.position),
                    t._dragging === t._dragType.NEAR_DRAG && n.pickInfo.gripTransform ? u.originMesh.rotationQuaternion.copyFrom(n.pickInfo.gripTransform.rotationQuaternion) : u.originMesh.rotationQuaternion.copyFrom(n.pickInfo.aimTransform.rotationQuaternion)) : (t._dragging = t._dragType.DRAG,
                    u.originMesh.position.copyFrom(n.pickInfo.ray.origin)),
                    u.lastOriginPosition.copyFrom(u.originMesh.position),
                    u.dragMesh.position.copyFrom(n.pickInfo.pickedPoint),
                    u.lastDragPosition.copyFrom(n.pickInfo.pickedPoint),
                    u.pivotMesh.position.copyFrom(t._ownerNode.getAbsolutePivotPoint()),
                    u.pivotMesh.rotationQuaternion.copyFrom(t._ownerNode.absoluteRotationQuaternion),
                    u.startingPosition.copyFrom(u.dragMesh.position),
                    u.startingPivotPosition.copyFrom(u.pivotMesh.position),
                    u.startingOrientation.copyFrom(u.dragMesh.rotationQuaternion),
                    u.startingPivotOrientation.copyFrom(u.pivotMesh.rotationQuaternion),
                    l ? (u.originMesh.addChild(u.dragMesh),
                    u.originMesh.addChild(u.pivotMesh)) : u.originMesh.lookAt(u.dragMesh.position),
                    u.dragging = !0,
                    t.currentDraggingPointerIds.indexOf(a) === -1 && t.currentDraggingPointerIds.push(a),
                    t.detachCameraControls && t._pointerCamera && !t._pointerCamera.leftCamera && (t._pointerCamera.inputs && t._pointerCamera.inputs.attachedToElement ? (t._pointerCamera.detachControl(),
                    t._attachedToElement = !0) : t._attachedToElement = !1),
                    t._targetDragStart(u.pivotMesh.position, u.pivotMesh.rotationQuaternion, a),
                    t.onDragStartObservable.notifyObservers({
                        position: u.pivotMesh.position
                    })
                }
            } else if (n.type == PointerEventTypes.POINTERUP || n.type == PointerEventTypes.POINTERDOUBLETAP) {
                var c = t.currentDraggingPointerIds.indexOf(a);
                s.dragging = !1,
                c !== -1 && (t.currentDraggingPointerIds.splice(c, 1),
                t.currentDraggingPointerIds.length === 0 && (t._moving = !1,
                t._dragging = t._dragType.NONE,
                t.detachCameraControls && t._attachedToElement && t._pointerCamera && !t._pointerCamera.leftCamera && (t._pointerCamera.attachControl(!0),
                t._attachedToElement = !1)),
                s.originMesh.removeChild(s.dragMesh),
                s.originMesh.removeChild(s.pivotMesh),
                t._targetDragEnd(a),
                t.onDragEndObservable.notifyObservers({}))
            } else if (n.type == PointerEventTypes.POINTERMOVE) {
                var c = t.currentDraggingPointerIds.indexOf(a);
                if (c !== -1 && s.dragging && n.pickInfo && (n.pickInfo.ray || n.pickInfo.aimTransform)) {
                    var h = t.zDragFactor;
                    (t.currentDraggingPointerIds.length > 1 || n.pickInfo.originMesh) && (h = 0),
                    t._ownerNode.computeWorldMatrix(!0),
                    l ? t._pointerUpdateXR(n.pickInfo.aimTransform, n.pickInfo.gripTransform, a, h) : t._pointerUpdate2D(n.pickInfo.ray, a, h),
                    t._tmpQuaternion.copyFrom(s.startingPivotOrientation),
                    t._tmpQuaternion.x = -t._tmpQuaternion.x,
                    t._tmpQuaternion.y = -t._tmpQuaternion.y,
                    t._tmpQuaternion.z = -t._tmpQuaternion.z,
                    s.pivotMesh.absoluteRotationQuaternion.multiplyToRef(t._tmpQuaternion, t._tmpQuaternion),
                    s.pivotMesh.absolutePosition.subtractToRef(s.startingPivotPosition, t._tmpVector),
                    t.onDragObservable.notifyObservers({
                        delta: t._tmpVector,
                        position: s.pivotMesh.position,
                        pickInfo: n.pickInfo
                    }),
                    t._targetDrag(t._tmpVector, t._tmpQuaternion, a),
                    s.lastDragPosition.copyFrom(s.dragMesh.absolutePosition),
                    t._moving = !0
                }
            }
        })
    }
    ,
    i.prototype._applyZOffset = function(e, t, r) {
        e.position.z -= e.position.z < 1 ? t * r : t * r * e.position.z,
        e.position.z < 0 && (e.position.z = 0)
    }
    ,
    i.prototype._targetDragStart = function(e, t, r) {}
    ,
    i.prototype._targetDrag = function(e, t, r) {}
    ,
    i.prototype._targetDragEnd = function(e) {}
    ,
    i.prototype.detach = function() {
        this._scene && (this.detachCameraControls && this._attachedToElement && this._pointerCamera && !this._pointerCamera.leftCamera && (this._pointerCamera.attachControl(!0),
        this._attachedToElement = !1),
        this._scene.onPointerObservable.remove(this._pointerObserver));
        for (var e in this._virtualMeshesInfo)
            this._virtualMeshesInfo[e].originMesh.dispose(),
            this._virtualMeshesInfo[e].dragMesh.dispose();
        this.onDragEndObservable.clear(),
        this.onDragObservable.clear(),
        this.onDragStartObservable.clear()
    }
    ,
    i
}()
  , SixDofDragBehavior = function(i) {
    __extends(e, i);
    function e() {
        var t = i !== null && i.apply(this, arguments) || this;
        return t._sceneRenderObserver = null,
        t._targetPosition = new Vector3(0,0,0),
        t._targetOrientation = new Quaternion,
        t._targetScaling = new Vector3(1,1,1),
        t._startingPosition = new Vector3(0,0,0),
        t._startingOrientation = new Quaternion,
        t._startingScaling = new Vector3(1,1,1),
        t.onPositionChangedObservable = new Observable,
        t.dragDeltaRatio = .2,
        t.rotateDraggedObject = !0,
        t.rotateAroundYOnly = !1,
        t.rotateWithMotionController = !0,
        t.disableMovement = !1,
        t.faceCameraOnDragStart = !1,
        t
    }
    return Object.defineProperty(e.prototype, "name", {
        get: function() {
            return "SixDofDrag"
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.attach = function(t) {
        var r = this;
        i.prototype.attach.call(this, t),
        t.isNearGrabbable = !0,
        this._virtualTransformNode = new TransformNode("virtual_sixDof",BaseSixDofDragBehavior._virtualScene),
        this._virtualTransformNode.rotationQuaternion = Quaternion.Identity(),
        this._sceneRenderObserver = t.getScene().onBeforeRenderObservable.add(function() {
            if (r.currentDraggingPointerIds.length === 1 && r._moving && !r.disableMovement) {
                var n = t.parent;
                t.setParent(null),
                t.position.addInPlace(r._targetPosition.subtract(t.position).scale(r.dragDeltaRatio)),
                r.onPositionChangedObservable.notifyObservers({
                    position: t.absolutePosition
                }),
                (!n || n.scaling && !n.scaling.isNonUniformWithinEpsilon(.001)) && Quaternion.SlerpToRef(t.rotationQuaternion, r._targetOrientation, r.dragDeltaRatio, t.rotationQuaternion),
                t.setParent(n)
            }
        })
    }
    ,
    e.prototype._getPositionOffsetAround = function(t, r, n) {
        var o = TmpVectors.Matrix[0]
          , a = TmpVectors.Matrix[1]
          , s = TmpVectors.Matrix[2]
          , l = TmpVectors.Matrix[3]
          , u = TmpVectors.Matrix[4];
        return Matrix.TranslationToRef(t.x, t.y, t.z, o),
        Matrix.TranslationToRef(-t.x, -t.y, -t.z, a),
        Matrix.FromQuaternionToRef(n, s),
        Matrix.ScalingToRef(r, r, r, l),
        a.multiplyToRef(s, u),
        u.multiplyToRef(l, u),
        u.multiplyToRef(o, u),
        u.getTranslation()
    }
    ,
    e.prototype._onePointerPositionUpdated = function(t, r) {
        var n = TmpVectors.Vector3[0];
        n.setAll(0),
        this._dragging === this._dragType.DRAG ? this.rotateDraggedObject && (this.rotateAroundYOnly ? Quaternion.RotationYawPitchRollToRef(r.toEulerAngles().y, 0, 0, TmpVectors.Quaternion[0]) : TmpVectors.Quaternion[0].copyFrom(r),
        TmpVectors.Quaternion[0].multiplyToRef(this._startingOrientation, this._targetOrientation)) : (this._dragging === this._dragType.NEAR_DRAG || this._dragging === this._dragType.DRAG_WITH_CONTROLLER && this.rotateWithMotionController) && r.multiplyToRef(this._startingOrientation, this._targetOrientation),
        this._targetPosition.copyFrom(this._startingPosition).addInPlace(t)
    }
    ,
    e.prototype._twoPointersPositionUpdated = function() {
        var t = this._virtualMeshesInfo[this.currentDraggingPointerIds[0]].startingPosition
          , r = this._virtualMeshesInfo[this.currentDraggingPointerIds[1]].startingPosition
          , n = TmpVectors.Vector3[0];
        t.addToRef(r, n),
        n.scaleInPlace(.5);
        var o = TmpVectors.Vector3[1];
        r.subtractToRef(t, o);
        var a = this._virtualMeshesInfo[this.currentDraggingPointerIds[0]].dragMesh.absolutePosition
          , s = this._virtualMeshesInfo[this.currentDraggingPointerIds[1]].dragMesh.absolutePosition
          , l = TmpVectors.Vector3[2];
        a.addToRef(s, l),
        l.scaleInPlace(.5);
        var u = TmpVectors.Vector3[3];
        s.subtractToRef(a, u);
        var c = u.length() / o.length()
          , h = l.subtract(n)
          , f = Quaternion.FromEulerAngles(0, Vector3.GetAngleBetweenVectorsOnPlane(o.normalize(), u.normalize(), Vector3.UpReadOnly), 0)
          , d = this._ownerNode.parent;
        this._ownerNode.setParent(null);
        var _ = this._getPositionOffsetAround(n.subtract(this._virtualTransformNode.getAbsolutePivotPoint()), c, f);
        this._virtualTransformNode.rotationQuaternion.multiplyToRef(f, this._ownerNode.rotationQuaternion),
        this._virtualTransformNode.scaling.scaleToRef(c, this._ownerNode.scaling),
        this._virtualTransformNode.position.addToRef(h.addInPlace(_), this._ownerNode.position),
        this.onPositionChangedObservable.notifyObservers({
            position: this._ownerNode.position
        }),
        this._ownerNode.setParent(d)
    }
    ,
    e.prototype._targetDragStart = function() {
        var t = this.currentDraggingPointerIds.length
          , r = this._ownerNode.parent;
        this._ownerNode.rotationQuaternion || (this._ownerNode.rotationQuaternion = Quaternion.RotationYawPitchRoll(this._ownerNode.rotation.y, this._ownerNode.rotation.x, this._ownerNode.rotation.z));
        var n = this._ownerNode.getAbsolutePivotPoint();
        if (this._ownerNode.setParent(null),
        t === 1) {
            if (this._targetPosition.copyFrom(this._ownerNode.position),
            this._targetOrientation.copyFrom(this._ownerNode.rotationQuaternion),
            this._targetScaling.copyFrom(this._ownerNode.scaling),
            this.faceCameraOnDragStart && this._scene.activeCamera) {
                var o = TmpVectors.Vector3[0];
                this._scene.activeCamera.position.subtractToRef(n, o),
                o.normalize();
                var a = TmpVectors.Quaternion[0];
                this._scene.useRightHandedSystem ? Quaternion.FromLookDirectionRHToRef(o, new Vector3(0,1,0), a) : Quaternion.FromLookDirectionLHToRef(o, new Vector3(0,1,0), a),
                a.normalize(),
                Quaternion.RotationYawPitchRollToRef(a.toEulerAngles().y, 0, 0, TmpVectors.Quaternion[0]),
                this._targetOrientation.copyFrom(TmpVectors.Quaternion[0])
            }
            this._startingPosition.copyFrom(this._targetPosition),
            this._startingOrientation.copyFrom(this._targetOrientation),
            this._startingScaling.copyFrom(this._targetScaling)
        } else
            t === 2 && (this._virtualTransformNode.setPivotPoint(new Vector3(0,0,0), Space.LOCAL),
            this._virtualTransformNode.position.copyFrom(this._ownerNode.position),
            this._virtualTransformNode.scaling.copyFrom(this._ownerNode.scaling),
            this._virtualTransformNode.rotationQuaternion.copyFrom(this._ownerNode.rotationQuaternion),
            this._virtualTransformNode.setPivotPoint(n, Space.WORLD),
            this._resetVirtualMeshesPosition());
        this._ownerNode.setParent(r)
    }
    ,
    e.prototype._targetDrag = function(t, r, n) {
        this.currentDraggingPointerIds.length === 1 ? this._onePointerPositionUpdated(t, r) : this.currentDraggingPointerIds.length === 2 && this._twoPointersPositionUpdated()
    }
    ,
    e.prototype._targetDragEnd = function() {
        if (this.currentDraggingPointerIds.length === 1) {
            this._resetVirtualMeshesPosition();
            var t = this.faceCameraOnDragStart;
            this.faceCameraOnDragStart = !1,
            this._targetDragStart(),
            this.faceCameraOnDragStart = t
        }
    }
    ,
    e.prototype.detach = function() {
        i.prototype.detach.call(this),
        this._ownerNode && (this._ownerNode.isNearGrabbable = !1,
        this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver)),
        this._virtualTransformNode && this._virtualTransformNode.dispose()
    }
    ,
    e
}(BaseSixDofDragBehavior)
  , Gizmo = function() {
    function i(e) {
        var t = this;
        e === void 0 && (e = UtilityLayerRenderer.DefaultUtilityLayer),
        this.gizmoLayer = e,
        this._attachedMesh = null,
        this._attachedNode = null,
        this._customRotationQuaternion = null,
        this._scaleRatio = 1,
        this._isHovered = !1,
        this._customMeshSet = !1,
        this._updateGizmoRotationToMatchAttachedMesh = !0,
        this.updateGizmoPositionToMatchAttachedMesh = !0,
        this.updateScale = !0,
        this._interactionsEnabled = !0,
        this._tempQuaternion = new Quaternion(0,0,0,1),
        this._tempVector = new Vector3,
        this._tempVector2 = new Vector3,
        this._tempMatrix1 = new Matrix,
        this._tempMatrix2 = new Matrix,
        this._rightHandtoLeftHandMatrix = Matrix.RotationY(Math.PI),
        this._rootMesh = new Mesh("gizmoRootNode",e.utilityLayerScene),
        this._rootMesh.rotationQuaternion = Quaternion.Identity(),
        this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function() {
            t._update()
        })
    }
    return Object.defineProperty(i.prototype, "scaleRatio", {
        get: function() {
            return this._scaleRatio
        },
        set: function(e) {
            this._scaleRatio = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "isHovered", {
        get: function() {
            return this._isHovered
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "attachedMesh", {
        get: function() {
            return this._attachedMesh
        },
        set: function(e) {
            this._attachedMesh = e,
            e && (this._attachedNode = e),
            this._rootMesh.setEnabled(!!e),
            this._attachedNodeChanged(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "attachedNode", {
        get: function() {
            return this._attachedNode
        },
        set: function(e) {
            this._attachedNode = e,
            this._attachedMesh = null,
            this._rootMesh.setEnabled(!!e),
            this._attachedNodeChanged(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.setCustomMesh = function(e) {
        if (e.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(t) {
            t.dispose()
        }),
        e.parent = this._rootMesh,
        this._customMeshSet = !0
    }
    ,
    Object.defineProperty(i.prototype, "updateGizmoRotationToMatchAttachedMesh", {
        get: function() {
            return this._updateGizmoRotationToMatchAttachedMesh
        },
        set: function(e) {
            this._updateGizmoRotationToMatchAttachedMesh = e
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype._attachedNodeChanged = function(e) {}
    ,
    Object.defineProperty(i.prototype, "customRotationQuaternion", {
        get: function() {
            return this._customRotationQuaternion
        },
        set: function(e) {
            this._customRotationQuaternion = e
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype._update = function() {
        if (this.attachedNode) {
            var e = this.attachedNode;
            if (this.attachedMesh && (e = this.attachedMesh._effectiveMesh || this.attachedNode),
            this.updateGizmoPositionToMatchAttachedMesh) {
                var t = e.getWorldMatrix().getRow(3)
                  , r = t ? t.toVector3() : new Vector3(0,0,0);
                this._rootMesh.position.copyFrom(r)
            }
            if (this.updateGizmoRotationToMatchAttachedMesh ? e.getWorldMatrix().decompose(void 0, this._rootMesh.rotationQuaternion) : this._customRotationQuaternion ? this._rootMesh.rotationQuaternion.copyFrom(this._customRotationQuaternion) : this._rootMesh.rotationQuaternion.set(0, 0, 0, 1),
            this.updateScale) {
                var n = this.gizmoLayer.utilityLayerScene.activeCamera
                  , o = n.globalPosition;
                n.devicePosition && (o = n.devicePosition),
                this._rootMesh.position.subtractToRef(o, this._tempVector);
                var a = this._tempVector.length() * this.scaleRatio;
                this._rootMesh.scaling.set(a, a, a),
                e._getWorldMatrixDeterminant() < 0 && (this._rootMesh.scaling.y *= -1)
            } else
                this._rootMesh.scaling.setAll(this.scaleRatio)
        }
    }
    ,
    i.prototype._handlePivot = function() {
        var e = this._attachedNode;
        e.isUsingPivotMatrix && e.isUsingPivotMatrix() && e.position && e.getWorldMatrix().setTranslation(e.position)
    }
    ,
    i.prototype._matrixChanged = function() {
        if (!!this._attachedNode)
            if (this._attachedNode._isCamera) {
                var e = this._attachedNode, t, r;
                if (e.parent) {
                    var n = this._tempMatrix2;
                    e.parent._worldMatrix.invertToRef(n),
                    this._attachedNode._worldMatrix.multiplyToRef(n, this._tempMatrix1),
                    t = this._tempMatrix1
                } else
                    t = this._attachedNode._worldMatrix;
                e.getScene().useRightHandedSystem ? (this._rightHandtoLeftHandMatrix.multiplyToRef(t, this._tempMatrix2),
                r = this._tempMatrix2) : r = t,
                r.decompose(this._tempVector2, this._tempQuaternion, this._tempVector);
                var o = this._attachedNode.getClassName() === "FreeCamera" || this._attachedNode.getClassName() === "FlyCamera" || this._attachedNode.getClassName() === "ArcFollowCamera" || this._attachedNode.getClassName() === "TargetCamera" || this._attachedNode.getClassName() === "TouchCamera" || this._attachedNode.getClassName() === "UniversalCamera";
                if (o) {
                    var a = this._attachedNode;
                    a.rotation = this._tempQuaternion.toEulerAngles(),
                    a.rotationQuaternion && (a.rotationQuaternion.copyFrom(this._tempQuaternion),
                    a.rotationQuaternion.normalize())
                }
                e.position.copyFrom(this._tempVector)
            } else if (this._attachedNode._isMesh || this._attachedNode.getClassName() === "AbstractMesh" || this._attachedNode.getClassName() === "TransformNode" || this._attachedNode.getClassName() === "InstancedMesh") {
                var s = this._attachedNode;
                if (s.parent) {
                    var n = this._tempMatrix1
                      , l = this._tempMatrix2;
                    s.parent.getWorldMatrix().invertToRef(n),
                    this._attachedNode.getWorldMatrix().multiplyToRef(n, l),
                    l.decompose(s.scaling, this._tempQuaternion, s.position)
                } else
                    this._attachedNode._worldMatrix.decompose(s.scaling, this._tempQuaternion, s.position);
                s.billboardMode || (s.rotationQuaternion ? (s.rotationQuaternion.copyFrom(this._tempQuaternion),
                s.rotationQuaternion.normalize()) : s.rotation = this._tempQuaternion.toEulerAngles())
            } else if (this._attachedNode.getClassName() === "Bone") {
                var u = this._attachedNode
                  , c = u.getParent();
                if (c) {
                    var h = this._tempMatrix1
                      , f = this._tempMatrix2;
                    c.getWorldMatrix().invertToRef(h),
                    u.getWorldMatrix().multiplyToRef(h, f);
                    var d = u.getLocalMatrix();
                    d.copyFrom(f)
                } else {
                    var d = u.getLocalMatrix();
                    d.copyFrom(u.getWorldMatrix())
                }
                u.markAsDirty()
            } else {
                var _ = this._attachedNode;
                if (_.getTypeID) {
                    var g = _.getTypeID();
                    if (g === Light.LIGHTTYPEID_DIRECTIONALLIGHT || g === Light.LIGHTTYPEID_SPOTLIGHT || g === Light.LIGHTTYPEID_POINTLIGHT) {
                        var m = _.parent;
                        if (m) {
                            var h = this._tempMatrix1
                              , v = this._tempMatrix2;
                            m.getWorldMatrix().invertToRef(h),
                            _.getWorldMatrix().multiplyToRef(h, v),
                            v.decompose(void 0, this._tempQuaternion, this._tempVector)
                        } else
                            this._attachedNode._worldMatrix.decompose(void 0, this._tempQuaternion, this._tempVector);
                        _.position = new Vector3(this._tempVector.x,this._tempVector.y,this._tempVector.z),
                        Vector3.Backward(!1).rotateByQuaternionToRef(this._tempQuaternion, this._tempVector),
                        _.direction = new Vector3(this._tempVector.x,this._tempVector.y,this._tempVector.z)
                    }
                }
            }
    }
    ,
    i.prototype._setGizmoMeshMaterial = function(e, t) {
        e && e.forEach(function(r) {
            r.material = t,
            r.color && (r.color = t.diffuseColor)
        })
    }
    ,
    i.GizmoAxisPointerObserver = function(e, t) {
        var r = !1
          , n = e.utilityLayerScene.onPointerObservable.add(function(o) {
            var a, s;
            if (o.pickInfo) {
                if (o.type === PointerEventTypes.POINTERMOVE) {
                    if (r)
                        return;
                    t.forEach(function(u) {
                        var c, h;
                        if (u.colliderMeshes && u.gizmoMeshes) {
                            var f = ((c = u.colliderMeshes) === null || c === void 0 ? void 0 : c.indexOf((h = o == null ? void 0 : o.pickInfo) === null || h === void 0 ? void 0 : h.pickedMesh)) != -1
                              , d = u.dragBehavior.enabled ? f || u.active ? u.hoverMaterial : u.material : u.disableMaterial;
                            u.gizmoMeshes.forEach(function(_) {
                                _.material = d,
                                _.color && (_.color = d.diffuseColor)
                            })
                        }
                    })
                }
                if (o.type === PointerEventTypes.POINTERDOWN && t.has((a = o.pickInfo.pickedMesh) === null || a === void 0 ? void 0 : a.parent)) {
                    r = !0;
                    var l = t.get((s = o.pickInfo.pickedMesh) === null || s === void 0 ? void 0 : s.parent);
                    l.active = !0,
                    t.forEach(function(u) {
                        var c, h, f = ((c = u.colliderMeshes) === null || c === void 0 ? void 0 : c.indexOf((h = o == null ? void 0 : o.pickInfo) === null || h === void 0 ? void 0 : h.pickedMesh)) != -1, d = (f || u.active) && u.dragBehavior.enabled ? u.hoverMaterial : u.disableMaterial;
                        u.gizmoMeshes.forEach(function(_) {
                            _.material = d,
                            _.color && (_.color = d.diffuseColor)
                        })
                    })
                }
                o.type === PointerEventTypes.POINTERUP && t.forEach(function(u) {
                    u.active = !1,
                    r = !1,
                    u.gizmoMeshes.forEach(function(c) {
                        c.material = u.dragBehavior.enabled ? u.material : u.disableMaterial,
                        c.color && (c.color = u.material.diffuseColor)
                    })
                })
            }
        });
        return n
    }
    ,
    i.prototype.dispose = function() {
        this._rootMesh.dispose(),
        this._beforeRenderObserver && this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver)
    }
    ,
    i
}()
  , PivotTools = function() {
    function i() {}
    return i._RemoveAndStorePivotPoint = function(e) {
        e && i._PivotCached === 0 && (e.getPivotPointToRef(i._OldPivotPoint),
        i._PivotPostMultiplyPivotMatrix = e._postMultiplyPivotMatrix,
        i._OldPivotPoint.equalsToFloats(0, 0, 0) || (e.setPivotMatrix(Matrix.IdentityReadOnly),
        i._OldPivotPoint.subtractToRef(e.getPivotPoint(), i._PivotTranslation),
        i._PivotTmpVector.copyFromFloats(1, 1, 1),
        i._PivotTmpVector.subtractInPlace(e.scaling),
        i._PivotTmpVector.multiplyInPlace(i._PivotTranslation),
        e.position.addInPlace(i._PivotTmpVector))),
        i._PivotCached++
    }
    ,
    i._RestorePivotPoint = function(e) {
        e && !i._OldPivotPoint.equalsToFloats(0, 0, 0) && i._PivotCached === 1 && (e.setPivotPoint(i._OldPivotPoint),
        e._postMultiplyPivotMatrix = i._PivotPostMultiplyPivotMatrix,
        i._PivotTmpVector.copyFromFloats(1, 1, 1),
        i._PivotTmpVector.subtractInPlace(e.scaling),
        i._PivotTmpVector.multiplyInPlace(i._PivotTranslation),
        e.position.subtractInPlace(i._PivotTmpVector)),
        this._PivotCached--
    }
    ,
    i._PivotCached = 0,
    i._OldPivotPoint = new Vector3,
    i._PivotTranslation = new Vector3,
    i._PivotTmpVector = new Vector3,
    i._PivotPostMultiplyPivotMatrix = !1,
    i
}()
  , PointerDragBehavior = function() {
    function i(e) {
        this._useAlternatePickedPointAboveMaxDragAngleDragSpeed = -1.1,
        this.maxDragAngle = 0,
        this._useAlternatePickedPointAboveMaxDragAngle = !1,
        this.currentDraggingPointerId = -1,
        this.dragging = !1,
        this.dragDeltaRatio = .2,
        this.updateDragPlane = !0,
        this._debugMode = !1,
        this._moving = !1,
        this.onDragObservable = new Observable,
        this.onDragStartObservable = new Observable,
        this.onDragEndObservable = new Observable,
        this.onEnabledObservable = new Observable,
        this.moveAttached = !0,
        this._enabled = !0,
        this.startAndReleaseDragOnPointerEvents = !0,
        this.detachCameraControls = !0,
        this.useObjectOrientationForDragging = !0,
        this.validateDrag = function(r) {
            return !0
        }
        ,
        this._tmpVector = new Vector3(0,0,0),
        this._alternatePickedPoint = new Vector3(0,0,0),
        this._worldDragAxis = new Vector3(0,0,0),
        this._targetPosition = new Vector3(0,0,0),
        this._attachedToElement = !1,
        this._startDragRay = new Ray(new Vector3,new Vector3),
        this._lastPointerRay = {},
        this._dragDelta = new Vector3,
        this._pointA = new Vector3(0,0,0),
        this._pointC = new Vector3(0,0,0),
        this._localAxis = new Vector3(0,0,0),
        this._lookAt = new Vector3(0,0,0),
        this._options = e || {};
        var t = 0;
        if (this._options.dragAxis && t++,
        this._options.dragPlaneNormal && t++,
        t > 1)
            throw "Multiple drag modes specified in dragBehavior options. Only one expected"
    }
    return Object.defineProperty(i.prototype, "currentDraggingPointerID", {
        get: function() {
            return this.currentDraggingPointerId
        },
        set: function(e) {
            this.currentDraggingPointerId = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "enabled", {
        get: function() {
            return this._enabled
        },
        set: function(e) {
            e != this._enabled && this.onEnabledObservable.notifyObservers(e),
            this._enabled = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "options", {
        get: function() {
            return this._options
        },
        set: function(e) {
            this._options = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "name", {
        get: function() {
            return "PointerDrag"
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.init = function() {}
    ,
    i.prototype.attach = function(e, t) {
        var r = this;
        this._scene = e.getScene(),
        e.isNearGrabbable = !0,
        this.attachedNode = e,
        i._planeScene || (this._debugMode ? i._planeScene = this._scene : (i._planeScene = new Scene(this._scene.getEngine(),{
            virtual: !0
        }),
        i._planeScene.detachControl(),
        this._scene.onDisposeObservable.addOnce(function() {
            i._planeScene.dispose(),
            i._planeScene = null
        }))),
        this._dragPlane = CreatePlane("pointerDragPlane", {
            size: this._debugMode ? 1 : 1e4,
            updatable: !1,
            sideOrientation: Mesh.DOUBLESIDE
        }, i._planeScene),
        this.lastDragPosition = new Vector3(0,0,0);
        var n = t || function(o) {
            return r.attachedNode == o || o.isDescendantOf(r.attachedNode)
        }
        ;
        this._pointerObserver = this._scene.onPointerObservable.add(function(o, a) {
            if (!r.enabled) {
                r._attachedToElement && r.releaseDrag();
                return
            }
            if (o.type == PointerEventTypes.POINTERDOWN)
                r.startAndReleaseDragOnPointerEvents && !r.dragging && o.pickInfo && o.pickInfo.hit && o.pickInfo.pickedMesh && o.pickInfo.pickedPoint && o.pickInfo.ray && n(o.pickInfo.pickedMesh) && r._startDrag(o.event.pointerId, o.pickInfo.ray, o.pickInfo.pickedPoint);
            else if (o.type == PointerEventTypes.POINTERUP)
                r.startAndReleaseDragOnPointerEvents && r.currentDraggingPointerId == o.event.pointerId && r.releaseDrag();
            else if (o.type == PointerEventTypes.POINTERMOVE) {
                var s = o.event.pointerId;
                if (r.currentDraggingPointerId === i._AnyMouseId && s !== i._AnyMouseId) {
                    var l = o.event
                      , u = l.pointerType === "mouse" || !r._scene.getEngine().hostInformation.isMobile && l instanceof MouseEvent;
                    u && (r._lastPointerRay[r.currentDraggingPointerId] && (r._lastPointerRay[s] = r._lastPointerRay[r.currentDraggingPointerId],
                    delete r._lastPointerRay[r.currentDraggingPointerId]),
                    r.currentDraggingPointerId = s)
                }
                r._lastPointerRay[s] || (r._lastPointerRay[s] = new Ray(new Vector3,new Vector3)),
                o.pickInfo && o.pickInfo.ray && (r._lastPointerRay[s].origin.copyFrom(o.pickInfo.ray.origin),
                r._lastPointerRay[s].direction.copyFrom(o.pickInfo.ray.direction),
                r.currentDraggingPointerId == s && r.dragging && r._moveDrag(o.pickInfo.ray))
            }
        }),
        this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function() {
            r._moving && r.moveAttached && (PivotTools._RemoveAndStorePivotPoint(r.attachedNode),
            r._targetPosition.subtractToRef(r.attachedNode.absolutePosition, r._tmpVector),
            r._tmpVector.scaleInPlace(r.dragDeltaRatio),
            r.attachedNode.getAbsolutePosition().addToRef(r._tmpVector, r._tmpVector),
            r.validateDrag(r._tmpVector) && r.attachedNode.setAbsolutePosition(r._tmpVector),
            PivotTools._RestorePivotPoint(r.attachedNode))
        })
    }
    ,
    i.prototype.releaseDrag = function() {
        if (this.dragging && (this.dragging = !1,
        this.onDragEndObservable.notifyObservers({
            dragPlanePoint: this.lastDragPosition,
            pointerId: this.currentDraggingPointerId
        })),
        this.currentDraggingPointerId = -1,
        this._moving = !1,
        this.detachCameraControls && this._attachedToElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
            if (this._scene.activeCamera.getClassName() === "ArcRotateCamera") {
                var e = this._scene.activeCamera;
                e.attachControl(e.inputs ? e.inputs.noPreventDefault : !0, e._useCtrlForPanning, e._panningMouseButton)
            } else
                this._scene.activeCamera.attachControl(this._scene.activeCamera.inputs ? this._scene.activeCamera.inputs.noPreventDefault : !0);
            this._attachedToElement = !1
        }
    }
    ,
    i.prototype.startDrag = function(e, t, r) {
        e === void 0 && (e = i._AnyMouseId),
        this._startDrag(e, t, r);
        var n = this._lastPointerRay[e];
        e === i._AnyMouseId && (n = this._lastPointerRay[Object.keys(this._lastPointerRay)[0]]),
        n && this._moveDrag(n)
    }
    ,
    i.prototype._startDrag = function(e, t, r) {
        if (!(!this._scene.activeCamera || this.dragging || !this.attachedNode)) {
            PivotTools._RemoveAndStorePivotPoint(this.attachedNode),
            t ? (this._startDragRay.direction.copyFrom(t.direction),
            this._startDragRay.origin.copyFrom(t.origin)) : (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, r || this._tmpVector);
            var n = this._pickWithRayOnDragPlane(this._startDragRay);
            n && (this.dragging = !0,
            this.currentDraggingPointerId = e,
            this.lastDragPosition.copyFrom(n),
            this.onDragStartObservable.notifyObservers({
                dragPlanePoint: n,
                pointerId: this.currentDraggingPointerId
            }),
            this._targetPosition.copyFrom(this.attachedNode.getAbsolutePosition()),
            this.detachCameraControls && this._scene.activeCamera && this._scene.activeCamera.inputs && !this._scene.activeCamera.leftCamera && (this._scene.activeCamera.inputs.attachedToElement ? (this._scene.activeCamera.detachControl(),
            this._attachedToElement = !0) : this._attachedToElement = !1)),
            PivotTools._RestorePivotPoint(this.attachedNode)
        }
    }
    ,
    i.prototype._moveDrag = function(e) {
        this._moving = !0;
        var t = this._pickWithRayOnDragPlane(e);
        if (t) {
            this.updateDragPlane && this._updateDragPlanePosition(e, t);
            var r = 0;
            this._options.dragAxis ? (this.useObjectOrientationForDragging ? Vector3.TransformCoordinatesToRef(this._options.dragAxis, this.attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis) : this._worldDragAxis.copyFrom(this._options.dragAxis),
            t.subtractToRef(this.lastDragPosition, this._tmpVector),
            r = Vector3.Dot(this._tmpVector, this._worldDragAxis),
            this._worldDragAxis.scaleToRef(r, this._dragDelta)) : (r = this._dragDelta.length(),
            t.subtractToRef(this.lastDragPosition, this._dragDelta)),
            this._targetPosition.addInPlace(this._dragDelta),
            this.onDragObservable.notifyObservers({
                dragDistance: r,
                delta: this._dragDelta,
                dragPlanePoint: t,
                dragPlaneNormal: this._dragPlane.forward,
                pointerId: this.currentDraggingPointerId
            }),
            this.lastDragPosition.copyFrom(t)
        }
    }
    ,
    i.prototype._pickWithRayOnDragPlane = function(e) {
        var t = this;
        if (!e)
            return null;
        var r = Math.acos(Vector3.Dot(this._dragPlane.forward, e.direction));
        if (r > Math.PI / 2 && (r = Math.PI - r),
        this.maxDragAngle > 0 && r > this.maxDragAngle)
            if (this._useAlternatePickedPointAboveMaxDragAngle) {
                this._tmpVector.copyFrom(e.direction),
                this.attachedNode.absolutePosition.subtractToRef(e.origin, this._alternatePickedPoint),
                this._alternatePickedPoint.normalize(),
                this._alternatePickedPoint.scaleInPlace(this._useAlternatePickedPointAboveMaxDragAngleDragSpeed * Vector3.Dot(this._alternatePickedPoint, this._tmpVector)),
                this._tmpVector.addInPlace(this._alternatePickedPoint);
                var n = Vector3.Dot(this._dragPlane.forward, this._tmpVector);
                return this._dragPlane.forward.scaleToRef(-n, this._alternatePickedPoint),
                this._alternatePickedPoint.addInPlace(this._tmpVector),
                this._alternatePickedPoint.addInPlace(this.attachedNode.absolutePosition),
                this._alternatePickedPoint
            } else
                return null;
        var o = i._planeScene.pickWithRay(e, function(a) {
            return a == t._dragPlane
        });
        return o && o.hit && o.pickedMesh && o.pickedPoint ? o.pickedPoint : null
    }
    ,
    i.prototype._updateDragPlanePosition = function(e, t) {
        this._pointA.copyFrom(t),
        this._options.dragAxis ? (this.useObjectOrientationForDragging ? Vector3.TransformCoordinatesToRef(this._options.dragAxis, this.attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis),
        e.origin.subtractToRef(this._pointA, this._pointC),
        this._pointC.normalize(),
        Math.abs(Vector3.Dot(this._localAxis, this._pointC)) > .999 ? Math.abs(Vector3.Dot(Vector3.UpReadOnly, this._pointC)) > .999 ? this._lookAt.copyFrom(Vector3.Right()) : this._lookAt.copyFrom(Vector3.UpReadOnly) : (Vector3.CrossToRef(this._localAxis, this._pointC, this._lookAt),
        Vector3.CrossToRef(this._localAxis, this._lookAt, this._lookAt),
        this._lookAt.normalize()),
        this._dragPlane.position.copyFrom(this._pointA),
        this._pointA.addToRef(this._lookAt, this._lookAt),
        this._dragPlane.lookAt(this._lookAt)) : this._options.dragPlaneNormal ? (this.useObjectOrientationForDragging ? 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.addToRef(this._localAxis, this._lookAt),
        this._dragPlane.lookAt(this._lookAt)) : (this._dragPlane.position.copyFrom(this._pointA),
        this._dragPlane.lookAt(e.origin)),
        this._dragPlane.position.copyFrom(this.attachedNode.getAbsolutePosition()),
        this._dragPlane.computeWorldMatrix(!0)
    }
    ,
    i.prototype.detach = function() {
        this.attachedNode.isNearGrabbable = !1,
        this._pointerObserver && this._scene.onPointerObservable.remove(this._pointerObserver),
        this._beforeRenderObserver && this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver),
        this._dragPlane.dispose(),
        this.releaseDrag()
    }
    ,
    i._AnyMouseId = -2,
    i
}()
  , PlaneRotationGizmo = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a, s, l) {
        r === void 0 && (r = Color3.Gray()),
        n === void 0 && (n = UtilityLayerRenderer.DefaultUtilityLayer),
        o === void 0 && (o = 32),
        a === void 0 && (a = null),
        l === void 0 && (l = 1);
        var u, c = i.call(this, n) || this;
        c._pointerObserver = null,
        c.snapDistance = 0,
        c.onSnapObservable = new Observable,
        c.angle = 0,
        c._isEnabled = !0,
        c._parent = null,
        c._dragging = !1,
        c._angles = new Vector3,
        c._parent = a,
        c._coloredMaterial = new StandardMaterial("",n.utilityLayerScene),
        c._coloredMaterial.diffuseColor = r,
        c._coloredMaterial.specularColor = r.subtract(new Color3(.1,.1,.1)),
        c._hoverMaterial = new StandardMaterial("",n.utilityLayerScene),
        c._hoverMaterial.diffuseColor = Color3.Yellow(),
        c._disableMaterial = new StandardMaterial("",n.utilityLayerScene),
        c._disableMaterial.diffuseColor = Color3.Gray(),
        c._disableMaterial.alpha = .4,
        c._gizmoMesh = new Mesh("",n.utilityLayerScene);
        var h = c._createGizmoMesh(c._gizmoMesh, l, o)
          , f = h.rotationMesh
          , d = h.collider;
        c._rotationDisplayPlane = CreatePlane("rotationDisplay", {
            size: .6,
            updatable: !1
        }, c.gizmoLayer.utilityLayerScene),
        c._rotationDisplayPlane.rotation.z = Math.PI * .5,
        c._rotationDisplayPlane.parent = c._gizmoMesh,
        c._rotationDisplayPlane.setEnabled(!1),
        Effect.ShadersStore.rotationGizmoVertexShader = e._rotationGizmoVertexShader,
        Effect.ShadersStore.rotationGizmoFragmentShader = e._rotationGizmoFragmentShader,
        c._rotationShaderMaterial = new ShaderMaterial("shader",c.gizmoLayer.utilityLayerScene,{
            vertex: "rotationGizmo",
            fragment: "rotationGizmo"
        },{
            attributes: ["position", "uv"],
            uniforms: ["worldViewProjection", "angles"]
        }),
        c._rotationShaderMaterial.backFaceCulling = !1,
        c._rotationDisplayPlane.material = c._rotationShaderMaterial,
        c._rotationDisplayPlane.visibility = .999,
        c._gizmoMesh.lookAt(c._rootMesh.position.add(t)),
        c._rootMesh.addChild(c._gizmoMesh),
        c._gizmoMesh.scaling.scaleInPlace(1 / 3),
        c.dragBehavior = new PointerDragBehavior({
            dragPlaneNormal: t
        }),
        c.dragBehavior.moveAttached = !1,
        c.dragBehavior.maxDragAngle = e.MaxDragAngle,
        c.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = !0,
        c._rootMesh.addBehavior(c.dragBehavior);
        var _ = new Vector3
          , g = new Matrix
          , m = new Vector3
          , v = new Vector3;
        c.dragBehavior.onDragStartObservable.add(function(P) {
            c.attachedNode && (_.copyFrom(P.dragPlanePoint),
            c._rotationDisplayPlane.setEnabled(!0),
            c._rotationDisplayPlane.getWorldMatrix().invertToRef(g),
            Vector3.TransformCoordinatesToRef(P.dragPlanePoint, g, _),
            c._angles.x = Math.atan2(_.y, _.x) + Math.PI,
            c._angles.y = 0,
            c._angles.z = c.updateGizmoRotationToMatchAttachedMesh ? 1 : 0,
            c._dragging = !0,
            _.copyFrom(P.dragPlanePoint),
            c._rotationShaderMaterial.setVector3("angles", c._angles),
            c.angle = 0)
        }),
        c.dragBehavior.onDragEndObservable.add(function() {
            c._dragging = !1,
            c._rotationDisplayPlane.setEnabled(!1)
        });
        var y = {
            snapDistance: 0
        }
          , b = 0
          , T = new Matrix
          , C = new Quaternion;
        c.dragBehavior.onDragObservable.add(function(P) {
            if (c.attachedNode) {
                var R = new Vector3(1,1,1)
                  , M = new Quaternion(0,0,0,1)
                  , x = new Vector3(0,0,0);
                c._handlePivot(),
                c.attachedNode.getWorldMatrix().decompose(R, M, x);
                var I = P.dragPlanePoint.subtract(x).normalize()
                  , w = _.subtract(x).normalize()
                  , O = Vector3.Cross(I, w)
                  , D = Vector3.Dot(I, w)
                  , F = Math.atan2(O.length(), D);
                m.copyFrom(t),
                v.copyFrom(t),
                c.updateGizmoRotationToMatchAttachedMesh && (M.toRotationMatrix(g),
                v = Vector3.TransformCoordinates(m, g));
                var V = !1;
                if (n.utilityLayerScene.activeCamera) {
                    var N = n.utilityLayerScene.activeCamera.position.subtract(x).normalize();
                    Vector3.Dot(N, v) > 0 && (m.scaleInPlace(-1),
                    v.scaleInPlace(-1),
                    V = !0)
                }
                var L = Vector3.Dot(v, O) > 0;
                L && (F = -F);
                var k = !1;
                if (c.snapDistance != 0)
                    if (b += F,
                    Math.abs(b) > c.snapDistance) {
                        var U = Math.floor(Math.abs(b) / c.snapDistance);
                        b < 0 && (U *= -1),
                        b = b % c.snapDistance,
                        F = c.snapDistance * U,
                        k = !0
                    } else
                        F = 0;
                var z = Math.sin(F / 2);
                if (C.set(m.x * z, m.y * z, m.z * z, Math.cos(F / 2)),
                T.determinant() > 0) {
                    var H = new Vector3;
                    C.toEulerAnglesToRef(H),
                    Quaternion.RotationYawPitchRollToRef(H.y, -H.x, -H.z, C)
                }
                c.updateGizmoRotationToMatchAttachedMesh ? M.multiplyToRef(C, M) : C.multiplyToRef(M, M),
                c.attachedNode.getWorldMatrix().copyFrom(Matrix.Compose(R, M, x)),
                _.copyFrom(P.dragPlanePoint),
                k && (y.snapDistance = F,
                c.onSnapObservable.notifyObservers(y)),
                c._angles.y += F,
                c.angle += V ? -F : F,
                c._rotationShaderMaterial.setVector3("angles", c._angles),
                c._matrixChanged()
            }
        });
        var A = n._getSharedGizmoLight();
        A.includedOnlyMeshes = A.includedOnlyMeshes.concat(c._rootMesh.getChildMeshes(!1));
        var S = {
            colliderMeshes: [d],
            gizmoMeshes: [f],
            material: c._coloredMaterial,
            hoverMaterial: c._hoverMaterial,
            disableMaterial: c._disableMaterial,
            active: !1,
            dragBehavior: c.dragBehavior
        };
        return (u = c._parent) === null || u === void 0 || u.addToAxisCache(c._gizmoMesh, S),
        c._pointerObserver = n.utilityLayerScene.onPointerObservable.add(function(P) {
            var R;
            if (!c._customMeshSet && (c.dragBehavior.maxDragAngle = e.MaxDragAngle,
            c._isHovered = S.colliderMeshes.indexOf((R = P == null ? void 0 : P.pickInfo) === null || R === void 0 ? void 0 : R.pickedMesh) != -1,
            !c._parent)) {
                var M = S.dragBehavior.enabled ? c._isHovered || c._dragging ? c._hoverMaterial : c._coloredMaterial : c._disableMaterial;
                c._setGizmoMeshMaterial(S.gizmoMeshes, M)
            }
        }),
        c.dragBehavior.onEnabledObservable.add(function(P) {
            c._setGizmoMeshMaterial(S.gizmoMeshes, P ? c._coloredMaterial : c._disableMaterial)
        }),
        c
    }
    return e.prototype._createGizmoMesh = function(t, r, n) {
        var o = CreateTorus("ignore", {
            diameter: .6,
            thickness: .03 * r,
            tessellation: n
        }, this.gizmoLayer.utilityLayerScene);
        o.visibility = 0;
        var a = CreateTorus("", {
            diameter: .6,
            thickness: .005 * r,
            tessellation: n
        }, this.gizmoLayer.utilityLayerScene);
        return a.material = this._coloredMaterial,
        a.rotation.x = Math.PI / 2,
        o.rotation.x = Math.PI / 2,
        t.addChild(a),
        t.addChild(o),
        {
            rotationMesh: a,
            collider: o
        }
    }
    ,
    e.prototype._attachedNodeChanged = function(t) {
        this.dragBehavior && (this.dragBehavior.enabled = !!t)
    }
    ,
    Object.defineProperty(e.prototype, "isEnabled", {
        get: function() {
            return this._isEnabled
        },
        set: function(t) {
            this._isEnabled = t,
            t ? this._parent && (this.attachedMesh = this._parent.attachedMesh) : this.attachedMesh = null
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.dispose = function() {
        this.onSnapObservable.clear(),
        this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),
        this.dragBehavior.detach(),
        this._gizmoMesh && this._gizmoMesh.dispose(),
        this._rotationDisplayPlane && this._rotationDisplayPlane.dispose(),
        this._rotationShaderMaterial && this._rotationShaderMaterial.dispose(),
        [this._coloredMaterial, this._hoverMaterial, this._disableMaterial].forEach(function(t) {
            t && t.dispose()
        }),
        i.prototype.dispose.call(this)
    }
    ,
    e.MaxDragAngle = Math.PI * 9 / 20,
    e._rotationGizmoVertexShader = `
        precision highp float;
        attribute vec3 position;
        attribute vec2 uv;
        uniform mat4 worldViewProjection;
        varying vec3 vPosition;
        varying vec2 vUV;
        void main(void) {
            gl_Position = worldViewProjection * vec4(position, 1.0);
            vUV = uv;
        }`,
    e._rotationGizmoFragmentShader = `
        precision highp float;
        varying vec2 vUV;
        varying vec3 vPosition;
        uniform vec3 angles;
        #define twopi 6.283185307
        void main(void) {
            vec2 uv = vUV - vec2(0.5);
            float angle = atan(uv.y, uv.x) + 3.141592;
            float delta = gl_FrontFacing ? angles.y : -angles.y;
            float begin = angles.x - delta * angles.z;
            float start = (begin < (begin + delta)) ? begin : (begin + delta);
            float end = (begin > (begin + delta)) ? begin : (begin + delta);
            float len = sqrt(dot(uv,uv));
            float opacity = 1. - step(0.5, len);

            float base = abs(floor(start / twopi)) * twopi;
            start += base;
            end += base;

            float intensity = 0.;
            for (int i = 0; i < 5; i++)
            {
                intensity += max(step(start, angle) - step(end, angle), 0.);
                angle += twopi;
            }
            gl_FragColor = vec4(1.,1.,0., min(intensity * 0.25, 0.8)) * opacity;
        }`,
    e
}(Gizmo)
  , RotationGizmo = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a, s) {
        t === void 0 && (t = UtilityLayerRenderer.DefaultUtilityLayer),
        r === void 0 && (r = 32),
        n === void 0 && (n = !1),
        o === void 0 && (o = 1);
        var l = i.call(this, t) || this;
        l.onDragStartObservable = new Observable,
        l.onDragEndObservable = new Observable,
        l._observables = [],
        l._gizmoAxisCache = new Map;
        var u = s && s.xOptions && s.xOptions.color ? s.xOptions.color : Color3.Red().scale(.5)
          , c = s && s.yOptions && s.yOptions.color ? s.yOptions.color : Color3.Green().scale(.5)
          , h = s && s.zOptions && s.zOptions.color ? s.zOptions.color : Color3.Blue().scale(.5);
        return l.xGizmo = new PlaneRotationGizmo(new Vector3(1,0,0),u,t,r,l,n,o),
        l.yGizmo = new PlaneRotationGizmo(new Vector3(0,1,0),c,t,r,l,n,o),
        l.zGizmo = new PlaneRotationGizmo(new Vector3(0,0,1),h,t,r,l,n,o),
        [l.xGizmo, l.yGizmo, l.zGizmo].forEach(function(f) {
            s && s.updateScale != null && (f.updateScale = s.updateScale),
            f.dragBehavior.onDragStartObservable.add(function() {
                l.onDragStartObservable.notifyObservers({})
            }),
            f.dragBehavior.onDragEndObservable.add(function() {
                l.onDragEndObservable.notifyObservers({})
            })
        }),
        l.attachedMesh = null,
        l.attachedNode = null,
        a ? a.addToAxisCache(l._gizmoAxisCache) : Gizmo.GizmoAxisPointerObserver(t, l._gizmoAxisCache),
        l
    }
    return Object.defineProperty(e.prototype, "attachedMesh", {
        get: function() {
            return this._meshAttached
        },
        set: function(t) {
            this._meshAttached = t,
            this._nodeAttached = t,
            this._checkBillboardTransform(),
            [this.xGizmo, this.yGizmo, this.zGizmo].forEach(function(r) {
                r.isEnabled ? r.attachedMesh = t : r.attachedMesh = null
            })
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "attachedNode", {
        get: function() {
            return this._nodeAttached
        },
        set: function(t) {
            this._meshAttached = null,
            this._nodeAttached = t,
            this._checkBillboardTransform(),
            [this.xGizmo, this.yGizmo, this.zGizmo].forEach(function(r) {
                r.isEnabled ? r.attachedNode = t : r.attachedNode = null
            })
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._checkBillboardTransform = function() {
        this._nodeAttached && this._nodeAttached.billboardMode && console.log("Rotation Gizmo will not work with transforms in billboard mode.")
    }
    ,
    Object.defineProperty(e.prototype, "isHovered", {
        get: function() {
            var t = !1;
            return [this.xGizmo, this.yGizmo, this.zGizmo].forEach(function(r) {
                t = t || r.isHovered
            }),
            t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "updateGizmoRotationToMatchAttachedMesh", {
        get: function() {
            return this.xGizmo.updateGizmoRotationToMatchAttachedMesh
        },
        set: function(t) {
            this.xGizmo && (this.xGizmo.updateGizmoRotationToMatchAttachedMesh = t,
            this.yGizmo.updateGizmoRotationToMatchAttachedMesh = t,
            this.zGizmo.updateGizmoRotationToMatchAttachedMesh = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "snapDistance", {
        get: function() {
            return this.xGizmo.snapDistance
        },
        set: function(t) {
            this.xGizmo && (this.xGizmo.snapDistance = t,
            this.yGizmo.snapDistance = t,
            this.zGizmo.snapDistance = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "scaleRatio", {
        get: function() {
            return this.xGizmo.scaleRatio
        },
        set: function(t) {
            this.xGizmo && (this.xGizmo.scaleRatio = t,
            this.yGizmo.scaleRatio = t,
            this.zGizmo.scaleRatio = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.addToAxisCache = function(t, r) {
        this._gizmoAxisCache.set(t, r)
    }
    ,
    e.prototype.dispose = function() {
        var t = this;
        this.xGizmo.dispose(),
        this.yGizmo.dispose(),
        this.zGizmo.dispose(),
        this.onDragStartObservable.clear(),
        this.onDragEndObservable.clear(),
        this._observables.forEach(function(r) {
            t.gizmoLayer.utilityLayerScene.onPointerObservable.remove(r)
        })
    }
    ,
    e.prototype.setCustomMesh = function(t) {
        Logger$2.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)")
    }
    ,
    e
}(Gizmo)
  , AxisDragGizmo = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a) {
        r === void 0 && (r = Color3.Gray()),
        n === void 0 && (n = UtilityLayerRenderer.DefaultUtilityLayer),
        o === void 0 && (o = null),
        a === void 0 && (a = 1);
        var s, l = i.call(this, n) || this;
        l._pointerObserver = null,
        l.snapDistance = 0,
        l.onSnapObservable = new Observable,
        l._isEnabled = !0,
        l._parent = null,
        l._dragging = !1,
        l._parent = o,
        l._coloredMaterial = new StandardMaterial("",n.utilityLayerScene),
        l._coloredMaterial.diffuseColor = r,
        l._coloredMaterial.specularColor = r.subtract(new Color3(.1,.1,.1)),
        l._hoverMaterial = new StandardMaterial("",n.utilityLayerScene),
        l._hoverMaterial.diffuseColor = Color3.Yellow(),
        l._disableMaterial = new StandardMaterial("",n.utilityLayerScene),
        l._disableMaterial.diffuseColor = Color3.Gray(),
        l._disableMaterial.alpha = .4;
        var u = e._CreateArrow(n.utilityLayerScene, l._coloredMaterial, a)
          , c = e._CreateArrow(n.utilityLayerScene, l._coloredMaterial, a + 4, !0);
        l._gizmoMesh = new Mesh("",n.utilityLayerScene),
        l._gizmoMesh.addChild(u),
        l._gizmoMesh.addChild(c),
        l._gizmoMesh.lookAt(l._rootMesh.position.add(t)),
        l._gizmoMesh.scaling.scaleInPlace(1 / 3),
        l._gizmoMesh.parent = l._rootMesh;
        var h = 0
          , f = new Vector3
          , d = new Vector3
          , _ = {
            snapDistance: 0
        };
        l.dragBehavior = new PointerDragBehavior({
            dragAxis: t
        }),
        l.dragBehavior.moveAttached = !1,
        l._rootMesh.addBehavior(l.dragBehavior),
        l.dragBehavior.onDragObservable.add(function(v) {
            if (l.attachedNode) {
                l._handlePivot();
                var y = !1;
                if (l.snapDistance == 0)
                    l.attachedNode.getWorldMatrix().getTranslationToRef(d),
                    d.addInPlace(v.delta),
                    l.dragBehavior.validateDrag(d) && (l.attachedNode.position && l.attachedNode.position.addInPlaceFromFloats(v.delta.x, v.delta.y, v.delta.z),
                    l.attachedNode.getWorldMatrix().addTranslationFromFloats(v.delta.x, v.delta.y, v.delta.z),
                    l.attachedNode.updateCache(),
                    y = !0);
                else if (h += v.dragDistance,
                Math.abs(h) > l.snapDistance) {
                    var b = Math.floor(Math.abs(h) / l.snapDistance);
                    h = h % l.snapDistance,
                    v.delta.normalizeToRef(f),
                    f.scaleInPlace(l.snapDistance * b),
                    l.attachedNode.getWorldMatrix().getTranslationToRef(d),
                    d.addInPlace(f),
                    l.dragBehavior.validateDrag(d) && (l.attachedNode.getWorldMatrix().addTranslationFromFloats(f.x, f.y, f.z),
                    l.attachedNode.updateCache(),
                    _.snapDistance = l.snapDistance * b,
                    l.onSnapObservable.notifyObservers(_),
                    y = !0)
                }
                y && l._matrixChanged()
            }
        }),
        l.dragBehavior.onDragStartObservable.add(function() {
            l._dragging = !0
        }),
        l.dragBehavior.onDragEndObservable.add(function() {
            l._dragging = !1
        });
        var g = n._getSharedGizmoLight();
        g.includedOnlyMeshes = g.includedOnlyMeshes.concat(l._rootMesh.getChildMeshes(!1));
        var m = {
            gizmoMeshes: u.getChildMeshes(),
            colliderMeshes: c.getChildMeshes(),
            material: l._coloredMaterial,
            hoverMaterial: l._hoverMaterial,
            disableMaterial: l._disableMaterial,
            active: !1,
            dragBehavior: l.dragBehavior
        };
        return (s = l._parent) === null || s === void 0 || s.addToAxisCache(c, m),
        l._pointerObserver = n.utilityLayerScene.onPointerObservable.add(function(v) {
            var y;
            if (!l._customMeshSet && (l._isHovered = m.colliderMeshes.indexOf((y = v == null ? void 0 : v.pickInfo) === null || y === void 0 ? void 0 : y.pickedMesh) != -1,
            !l._parent)) {
                var b = l.dragBehavior.enabled ? l._isHovered || l._dragging ? l._hoverMaterial : l._coloredMaterial : l._disableMaterial;
                l._setGizmoMeshMaterial(m.gizmoMeshes, b)
            }
        }),
        l.dragBehavior.onEnabledObservable.add(function(v) {
            l._setGizmoMeshMaterial(m.gizmoMeshes, v ? m.material : m.disableMaterial)
        }),
        l
    }
    return e._CreateArrow = function(t, r, n, o) {
        n === void 0 && (n = 1),
        o === void 0 && (o = !1);
        var a = new TransformNode("arrow",t)
          , s = CreateCylinder("cylinder", {
            diameterTop: 0,
            height: .075,
            diameterBottom: .0375 * (1 + (n - 1) / 4),
            tessellation: 96
        }, t)
          , l = CreateCylinder("cylinder", {
            diameterTop: .005 * n,
            height: .275,
            diameterBottom: .005 * n,
            tessellation: 96
        }, t);
        return s.parent = a,
        s.material = r,
        s.rotation.x = Math.PI / 2,
        s.position.z += .3,
        l.parent = a,
        l.material = r,
        l.position.z += .275 / 2,
        l.rotation.x = Math.PI / 2,
        o && (l.visibility = 0,
        s.visibility = 0),
        a
    }
    ,
    e._CreateArrowInstance = function(t, r) {
        for (var n = new TransformNode("arrow",t), o = 0, a = r.getChildMeshes(); o < a.length; o++) {
            var s = a[o]
              , l = s.createInstance(s.name);
            l.parent = n
        }
        return n
    }
    ,
    e.prototype._attachedNodeChanged = function(t) {
        this.dragBehavior && (this.dragBehavior.enabled = !!t)
    }
    ,
    Object.defineProperty(e.prototype, "isEnabled", {
        get: function() {
            return this._isEnabled
        },
        set: function(t) {
            this._isEnabled = t,
            t ? this._parent && (this.attachedMesh = this._parent.attachedMesh,
            this.attachedNode = this._parent.attachedNode) : (this.attachedMesh = null,
            this.attachedNode = null)
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.dispose = function() {
        this.onSnapObservable.clear(),
        this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),
        this.dragBehavior.detach(),
        this._gizmoMesh && this._gizmoMesh.dispose(),
        [this._coloredMaterial, this._hoverMaterial, this._disableMaterial].forEach(function(t) {
            t && t.dispose()
        }),
        i.prototype.dispose.call(this)
    }
    ,
    e
}(Gizmo)
  , PlaneDragGizmo = function(i) {
    __extends(e, i);
    function e(t, r, n, o) {
        r === void 0 && (r = Color3.Gray()),
        n === void 0 && (n = UtilityLayerRenderer.DefaultUtilityLayer),
        o === void 0 && (o = null);
        var a, s = i.call(this, n) || this;
        s._pointerObserver = null,
        s.snapDistance = 0,
        s.onSnapObservable = new Observable,
        s._isEnabled = !1,
        s._parent = null,
        s._dragging = !1,
        s._parent = o,
        s._coloredMaterial = new StandardMaterial("",n.utilityLayerScene),
        s._coloredMaterial.diffuseColor = r,
        s._coloredMaterial.specularColor = r.subtract(new Color3(.1,.1,.1)),
        s._hoverMaterial = new StandardMaterial("",n.utilityLayerScene),
        s._hoverMaterial.diffuseColor = Color3.Yellow(),
        s._disableMaterial = new StandardMaterial("",n.utilityLayerScene),
        s._disableMaterial.diffuseColor = Color3.Gray(),
        s._disableMaterial.alpha = .4,
        s._gizmoMesh = e._CreatePlane(n.utilityLayerScene, s._coloredMaterial),
        s._gizmoMesh.lookAt(s._rootMesh.position.add(t)),
        s._gizmoMesh.scaling.scaleInPlace(1 / 3),
        s._gizmoMesh.parent = s._rootMesh;
        var l = 0
          , u = new Vector3
          , c = {
            snapDistance: 0
        };
        s.dragBehavior = new PointerDragBehavior({
            dragPlaneNormal: t
        }),
        s.dragBehavior.moveAttached = !1,
        s._rootMesh.addBehavior(s.dragBehavior),
        s.dragBehavior.onDragObservable.add(function(d) {
            if (s.attachedNode) {
                if (s._handlePivot(),
                s.snapDistance == 0)
                    s.attachedNode.getWorldMatrix().addTranslationFromFloats(d.delta.x, d.delta.y, d.delta.z);
                else if (l += d.dragDistance,
                Math.abs(l) > s.snapDistance) {
                    var _ = Math.floor(Math.abs(l) / s.snapDistance);
                    l = l % s.snapDistance,
                    d.delta.normalizeToRef(u),
                    u.scaleInPlace(s.snapDistance * _),
                    s.attachedNode.getWorldMatrix().addTranslationFromFloats(u.x, u.y, u.z),
                    c.snapDistance = s.snapDistance * _,
                    s.onSnapObservable.notifyObservers(c)
                }
                s._matrixChanged()
            }
        }),
        s.dragBehavior.onDragStartObservable.add(function() {
            s._dragging = !0
        }),
        s.dragBehavior.onDragEndObservable.add(function() {
            s._dragging = !1
        });
        var h = n._getSharedGizmoLight();
        h.includedOnlyMeshes = h.includedOnlyMeshes.concat(s._rootMesh.getChildMeshes(!1));
        var f = {
            gizmoMeshes: s._gizmoMesh.getChildMeshes(),
            colliderMeshes: s._gizmoMesh.getChildMeshes(),
            material: s._coloredMaterial,
            hoverMaterial: s._hoverMaterial,
            disableMaterial: s._disableMaterial,
            active: !1,
            dragBehavior: s.dragBehavior
        };
        return (a = s._parent) === null || a === void 0 || a.addToAxisCache(s._gizmoMesh, f),
        s._pointerObserver = n.utilityLayerScene.onPointerObservable.add(function(d) {
            var _;
            if (!s._customMeshSet && (s._isHovered = f.colliderMeshes.indexOf((_ = d == null ? void 0 : d.pickInfo) === null || _ === void 0 ? void 0 : _.pickedMesh) != -1,
            !s._parent)) {
                var g = f.dragBehavior.enabled ? s._isHovered || s._dragging ? s._hoverMaterial : s._coloredMaterial : s._disableMaterial;
                s._setGizmoMeshMaterial(f.gizmoMeshes, g)
            }
        }),
        s.dragBehavior.onEnabledObservable.add(function(d) {
            s._setGizmoMeshMaterial(f.gizmoMeshes, d ? s._coloredMaterial : s._disableMaterial)
        }),
        s
    }
    return e._CreatePlane = function(t, r) {
        var n = new TransformNode("plane",t)
          , o = CreatePlane("dragPlane", {
            width: .1375,
            height: .1375,
            sideOrientation: 2
        }, t);
        return o.material = r,
        o.parent = n,
        n
    }
    ,
    e.prototype._attachedNodeChanged = function(t) {
        this.dragBehavior && (this.dragBehavior.enabled = !!t)
    }
    ,
    Object.defineProperty(e.prototype, "isEnabled", {
        get: function() {
            return this._isEnabled
        },
        set: function(t) {
            this._isEnabled = t,
            t ? this._parent && (this.attachedNode = this._parent.attachedNode) : this.attachedNode = null
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.dispose = function() {
        this.onSnapObservable.clear(),
        this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),
        this.dragBehavior.detach(),
        i.prototype.dispose.call(this),
        this._gizmoMesh && this._gizmoMesh.dispose(),
        [this._coloredMaterial, this._hoverMaterial, this._disableMaterial].forEach(function(t) {
            t && t.dispose()
        })
    }
    ,
    e
}(Gizmo)
  , PositionGizmo = function(i) {
    __extends(e, i);
    function e(t, r, n) {
        t === void 0 && (t = UtilityLayerRenderer.DefaultUtilityLayer),
        r === void 0 && (r = 1);
        var o = i.call(this, t) || this;
        return o._meshAttached = null,
        o._nodeAttached = null,
        o._observables = [],
        o._gizmoAxisCache = new Map,
        o.onDragStartObservable = new Observable,
        o.onDragEndObservable = new Observable,
        o._planarGizmoEnabled = !1,
        o.xGizmo = new AxisDragGizmo(new Vector3(1,0,0),Color3.Red().scale(.5),t,o,r),
        o.yGizmo = new AxisDragGizmo(new Vector3(0,1,0),Color3.Green().scale(.5),t,o,r),
        o.zGizmo = new AxisDragGizmo(new Vector3(0,0,1),Color3.Blue().scale(.5),t,o,r),
        o.xPlaneGizmo = new PlaneDragGizmo(new Vector3(1,0,0),Color3.Red().scale(.5),o.gizmoLayer,o),
        o.yPlaneGizmo = new PlaneDragGizmo(new Vector3(0,1,0),Color3.Green().scale(.5),o.gizmoLayer,o),
        o.zPlaneGizmo = new PlaneDragGizmo(new Vector3(0,0,1),Color3.Blue().scale(.5),o.gizmoLayer,o),
        [o.xGizmo, o.yGizmo, o.zGizmo, o.xPlaneGizmo, o.yPlaneGizmo, o.zPlaneGizmo].forEach(function(a) {
            a.dragBehavior.onDragStartObservable.add(function() {
                o.onDragStartObservable.notifyObservers({})
            }),
            a.dragBehavior.onDragEndObservable.add(function() {
                o.onDragEndObservable.notifyObservers({})
            })
        }),
        o.attachedMesh = null,
        n ? n.addToAxisCache(o._gizmoAxisCache) : Gizmo.GizmoAxisPointerObserver(t, o._gizmoAxisCache),
        o
    }
    return Object.defineProperty(e.prototype, "attachedMesh", {
        get: function() {
            return this._meshAttached
        },
        set: function(t) {
            this._meshAttached = t,
            this._nodeAttached = t,
            [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach(function(r) {
                r.isEnabled ? r.attachedMesh = t : r.attachedMesh = null
            })
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "attachedNode", {
        get: function() {
            return this._nodeAttached
        },
        set: function(t) {
            this._meshAttached = null,
            this._nodeAttached = t,
            [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach(function(r) {
                r.isEnabled ? r.attachedNode = t : r.attachedNode = null
            })
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "isHovered", {
        get: function() {
            var t = !1;
            return [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach(function(r) {
                t = t || r.isHovered
            }),
            t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "planarGizmoEnabled", {
        get: function() {
            return this._planarGizmoEnabled
        },
        set: function(t) {
            var r = this;
            this._planarGizmoEnabled = t,
            [this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach(function(n) {
                n && (n.isEnabled = t,
                t && (n.attachedMesh ? n.attachedMesh = r.attachedMesh : n.attachedNode = r.attachedNode))
            }, this)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "updateGizmoRotationToMatchAttachedMesh", {
        get: function() {
            return this._updateGizmoRotationToMatchAttachedMesh
        },
        set: function(t) {
            this._updateGizmoRotationToMatchAttachedMesh = t,
            [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach(function(r) {
                r && (r.updateGizmoRotationToMatchAttachedMesh = t)
            })
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "snapDistance", {
        get: function() {
            return this._snapDistance
        },
        set: function(t) {
            this._snapDistance = t,
            [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach(function(r) {
                r && (r.snapDistance = t)
            })
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "scaleRatio", {
        get: function() {
            return this._scaleRatio
        },
        set: function(t) {
            this._scaleRatio = t,
            [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach(function(r) {
                r && (r.scaleRatio = t)
            })
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.addToAxisCache = function(t, r) {
        this._gizmoAxisCache.set(t, r)
    }
    ,
    e.prototype.dispose = function() {
        var t = this;
        [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach(function(r) {
            r && r.dispose()
        }),
        this._observables.forEach(function(r) {
            t.gizmoLayer.utilityLayerScene.onPointerObservable.remove(r)
        }),
        this.onDragStartObservable.clear(),
        this.onDragEndObservable.clear()
    }
    ,
    e.prototype.setCustomMesh = function(t) {
        Logger$2.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,gizmo.xPlaneGizmo, gizmo.yPlaneGizmo, gizmo.zPlaneGizmo)")
    }
    ,
    e
}(Gizmo)
  , AxisScaleGizmo = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a) {
        r === void 0 && (r = Color3.Gray()),
        n === void 0 && (n = UtilityLayerRenderer.DefaultUtilityLayer),
        o === void 0 && (o = null),
        a === void 0 && (a = 1);
        var s, l, u, c, h, f, d, _ = i.call(this, n) || this;
        _._pointerObserver = null,
        _.snapDistance = 0,
        _.onSnapObservable = new Observable,
        _.uniformScaling = !1,
        _.sensitivity = 1,
        _.dragScale = 1,
        _._isEnabled = !0,
        _._parent = null,
        _._dragging = !1,
        _._tmpVector = new Vector3,
        _._tmpMatrix = new Matrix,
        _._tmpMatrix2 = new Matrix,
        _._parent = o,
        _._coloredMaterial = new StandardMaterial("",n.utilityLayerScene),
        _._coloredMaterial.diffuseColor = r,
        _._coloredMaterial.specularColor = r.subtract(new Color3(.1,.1,.1)),
        _._hoverMaterial = new StandardMaterial("",n.utilityLayerScene),
        _._hoverMaterial.diffuseColor = Color3.Yellow(),
        _._disableMaterial = new StandardMaterial("",n.utilityLayerScene),
        _._disableMaterial.diffuseColor = Color3.Gray(),
        _._disableMaterial.alpha = .4,
        _._gizmoMesh = new Mesh("axis",n.utilityLayerScene);
        var g = _._createGizmoMesh(_._gizmoMesh, a)
          , m = g.arrowMesh
          , v = g.arrowTail
          , y = _._createGizmoMesh(_._gizmoMesh, a + 4, !0);
        _._gizmoMesh.lookAt(_._rootMesh.position.add(t)),
        _._rootMesh.addChild(_._gizmoMesh),
        _._gizmoMesh.scaling.scaleInPlace(1 / 3);
        var b = m.position.clone()
          , T = v.position.clone()
          , C = v.scaling.clone()
          , A = function(w) {
            var O = w * (3 / _._rootMesh.scaling.length()) * 6;
            m.position.z += O / 3.5,
            v.scaling.y += O,
            _.dragScale = v.scaling.y,
            v.position.z = m.position.z / 2
        }
          , S = function() {
            m.position.set(b.x, b.y, b.z),
            v.position.set(T.x, T.y, T.z),
            v.scaling.set(C.x, C.y, C.z),
            _.dragScale = v.scaling.y,
            _._dragging = !1
        };
        _.dragBehavior = new PointerDragBehavior({
            dragAxis: t
        }),
        _.dragBehavior.moveAttached = !1,
        _._rootMesh.addBehavior(_.dragBehavior);
        var P = 0
          , R = new Vector3
          , M = {
            snapDistance: 0
        };
        _.dragBehavior.onDragObservable.add(function(w) {
            if (_.attachedNode) {
                _._handlePivot();
                var O = _.sensitivity * w.dragDistance * (_.scaleRatio * 3 / _._rootMesh.scaling.length())
                  , D = !1
                  , F = 0;
                _.uniformScaling ? R.setAll(.57735) : R.copyFrom(t),
                _.snapDistance == 0 ? R.scaleToRef(O, R) : (P += O,
                Math.abs(P) > _.snapDistance ? (F = Math.floor(Math.abs(P) / _.snapDistance),
                P < 0 && (F *= -1),
                P = P % _.snapDistance,
                R.scaleToRef(_.snapDistance * F, R),
                D = !0) : R.scaleInPlace(0)),
                Matrix.ScalingToRef(1 + R.x, 1 + R.y, 1 + R.z, _._tmpMatrix2),
                _._tmpMatrix2.multiplyToRef(_.attachedNode.getWorldMatrix(), _._tmpMatrix),
                _._tmpMatrix.decompose(_._tmpVector);
                var V = 1e5;
                Math.abs(_._tmpVector.x) < V && Math.abs(_._tmpVector.y) < V && Math.abs(_._tmpVector.z) < V && _.attachedNode.getWorldMatrix().copyFrom(_._tmpMatrix),
                D && (M.snapDistance = _.snapDistance * F,
                _.onSnapObservable.notifyObservers(M)),
                _._matrixChanged()
            }
        }),
        _.dragBehavior.onDragStartObservable.add(function() {
            _._dragging = !0
        }),
        _.dragBehavior.onDragObservable.add(function(w) {
            return A(w.dragDistance)
        }),
        _.dragBehavior.onDragEndObservable.add(S),
        (u = (l = (s = o == null ? void 0 : o.uniformScaleGizmo) === null || s === void 0 ? void 0 : s.dragBehavior) === null || l === void 0 ? void 0 : l.onDragObservable) === null || u === void 0 || u.add(function(w) {
            return A(w.delta.y)
        }),
        (f = (h = (c = o == null ? void 0 : o.uniformScaleGizmo) === null || c === void 0 ? void 0 : c.dragBehavior) === null || h === void 0 ? void 0 : h.onDragEndObservable) === null || f === void 0 || f.add(S);
        var x = {
            gizmoMeshes: [m, v],
            colliderMeshes: [y.arrowMesh, y.arrowTail],
            material: _._coloredMaterial,
            hoverMaterial: _._hoverMaterial,
            disableMaterial: _._disableMaterial,
            active: !1,
            dragBehavior: _.dragBehavior
        };
        (d = _._parent) === null || d === void 0 || d.addToAxisCache(_._gizmoMesh, x),
        _._pointerObserver = n.utilityLayerScene.onPointerObservable.add(function(w) {
            var O;
            if (!_._customMeshSet && (_._isHovered = x.colliderMeshes.indexOf((O = w == null ? void 0 : w.pickInfo) === null || O === void 0 ? void 0 : O.pickedMesh) != -1,
            !_._parent)) {
                var D = _.dragBehavior.enabled ? _._isHovered || _._dragging ? _._hoverMaterial : _._coloredMaterial : _._disableMaterial;
                _._setGizmoMeshMaterial(x.gizmoMeshes, D)
            }
        }),
        _.dragBehavior.onEnabledObservable.add(function(w) {
            _._setGizmoMeshMaterial(x.gizmoMeshes, w ? _._coloredMaterial : _._disableMaterial)
        });
        var I = n._getSharedGizmoLight();
        return I.includedOnlyMeshes = I.includedOnlyMeshes.concat(_._rootMesh.getChildMeshes()),
        _
    }
    return e.prototype._createGizmoMesh = function(t, r, n) {
        n === void 0 && (n = !1);
        var o = CreateBox("yPosMesh", {
            size: .4 * (1 + (r - 1) / 4)
        }, this.gizmoLayer.utilityLayerScene)
          , a = CreateCylinder("cylinder", {
            diameterTop: .005 * r,
            height: .275,
            diameterBottom: .005 * r,
            tessellation: 96
        }, this.gizmoLayer.utilityLayerScene);
        return o.scaling.scaleInPlace(.1),
        o.material = this._coloredMaterial,
        o.rotation.x = Math.PI / 2,
        o.position.z += .3,
        a.material = this._coloredMaterial,
        a.position.z += .275 / 2,
        a.rotation.x = Math.PI / 2,
        n && (o.visibility = 0,
        a.visibility = 0),
        t.addChild(o),
        t.addChild(a),
        {
            arrowMesh: o,
            arrowTail: a
        }
    }
    ,
    e.prototype._attachedNodeChanged = function(t) {
        this.dragBehavior && (this.dragBehavior.enabled = !!t)
    }
    ,
    Object.defineProperty(e.prototype, "isEnabled", {
        get: function() {
            return this._isEnabled
        },
        set: function(t) {
            this._isEnabled = t,
            t ? this._parent && (this.attachedMesh = this._parent.attachedMesh,
            this.attachedNode = this._parent.attachedNode) : (this.attachedMesh = null,
            this.attachedNode = null)
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.dispose = function() {
        this.onSnapObservable.clear(),
        this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),
        this.dragBehavior.detach(),
        this._gizmoMesh && this._gizmoMesh.dispose(),
        [this._coloredMaterial, this._hoverMaterial, this._disableMaterial].forEach(function(t) {
            t && t.dispose()
        }),
        i.prototype.dispose.call(this)
    }
    ,
    e.prototype.setCustomMesh = function(t, r) {
        var n = this;
        r === void 0 && (r = !1),
        i.prototype.setCustomMesh.call(this, t),
        r && (this._rootMesh.getChildMeshes().forEach(function(o) {
            o.material = n._coloredMaterial,
            o.color && (o.color = n._coloredMaterial.diffuseColor)
        }),
        this._customMeshSet = !1)
    }
    ,
    e
}(Gizmo)
  , ScaleGizmo = function(i) {
    __extends(e, i);
    function e(t, r, n) {
        t === void 0 && (t = UtilityLayerRenderer.DefaultUtilityLayer),
        r === void 0 && (r = 1);
        var o = i.call(this, t) || this;
        return o._meshAttached = null,
        o._nodeAttached = null,
        o._sensitivity = 1,
        o._observables = [],
        o._gizmoAxisCache = new Map,
        o.onDragStartObservable = new Observable,
        o.onDragEndObservable = new Observable,
        o.uniformScaleGizmo = o._createUniformScaleMesh(),
        o.xGizmo = new AxisScaleGizmo(new Vector3(1,0,0),Color3.Red().scale(.5),t,o,r),
        o.yGizmo = new AxisScaleGizmo(new Vector3(0,1,0),Color3.Green().scale(.5),t,o,r),
        o.zGizmo = new AxisScaleGizmo(new Vector3(0,0,1),Color3.Blue().scale(.5),t,o,r),
        [o.xGizmo, o.yGizmo, o.zGizmo, o.uniformScaleGizmo].forEach(function(a) {
            a.dragBehavior.onDragStartObservable.add(function() {
                o.onDragStartObservable.notifyObservers({})
            }),
            a.dragBehavior.onDragEndObservable.add(function() {
                o.onDragEndObservable.notifyObservers({})
            })
        }),
        o.attachedMesh = null,
        o.attachedNode = null,
        n ? n.addToAxisCache(o._gizmoAxisCache) : Gizmo.GizmoAxisPointerObserver(t, o._gizmoAxisCache),
        o
    }
    return Object.defineProperty(e.prototype, "attachedMesh", {
        get: function() {
            return this._meshAttached
        },
        set: function(t) {
            this._meshAttached = t,
            this._nodeAttached = t,
            [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach(function(r) {
                r.isEnabled ? r.attachedMesh = t : r.attachedMesh = null
            })
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "attachedNode", {
        get: function() {
            return this._nodeAttached
        },
        set: function(t) {
            this._meshAttached = null,
            this._nodeAttached = t,
            [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach(function(r) {
                r.isEnabled ? r.attachedNode = t : r.attachedNode = null
            })
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "isHovered", {
        get: function() {
            var t = !1;
            return [this.xGizmo, this.yGizmo, this.zGizmo].forEach(function(r) {
                t = t || r.isHovered
            }),
            t
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._createUniformScaleMesh = function() {
        this._coloredMaterial = new StandardMaterial("",this.gizmoLayer.utilityLayerScene),
        this._coloredMaterial.diffuseColor = Color3.Gray(),
        this._hoverMaterial = new StandardMaterial("",this.gizmoLayer.utilityLayerScene),
        this._hoverMaterial.diffuseColor = Color3.Yellow(),
        this._disableMaterial = new StandardMaterial("",this.gizmoLayer.utilityLayerScene),
        this._disableMaterial.diffuseColor = Color3.Gray(),
        this._disableMaterial.alpha = .4;
        var t = new AxisScaleGizmo(new Vector3(0,1,0),Color3.Gray().scale(.5),this.gizmoLayer,this);
        t.updateGizmoRotationToMatchAttachedMesh = !1,
        t.uniformScaling = !0,
        this._uniformScalingMesh = CreatePolyhedron("uniform", {
            type: 1
        }, t.gizmoLayer.utilityLayerScene),
        this._uniformScalingMesh.scaling.scaleInPlace(.01),
        this._uniformScalingMesh.visibility = 0,
        this._octahedron = CreatePolyhedron("", {
            type: 1
        }, t.gizmoLayer.utilityLayerScene),
        this._octahedron.scaling.scaleInPlace(.007),
        this._uniformScalingMesh.addChild(this._octahedron),
        t.setCustomMesh(this._uniformScalingMesh, !0);
        var r = this.gizmoLayer._getSharedGizmoLight();
        r.includedOnlyMeshes = r.includedOnlyMeshes.concat(this._octahedron);
        var n = {
            gizmoMeshes: [this._octahedron, this._uniformScalingMesh],
            colliderMeshes: [this._uniformScalingMesh],
            material: this._coloredMaterial,
            hoverMaterial: this._hoverMaterial,
            disableMaterial: this._disableMaterial,
            active: !1,
            dragBehavior: t.dragBehavior
        };
        return this.addToAxisCache(t._rootMesh, n),
        t
    }
    ,
    Object.defineProperty(e.prototype, "updateGizmoRotationToMatchAttachedMesh", {
        get: function() {
            return this._updateGizmoRotationToMatchAttachedMesh
        },
        set: function(t) {
            t ? (this._updateGizmoRotationToMatchAttachedMesh = t,
            [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach(function(r) {
                r && (r.updateGizmoRotationToMatchAttachedMesh = t)
            })) : Logger$2.Warn("Setting updateGizmoRotationToMatchAttachedMesh = false on scaling gizmo is not supported.")
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "snapDistance", {
        get: function() {
            return this._snapDistance
        },
        set: function(t) {
            this._snapDistance = t,
            [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach(function(r) {
                r && (r.snapDistance = t)
            })
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "scaleRatio", {
        get: function() {
            return this._scaleRatio
        },
        set: function(t) {
            this._scaleRatio = t,
            [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach(function(r) {
                r && (r.scaleRatio = t)
            })
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "sensitivity", {
        get: function() {
            return this._sensitivity
        },
        set: function(t) {
            this._sensitivity = t,
            [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach(function(r) {
                r && (r.sensitivity = t)
            })
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.addToAxisCache = function(t, r) {
        this._gizmoAxisCache.set(t, r)
    }
    ,
    e.prototype.dispose = function() {
        var t = this;
        [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach(function(r) {
            r && r.dispose()
        }),
        this._observables.forEach(function(r) {
            t.gizmoLayer.utilityLayerScene.onPointerObservable.remove(r)
        }),
        this.onDragStartObservable.clear(),
        this.onDragEndObservable.clear(),
        [this._uniformScalingMesh, this._octahedron].forEach(function(r) {
            r && r.dispose()
        }),
        [this._coloredMaterial, this._hoverMaterial, this._disableMaterial].forEach(function(r) {
            r && r.dispose()
        })
    }
    ,
    e
}(Gizmo)
  , BoundingBoxGizmo = function(i) {
    __extends(e, i);
    function e(t, r) {
        t === void 0 && (t = Color3.Gray()),
        r === void 0 && (r = UtilityLayerRenderer.DefaultKeepDepthUtilityLayer);
        var n = i.call(this, r) || this;
        n._boundingDimensions = new Vector3(1,1,1),
        n._renderObserver = null,
        n._pointerObserver = null,
        n._scaleDragSpeed = .2,
        n._tmpQuaternion = new Quaternion,
        n._tmpVector = new Vector3(0,0,0),
        n._tmpRotationMatrix = new Matrix,
        n.ignoreChildren = !1,
        n.includeChildPredicate = null,
        n.rotationSphereSize = .1,
        n.scaleBoxSize = .1,
        n.fixedDragMeshScreenSize = !1,
        n.fixedDragMeshBoundsSize = !1,
        n.fixedDragMeshScreenSizeDistanceFactor = 10,
        n.onDragStartObservable = new Observable,
        n.onScaleBoxDragObservable = new Observable,
        n.onScaleBoxDragEndObservable = new Observable,
        n.onRotationSphereDragObservable = new Observable,
        n.onRotationSphereDragEndObservable = new Observable,
        n.scalePivot = null,
        n._axisFactor = new Vector3(1,1,1),
        n._existingMeshScale = new Vector3,
        n._dragMesh = null,
        n.pointerDragBehavior = new PointerDragBehavior,
        n.updateScale = !1,
        n._anchorMesh = new AbstractMesh("anchor",r.utilityLayerScene),
        n.coloredMaterial = new StandardMaterial("",r.utilityLayerScene),
        n.coloredMaterial.disableLighting = !0,
        n.hoverColoredMaterial = new StandardMaterial("",r.utilityLayerScene),
        n.hoverColoredMaterial.disableLighting = !0,
        n._lineBoundingBox = new AbstractMesh("",r.utilityLayerScene),
        n._lineBoundingBox.rotationQuaternion = new Quaternion;
        var o = [];
        o.push(CreateLines("lines", {
            points: [new Vector3(0,0,0), new Vector3(n._boundingDimensions.x,0,0)]
        }, r.utilityLayerScene)),
        o.push(CreateLines("lines", {
            points: [new Vector3(0,0,0), new Vector3(0,n._boundingDimensions.y,0)]
        }, r.utilityLayerScene)),
        o.push(CreateLines("lines", {
            points: [new Vector3(0,0,0), new Vector3(0,0,n._boundingDimensions.z)]
        }, r.utilityLayerScene)),
        o.push(CreateLines("lines", {
            points: [new Vector3(n._boundingDimensions.x,0,0), new Vector3(n._boundingDimensions.x,n._boundingDimensions.y,0)]
        }, r.utilityLayerScene)),
        o.push(CreateLines("lines", {
            points: [new Vector3(n._boundingDimensions.x,0,0), new Vector3(n._boundingDimensions.x,0,n._boundingDimensions.z)]
        }, r.utilityLayerScene)),
        o.push(CreateLines("lines", {
            points: [new Vector3(0,n._boundingDimensions.y,0), new Vector3(n._boundingDimensions.x,n._boundingDimensions.y,0)]
        }, r.utilityLayerScene)),
        o.push(CreateLines("lines", {
            points: [new Vector3(0,n._boundingDimensions.y,0), new Vector3(0,n._boundingDimensions.y,n._boundingDimensions.z)]
        }, r.utilityLayerScene)),
        o.push(CreateLines("lines", {
            points: [new Vector3(0,0,n._boundingDimensions.z), new Vector3(n._boundingDimensions.x,0,n._boundingDimensions.z)]
        }, r.utilityLayerScene)),
        o.push(CreateLines("lines", {
            points: [new Vector3(0,0,n._boundingDimensions.z), new Vector3(0,n._boundingDimensions.y,n._boundingDimensions.z)]
        }, r.utilityLayerScene)),
        o.push(CreateLines("lines", {
            points: [new Vector3(n._boundingDimensions.x,n._boundingDimensions.y,n._boundingDimensions.z), new Vector3(0,n._boundingDimensions.y,n._boundingDimensions.z)]
        }, r.utilityLayerScene)),
        o.push(CreateLines("lines", {
            points: [new Vector3(n._boundingDimensions.x,n._boundingDimensions.y,n._boundingDimensions.z), new Vector3(n._boundingDimensions.x,0,n._boundingDimensions.z)]
        }, r.utilityLayerScene)),
        o.push(CreateLines("lines", {
            points: [new Vector3(n._boundingDimensions.x,n._boundingDimensions.y,n._boundingDimensions.z), new Vector3(n._boundingDimensions.x,n._boundingDimensions.y,0)]
        }, r.utilityLayerScene)),
        o.forEach(function(m) {
            m.color = t,
            m.position.addInPlace(new Vector3(-n._boundingDimensions.x / 2,-n._boundingDimensions.y / 2,-n._boundingDimensions.z / 2)),
            m.isPickable = !1,
            n._lineBoundingBox.addChild(m)
        }),
        n._rootMesh.addChild(n._lineBoundingBox),
        n.setColor(t),
        n._rotateSpheresParent = new AbstractMesh("",r.utilityLayerScene),
        n._rotateSpheresParent.rotationQuaternion = new Quaternion;
        for (var a = function(m) {
            var v = CreateSphere("", {
                diameter: 1
            }, r.utilityLayerScene);
            v.rotationQuaternion = new Quaternion,
            v.material = s.coloredMaterial,
            v.isNearGrabbable = !0,
            l = new PointerDragBehavior({}),
            l.moveAttached = !1,
            l.updateDragPlane = !1,
            v.addBehavior(l);
            var y = new Vector3(1,0,0)
              , b = 0;
            l.onDragStartObservable.add(function() {
                y.copyFrom(v.forward),
                b = 0
            }),
            l.onDragObservable.add(function(T) {
                if (n.onRotationSphereDragObservable.notifyObservers({}),
                n.attachedMesh) {
                    var C = n.attachedMesh.parent;
                    if (C && C.scaling && C.scaling.isNonUniformWithinEpsilon(.001)) {
                        Logger$2.Warn("BoundingBoxGizmo controls are not supported on child meshes with non-uniform parent scaling");
                        return
                    }
                    PivotTools._RemoveAndStorePivotPoint(n.attachedMesh);
                    var A = y
                      , S = T.dragPlaneNormal.scale(Vector3.Dot(T.dragPlaneNormal, A))
                      , P = A.subtract(S).normalizeToNew()
                      , R = Vector3.Dot(P, T.delta) < 0 ? Math.abs(T.delta.length()) : -Math.abs(T.delta.length());
                    R = R / n._boundingDimensions.length() * n._anchorMesh.scaling.length(),
                    n.attachedMesh.rotationQuaternion || (n.attachedMesh.rotationQuaternion = Quaternion.RotationYawPitchRoll(n.attachedMesh.rotation.y, n.attachedMesh.rotation.x, n.attachedMesh.rotation.z)),
                    n._anchorMesh.rotationQuaternion || (n._anchorMesh.rotationQuaternion = Quaternion.RotationYawPitchRoll(n._anchorMesh.rotation.y, n._anchorMesh.rotation.x, n._anchorMesh.rotation.z)),
                    b += R,
                    Math.abs(b) <= 2 * Math.PI && (m >= 8 ? Quaternion.RotationYawPitchRollToRef(0, 0, R, n._tmpQuaternion) : m >= 4 ? Quaternion.RotationYawPitchRollToRef(R, 0, 0, n._tmpQuaternion) : Quaternion.RotationYawPitchRollToRef(0, R, 0, n._tmpQuaternion),
                    n._anchorMesh.addChild(n.attachedMesh),
                    n._anchorMesh.rotationQuaternion.multiplyToRef(n._tmpQuaternion, n._anchorMesh.rotationQuaternion),
                    n._anchorMesh.removeChild(n.attachedMesh),
                    n.attachedMesh.setParent(C)),
                    n.updateBoundingBox(),
                    PivotTools._RestorePivotPoint(n.attachedMesh)
                }
                n._updateDummy()
            }),
            l.onDragStartObservable.add(function() {
                n.onDragStartObservable.notifyObservers({}),
                n._selectNode(v)
            }),
            l.onDragEndObservable.add(function() {
                n.onRotationSphereDragEndObservable.notifyObservers({}),
                n._selectNode(null),
                n._updateDummy()
            }),
            s._rotateSpheresParent.addChild(v)
        }, s = this, l, u = 0; u < 12; u++)
            a(u);
        n._rootMesh.addChild(n._rotateSpheresParent),
        n._scaleBoxesParent = new AbstractMesh("",r.utilityLayerScene),
        n._scaleBoxesParent.rotationQuaternion = new Quaternion;
        for (var c = 0; c < 3; c++)
            for (var h = 0; h < 3; h++)
                for (var f = function() {
                    var v = (c === 1 ? 1 : 0) + (h === 1 ? 1 : 0) + (_ === 1 ? 1 : 0);
                    if (v === 1 || v === 3)
                        return "continue";
                    var y = CreateBox("", {
                        size: 1
                    }, r.utilityLayerScene);
                    y.material = d.coloredMaterial,
                    y.metadata = v === 2,
                    y.isNearGrabbable = !0;
                    var b = new Vector3(c - 1,h - 1,_ - 1).normalize();
                    l = new PointerDragBehavior({
                        dragAxis: b
                    }),
                    l.updateDragPlane = !1,
                    l.moveAttached = !1,
                    y.addBehavior(l),
                    l.onDragObservable.add(function(T) {
                        if (n.onScaleBoxDragObservable.notifyObservers({}),
                        n.attachedMesh) {
                            var C = n.attachedMesh.parent;
                            if (C && C.scaling && C.scaling.isNonUniformWithinEpsilon(.001)) {
                                Logger$2.Warn("BoundingBoxGizmo controls are not supported on child meshes with non-uniform parent scaling");
                                return
                            }
                            PivotTools._RemoveAndStorePivotPoint(n.attachedMesh);
                            var A = T.dragDistance / n._boundingDimensions.length() * n._anchorMesh.scaling.length()
                              , S = new Vector3(A,A,A);
                            v === 2 && (S.x *= Math.abs(b.x),
                            S.y *= Math.abs(b.y),
                            S.z *= Math.abs(b.z)),
                            S.scaleInPlace(n._scaleDragSpeed),
                            S.multiplyInPlace(n._axisFactor),
                            n.updateBoundingBox(),
                            n.scalePivot ? (n.attachedMesh.getWorldMatrix().getRotationMatrixToRef(n._tmpRotationMatrix),
                            n._boundingDimensions.scaleToRef(.5, n._tmpVector),
                            Vector3.TransformCoordinatesToRef(n._tmpVector, n._tmpRotationMatrix, n._tmpVector),
                            n._anchorMesh.position.subtractInPlace(n._tmpVector),
                            n._boundingDimensions.multiplyToRef(n.scalePivot, n._tmpVector),
                            Vector3.TransformCoordinatesToRef(n._tmpVector, n._tmpRotationMatrix, n._tmpVector),
                            n._anchorMesh.position.addInPlace(n._tmpVector)) : (y.absolutePosition.subtractToRef(n._anchorMesh.position, n._tmpVector),
                            n._anchorMesh.position.subtractInPlace(n._tmpVector)),
                            n._anchorMesh.addChild(n.attachedMesh),
                            n._anchorMesh.scaling.addInPlace(S),
                            (n._anchorMesh.scaling.x < 0 || n._anchorMesh.scaling.y < 0 || n._anchorMesh.scaling.z < 0) && n._anchorMesh.scaling.subtractInPlace(S),
                            n._anchorMesh.removeChild(n.attachedMesh),
                            n.attachedMesh.setParent(C),
                            PivotTools._RestorePivotPoint(n.attachedMesh)
                        }
                        n._updateDummy()
                    }),
                    l.onDragStartObservable.add(function() {
                        n.onDragStartObservable.notifyObservers({}),
                        n._selectNode(y)
                    }),
                    l.onDragEndObservable.add(function() {
                        n.onScaleBoxDragEndObservable.notifyObservers({}),
                        n._selectNode(null),
                        n._updateDummy()
                    }),
                    d._scaleBoxesParent.addChild(y)
                }, d = this, l, _ = 0; _ < 3; _++)
                    f();
        n._rootMesh.addChild(n._scaleBoxesParent);
        var g = new Array;
        return n._pointerObserver = r.utilityLayerScene.onPointerObservable.add(function(m) {
            g[m.event.pointerId] ? m.pickInfo && m.pickInfo.pickedMesh != g[m.event.pointerId] && (g[m.event.pointerId].material = n.coloredMaterial,
            delete g[m.event.pointerId]) : n._rotateSpheresParent.getChildMeshes().concat(n._scaleBoxesParent.getChildMeshes()).forEach(function(v) {
                m.pickInfo && m.pickInfo.pickedMesh == v && (g[m.event.pointerId] = v,
                v.material = n.hoverColoredMaterial)
            })
        }),
        n._renderObserver = n.gizmoLayer.originalScene.onBeforeRenderObservable.add(function() {
            n.attachedMesh && !n._existingMeshScale.equals(n.attachedMesh.scaling) ? n.updateBoundingBox() : (n.fixedDragMeshScreenSize || n.fixedDragMeshBoundsSize) && (n._updateRotationSpheres(),
            n._updateScaleBoxes()),
            n._dragMesh && n.attachedMesh && n.pointerDragBehavior.dragging && (n._lineBoundingBox.position.rotateByQuaternionToRef(n._rootMesh.rotationQuaternion, n._tmpVector),
            n.attachedMesh.setAbsolutePosition(n._dragMesh.position.add(n._tmpVector.scale(-1))))
        }),
        n.updateBoundingBox(),
        n
    }
    return Object.defineProperty(e.prototype, "axisFactor", {
        get: function() {
            return this._axisFactor
        },
        set: function(t) {
            this._axisFactor = t;
            for (var r = this._scaleBoxesParent.getChildMeshes(), n = 0, o = 0; o < 3; o++)
                for (var a = 0; a < 3; a++)
                    for (var s = 0; s < 3; s++) {
                        var l = (o === 1 ? 1 : 0) + (a === 1 ? 1 : 0) + (s === 1 ? 1 : 0);
                        if (!(l === 1 || l === 3)) {
                            if (r[n]) {
                                var u = new Vector3(o - 1,a - 1,s - 1);
                                u.multiplyInPlace(this._axisFactor),
                                r[n].setEnabled(u.lengthSquared() > Epsilon)
                            }
                            n++
                        }
                    }
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "scaleDragSpeed", {
        get: function() {
            return this._scaleDragSpeed
        },
        set: function(t) {
            this._scaleDragSpeed = t
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.setColor = function(t) {
        this.coloredMaterial.emissiveColor = t,
        this.hoverColoredMaterial.emissiveColor = t.clone().add(new Color3(.3,.3,.3)),
        this._lineBoundingBox.getChildren().forEach(function(r) {
            r.color && (r.color = t)
        })
    }
    ,
    e.prototype._attachedNodeChanged = function(t) {
        var r = this;
        if (t) {
            this._anchorMesh.scaling.setAll(1),
            PivotTools._RemoveAndStorePivotPoint(t);
            var n = t.parent;
            this._anchorMesh.addChild(t),
            this._anchorMesh.removeChild(t),
            t.setParent(n),
            PivotTools._RestorePivotPoint(t),
            this.updateBoundingBox(),
            t.getChildMeshes(!1).forEach(function(o) {
                o.markAsDirty("scaling")
            }),
            this.gizmoLayer.utilityLayerScene.onAfterRenderObservable.addOnce(function() {
                r._updateDummy()
            })
        }
    }
    ,
    e.prototype._selectNode = function(t) {
        this._rotateSpheresParent.getChildMeshes().concat(this._scaleBoxesParent.getChildMeshes()).forEach(function(r) {
            r.isVisible = !t || r == t
        })
    }
    ,
    e.prototype.updateBoundingBox = function() {
        if (this.attachedMesh) {
            PivotTools._RemoveAndStorePivotPoint(this.attachedMesh);
            var t = this.attachedMesh.parent;
            this.attachedMesh.setParent(null);
            var r = null;
            this.attachedMesh.skeleton && (r = this.attachedMesh.skeleton.overrideMesh,
            this.attachedMesh.skeleton.overrideMesh = null),
            this._update(),
            this.attachedMesh.rotationQuaternion || (this.attachedMesh.rotationQuaternion = Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z)),
            this._anchorMesh.rotationQuaternion || (this._anchorMesh.rotationQuaternion = Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z)),
            this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion),
            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);
            var n = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate);
            n.max.subtractToRef(n.min, this._boundingDimensions),
            this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions),
            this._lineBoundingBox.position.set((n.max.x + n.min.x) / 2, (n.max.y + n.min.y) / 2, (n.max.z + n.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),
            this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion),
            this.attachedMesh.position.copyFrom(this._tmpVector),
            this.attachedMesh.setParent(t),
            this.attachedMesh.skeleton && (this.attachedMesh.skeleton.overrideMesh = r)
        }
        this._updateRotationSpheres(),
        this._updateScaleBoxes(),
        this.attachedMesh && (this._existingMeshScale.copyFrom(this.attachedMesh.scaling),
        PivotTools._RestorePivotPoint(this.attachedMesh))
    }
    ,
    e.prototype._updateRotationSpheres = function() {
        for (var t = this._rotateSpheresParent.getChildMeshes(), r = 0; r < 3; r++)
            for (var n = 0; n < 2; n++)
                for (var o = 0; o < 2; o++) {
                    var a = r * 4 + n * 2 + o;
                    if (r == 0 && (t[a].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * n, this._boundingDimensions.z * o),
                    t[a].position.addInPlace(new Vector3(-this._boundingDimensions.x / 2,-this._boundingDimensions.y / 2,-this._boundingDimensions.z / 2)),
                    t[a].lookAt(Vector3.Cross(t[a].position.normalizeToNew(), Vector3.Right()).normalizeToNew().add(t[a].position))),
                    r == 1 && (t[a].position.set(this._boundingDimensions.x * n, this._boundingDimensions.y / 2, this._boundingDimensions.z * o),
                    t[a].position.addInPlace(new Vector3(-this._boundingDimensions.x / 2,-this._boundingDimensions.y / 2,-this._boundingDimensions.z / 2)),
                    t[a].lookAt(Vector3.Cross(t[a].position.normalizeToNew(), Vector3.Up()).normalizeToNew().add(t[a].position))),
                    r == 2 && (t[a].position.set(this._boundingDimensions.x * n, this._boundingDimensions.y * o, this._boundingDimensions.z / 2),
                    t[a].position.addInPlace(new Vector3(-this._boundingDimensions.x / 2,-this._boundingDimensions.y / 2,-this._boundingDimensions.z / 2)),
                    t[a].lookAt(Vector3.Cross(t[a].position.normalizeToNew(), Vector3.Forward()).normalizeToNew().add(t[a].position))),
                    this.fixedDragMeshScreenSize && this.gizmoLayer.utilityLayerScene.activeCamera) {
                        t[a].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
                        var s = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
                        t[a].scaling.set(s, s, s)
                    } else
                        this.fixedDragMeshBoundsSize ? t[a].scaling.set(this.rotationSphereSize * this._boundingDimensions.x, this.rotationSphereSize * this._boundingDimensions.y, this.rotationSphereSize * this._boundingDimensions.z) : t[a].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize)
                }
    }
    ,
    e.prototype._updateScaleBoxes = function() {
        for (var t = this._scaleBoxesParent.getChildMeshes(), r = 0, n = 0; n < 3; n++)
            for (var o = 0; o < 3; o++)
                for (var a = 0; a < 3; a++) {
                    var s = (n === 1 ? 1 : 0) + (o === 1 ? 1 : 0) + (a === 1 ? 1 : 0);
                    if (!(s === 1 || s === 3)) {
                        if (t[r])
                            if (t[r].position.set(this._boundingDimensions.x * (n / 2), this._boundingDimensions.y * (o / 2), this._boundingDimensions.z * (a / 2)),
                            t[r].position.addInPlace(new Vector3(-this._boundingDimensions.x / 2,-this._boundingDimensions.y / 2,-this._boundingDimensions.z / 2)),
                            this.fixedDragMeshScreenSize && this.gizmoLayer.utilityLayerScene.activeCamera) {
                                t[r].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
                                var l = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
                                t[r].scaling.set(l, l, l)
                            } else
                                this.fixedDragMeshBoundsSize ? t[r].scaling.set(this.scaleBoxSize * this._boundingDimensions.x, this.scaleBoxSize * this._boundingDimensions.y, this.scaleBoxSize * this._boundingDimensions.z) : t[r].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
                        r++
                    }
                }
    }
    ,
    e.prototype.setEnabledRotationAxis = function(t) {
        this._rotateSpheresParent.getChildMeshes().forEach(function(r, n) {
            n < 4 ? r.setEnabled(t.indexOf("x") != -1) : n < 8 ? r.setEnabled(t.indexOf("y") != -1) : r.setEnabled(t.indexOf("z") != -1)
        })
    }
    ,
    e.prototype.setEnabledScaling = function(t, r) {
        r === void 0 && (r = !1),
        this._scaleBoxesParent.getChildMeshes().forEach(function(n, o) {
            var a = t;
            r && n.metadata === !0 && (a = !1),
            n.setEnabled(a)
        })
    }
    ,
    e.prototype._updateDummy = function() {
        this._dragMesh && (this._dragMesh.position.copyFrom(this._lineBoundingBox.getAbsolutePosition()),
        this._dragMesh.scaling.copyFrom(this._lineBoundingBox.scaling),
        this._dragMesh.rotationQuaternion.copyFrom(this._rootMesh.rotationQuaternion))
    }
    ,
    e.prototype.enableDragBehavior = function() {
        this._dragMesh = CreateBox("dummy", {
            size: 1
        }, this.gizmoLayer.utilityLayerScene),
        this._dragMesh.visibility = 0,
        this._dragMesh.rotationQuaternion = new Quaternion,
        this.pointerDragBehavior.useObjectOrientationForDragging = !1,
        this._dragMesh.addBehavior(this.pointerDragBehavior)
    }
    ,
    e.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(),
        this._dragMesh && this._dragMesh.dispose(),
        i.prototype.dispose.call(this)
    }
    ,
    e.MakeNotPickableAndWrapInBoundingBox = function(t) {
        var r = function(l) {
            l.isPickable = !1,
            l.getChildMeshes().forEach(function(u) {
                r(u)
            })
        };
        r(t),
        t.rotationQuaternion || (t.rotationQuaternion = Quaternion.RotationYawPitchRoll(t.rotation.y, t.rotation.x, t.rotation.z));
        var n = t.position.clone()
          , o = t.rotationQuaternion.clone();
        t.rotationQuaternion.set(0, 0, 0, 1),
        t.position.set(0, 0, 0);
        var a = CreateBox("box", {
            size: 1
        }, t.getScene())
          , s = t.getHierarchyBoundingVectors();
        return s.max.subtractToRef(s.min, a.scaling),
        a.scaling.y === 0 && (a.scaling.y = Epsilon),
        a.scaling.x === 0 && (a.scaling.x = Epsilon),
        a.scaling.z === 0 && (a.scaling.z = Epsilon),
        a.position.set((s.max.x + s.min.x) / 2, (s.max.y + s.min.y) / 2, (s.max.z + s.min.z) / 2),
        t.addChild(a),
        t.rotationQuaternion.copyFrom(o),
        t.position.copyFrom(n),
        t.removeChild(a),
        a.addChild(t),
        a.visibility = 0,
        a
    }
    ,
    e.prototype.setCustomMesh = function(t) {
        Logger$2.Error("Custom meshes are not supported on this gizmo")
    }
    ,
    e
}(Gizmo);
(function() {
    function i(e, t, r, n) {
        t === void 0 && (t = 1),
        r === void 0 && (r = UtilityLayerRenderer.DefaultUtilityLayer),
        n === void 0 && (n = UtilityLayerRenderer.DefaultKeepDepthUtilityLayer),
        this.scene = e,
        this.clearGizmoOnEmptyPointerEvent = !1,
        this.onAttachedToMeshObservable = new Observable,
        this.onAttachedToNodeObservable = new Observable,
        this._gizmosEnabled = {
            positionGizmo: !1,
            rotationGizmo: !1,
            scaleGizmo: !1,
            boundingBoxGizmo: !1
        },
        this._pointerObservers = [],
        this._attachedMesh = null,
        this._attachedNode = null,
        this._boundingBoxColor = Color3.FromHexString("#0984e3"),
        this._thickness = 1,
        this._scaleRatio = 1,
        this._gizmoAxisCache = new Map,
        this.boundingBoxDragBehavior = new SixDofDragBehavior,
        this.attachableMeshes = null,
        this.attachableNodes = null,
        this.usePointerToAttachGizmos = !0,
        this._defaultUtilityLayer = r,
        this._defaultKeepDepthUtilityLayer = n,
        this._defaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = !1,
        this._thickness = t,
        this.gizmos = {
            positionGizmo: null,
            rotationGizmo: null,
            scaleGizmo: null,
            boundingBoxGizmo: null
        };
        var o = this._attachToMeshPointerObserver(e)
          , a = Gizmo.GizmoAxisPointerObserver(this._defaultUtilityLayer, this._gizmoAxisCache);
        this._pointerObservers = [o, a]
    }
    return Object.defineProperty(i.prototype, "keepDepthUtilityLayer", {
        get: function() {
            return this._defaultKeepDepthUtilityLayer
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "utilityLayer", {
        get: function() {
            return this._defaultUtilityLayer
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "isHovered", {
        get: function() {
            var e = !1;
            for (var t in this.gizmos) {
                var r = this.gizmos[t];
                if (r && r.isHovered) {
                    e = !0;
                    break
                }
            }
            return e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "scaleRatio", {
        get: function() {
            return this._scaleRatio
        },
        set: function(e) {
            this._scaleRatio = e,
            [this.gizmos.positionGizmo, this.gizmos.rotationGizmo, this.gizmos.scaleGizmo].forEach(function(t) {
                t && (t.scaleRatio = e)
            })
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype._attachToMeshPointerObserver = function(e) {
        var t = this
          , r = e.onPointerObservable.add(function(n) {
            if (!!t.usePointerToAttachGizmos && n.type == PointerEventTypes.POINTERDOWN)
                if (n.pickInfo && n.pickInfo.pickedMesh) {
                    var o = n.pickInfo.pickedMesh;
                    if (t.attachableMeshes == null)
                        for (; o && o.parent != null; )
                            o = o.parent;
                    else {
                        var a = !1;
                        t.attachableMeshes.forEach(function(s) {
                            o && (o == s || o.isDescendantOf(s)) && (o = s,
                            a = !0)
                        }),
                        a || (o = null)
                    }
                    o instanceof AbstractMesh ? t._attachedMesh != o && t.attachToMesh(o) : t.clearGizmoOnEmptyPointerEvent && t.attachToMesh(null)
                } else
                    t.clearGizmoOnEmptyPointerEvent && t.attachToMesh(null)
        });
        return r
    }
    ,
    i.prototype.attachToMesh = function(e) {
        this._attachedMesh && this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior),
        this._attachedNode && this._attachedNode.removeBehavior(this.boundingBoxDragBehavior),
        this._attachedMesh = e,
        this._attachedNode = null;
        for (var t in this.gizmos) {
            var r = this.gizmos[t];
            r && this._gizmosEnabled[t] && (r.attachedMesh = e)
        }
        this.boundingBoxGizmoEnabled && this._attachedMesh && this._attachedMesh.addBehavior(this.boundingBoxDragBehavior),
        this.onAttachedToMeshObservable.notifyObservers(e)
    }
    ,
    i.prototype.attachToNode = function(e) {
        this._attachedMesh && this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior),
        this._attachedNode && this._attachedNode.removeBehavior(this.boundingBoxDragBehavior),
        this._attachedMesh = null,
        this._attachedNode = e;
        for (var t in this.gizmos) {
            var r = this.gizmos[t];
            r && this._gizmosEnabled[t] && (r.attachedNode = e)
        }
        this.boundingBoxGizmoEnabled && this._attachedNode && this._attachedNode.addBehavior(this.boundingBoxDragBehavior),
        this.onAttachedToNodeObservable.notifyObservers(e)
    }
    ,
    Object.defineProperty(i.prototype, "positionGizmoEnabled", {
        get: function() {
            return this._gizmosEnabled.positionGizmo
        },
        set: function(e) {
            e ? (this.gizmos.positionGizmo || (this.gizmos.positionGizmo = new PositionGizmo(this._defaultUtilityLayer,this._thickness,this)),
            this._attachedNode ? this.gizmos.positionGizmo.attachedNode = this._attachedNode : this.gizmos.positionGizmo.attachedMesh = this._attachedMesh) : this.gizmos.positionGizmo && (this.gizmos.positionGizmo.attachedNode = null),
            this._gizmosEnabled.positionGizmo = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "rotationGizmoEnabled", {
        get: function() {
            return this._gizmosEnabled.rotationGizmo
        },
        set: function(e) {
            e ? (this.gizmos.rotationGizmo || (this.gizmos.rotationGizmo = new RotationGizmo(this._defaultUtilityLayer,32,!1,this._thickness,this)),
            this._attachedNode ? this.gizmos.rotationGizmo.attachedNode = this._attachedNode : this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh) : this.gizmos.rotationGizmo && (this.gizmos.rotationGizmo.attachedNode = null),
            this._gizmosEnabled.rotationGizmo = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "scaleGizmoEnabled", {
        get: function() {
            return this._gizmosEnabled.scaleGizmo
        },
        set: function(e) {
            e ? (this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new ScaleGizmo(this._defaultUtilityLayer,this._thickness,this),
            this._attachedNode ? this.gizmos.scaleGizmo.attachedNode = this._attachedNode : this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh) : this.gizmos.scaleGizmo && (this.gizmos.scaleGizmo.attachedNode = null),
            this._gizmosEnabled.scaleGizmo = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "boundingBoxGizmoEnabled", {
        get: function() {
            return this._gizmosEnabled.boundingBoxGizmo
        },
        set: function(e) {
            e ? (this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BoundingBoxGizmo(this._boundingBoxColor,this._defaultKeepDepthUtilityLayer),
            this._attachedMesh ? this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh : this.gizmos.boundingBoxGizmo.attachedNode = this._attachedNode,
            this._attachedMesh ? (this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior),
            this._attachedMesh.addBehavior(this.boundingBoxDragBehavior)) : this._attachedNode && (this._attachedNode.removeBehavior(this.boundingBoxDragBehavior),
            this._attachedNode.addBehavior(this.boundingBoxDragBehavior))) : this.gizmos.boundingBoxGizmo && (this._attachedMesh ? this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior) : this._attachedNode && this._attachedNode.removeBehavior(this.boundingBoxDragBehavior),
            this.gizmos.boundingBoxGizmo.attachedNode = null),
            this._gizmosEnabled.boundingBoxGizmo = e
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.addToAxisCache = function(e) {
        var t = this;
        e.size > 0 && e.forEach(function(r, n) {
            t._gizmoAxisCache.set(n, r)
        })
    }
    ,
    i.prototype.dispose = function() {
        var e = this, t, r;
        this._pointerObservers.forEach(function(a) {
            e.scene.onPointerObservable.remove(a)
        });
        for (var n in this.gizmos) {
            var o = this.gizmos[n];
            o && o.dispose()
        }
        this._defaultKeepDepthUtilityLayer !== UtilityLayerRenderer._DefaultKeepDepthUtilityLayer && ((t = this._defaultKeepDepthUtilityLayer) === null || t === void 0 || t.dispose()),
        this._defaultUtilityLayer !== UtilityLayerRenderer._DefaultUtilityLayer && ((r = this._defaultUtilityLayer) === null || r === void 0 || r.dispose()),
        this.boundingBoxDragBehavior.detach(),
        this.onAttachedToMeshObservable.clear()
    }
    ,
    i
}
)();
var LayerSceneComponent = function() {
    function i(e) {
        this.name = SceneComponentConstants.NAME_LAYER,
        this.scene = e,
        this._engine = e.getEngine(),
        e.layers = new Array
    }
    return i.prototype.register = function() {
        this.scene._beforeCameraDrawStage.registerStep(SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawCameraBackground),
        this.scene._afterCameraDrawStage.registerStep(SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawCameraForeground),
        this.scene._beforeRenderTargetDrawStage.registerStep(SceneComponentConstants.STEP_BEFORERENDERTARGETDRAW_LAYER, this, this._drawRenderTargetBackground),
        this.scene._afterRenderTargetDrawStage.registerStep(SceneComponentConstants.STEP_AFTERRENDERTARGETDRAW_LAYER, this, this._drawRenderTargetForeground)
    }
    ,
    i.prototype.rebuild = function() {
        for (var e = this.scene.layers, t = 0, r = e; t < r.length; t++) {
            var n = r[t];
            n._rebuild()
        }
    }
    ,
    i.prototype.dispose = function() {
        for (var e = this.scene.layers; e.length; )
            e[0].dispose()
    }
    ,
    i.prototype._draw = function(e) {
        var t = this.scene.layers;
        if (t.length) {
            this._engine.setDepthBuffer(!1);
            for (var r = 0, n = t; r < n.length; r++) {
                var o = n[r];
                e(o) && o.render()
            }
            this._engine.setDepthBuffer(!0)
        }
    }
    ,
    i.prototype._drawCameraPredicate = function(e, t, r) {
        return !e.renderOnlyInRenderTargetTextures && e.isBackground === t && (e.layerMask & r) !== 0
    }
    ,
    i.prototype._drawCameraBackground = function(e) {
        var t = this;
        this._draw(function(r) {
            return t._drawCameraPredicate(r, !0, e.layerMask)
        })
    }
    ,
    i.prototype._drawCameraForeground = function(e) {
        var t = this;
        this._draw(function(r) {
            return t._drawCameraPredicate(r, !1, e.layerMask)
        })
    }
    ,
    i.prototype._drawRenderTargetPredicate = function(e, t, r, n) {
        return e.renderTargetTextures.length > 0 && e.isBackground === t && e.renderTargetTextures.indexOf(n) > -1 && (e.layerMask & r) !== 0
    }
    ,
    i.prototype._drawRenderTargetBackground = function(e) {
        var t = this;
        this._draw(function(r) {
            return t._drawRenderTargetPredicate(r, !0, t.scene.activeCamera.layerMask, e)
        })
    }
    ,
    i.prototype._drawRenderTargetForeground = function(e) {
        var t = this;
        this._draw(function(r) {
            return t._drawRenderTargetPredicate(r, !1, t.scene.activeCamera.layerMask, e)
        })
    }
    ,
    i.prototype.addFromContainer = function(e) {
        var t = this;
        !e.layers || e.layers.forEach(function(r) {
            t.scene.layers.push(r)
        })
    }
    ,
    i.prototype.removeFromContainer = function(e, t) {
        var r = this;
        t === void 0 && (t = !1),
        e.layers && e.layers.forEach(function(n) {
            var o = r.scene.layers.indexOf(n);
            o !== -1 && r.scene.layers.splice(o, 1),
            t && n.dispose()
        })
    }
    ,
    i
}()
  , name$B = "layerPixelShader"
  , shader$B = `
varying vec2 vUV;
uniform sampler2D textureSampler;

uniform vec4 color;

#include<helperFunctions>
void main(void) {
vec4 baseColor=texture2D(textureSampler,vUV);
#ifdef LINEAR
baseColor.rgb=toGammaSpace(baseColor.rgb);
#endif
#ifdef ALPHATEST
if (baseColor.a<0.4)
discard;
#endif
gl_FragColor=baseColor*color;
}`;
ShaderStore.ShadersStore[name$B] = shader$B;
var name$A = "layerVertexShader"
  , shader$A = `
attribute vec2 position;

uniform vec2 scale;
uniform vec2 offset;
uniform mat4 textureMatrix;

varying vec2 vUV;
const vec2 madd=vec2(0.5,0.5);
void main(void) {
vec2 shiftedPosition=position*scale+offset;
vUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));
gl_Position=vec4(shiftedPosition,0.0,1.0);
}`;
ShaderStore.ShadersStore[name$A] = shader$A;
var Layer = function() {
    function i(e, t, r, n, o) {
        this.name = e,
        this.scale = new Vector2(1,1),
        this.offset = new Vector2(0,0),
        this.alphaBlendingMode = 2,
        this.layerMask = 268435455,
        this.renderTargetTextures = [],
        this.renderOnlyInRenderTargetTextures = !1,
        this.isEnabled = !0,
        this._vertexBuffers = {},
        this.onDisposeObservable = new Observable,
        this.onBeforeRenderObservable = new Observable,
        this.onAfterRenderObservable = new Observable,
        this.texture = t ? new Texture(t,r,!0) : null,
        this.isBackground = n === void 0 ? !0 : n,
        this.color = o === void 0 ? new Color4(1,1,1,1) : o,
        this._scene = r || EngineStore.LastCreatedScene;
        var a = this._scene._getComponent(SceneComponentConstants.NAME_LAYER);
        a || (a = new LayerSceneComponent(this._scene),
        this._scene._addComponent(a)),
        this._scene.layers.push(this);
        var s = this._scene.getEngine();
        this._drawWrapper = new DrawWrapper(s);
        var l = [];
        l.push(1, 1),
        l.push(-1, 1),
        l.push(-1, -1),
        l.push(1, -1);
        var u = new VertexBuffer(s,l,VertexBuffer.PositionKind,!1,!1,2);
        this._vertexBuffers[VertexBuffer.PositionKind] = u,
        this._createIndexBuffer()
    }
    return Object.defineProperty(i.prototype, "onDispose", {
        set: function(e) {
            this._onDisposeObserver && this.onDisposeObservable.remove(this._onDisposeObserver),
            this._onDisposeObserver = this.onDisposeObservable.add(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "onBeforeRender", {
        set: function(e) {
            this._onBeforeRenderObserver && this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),
            this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "onAfterRender", {
        set: function(e) {
            this._onAfterRenderObserver && this.onAfterRenderObservable.remove(this._onAfterRenderObserver),
            this._onAfterRenderObserver = this.onAfterRenderObservable.add(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype._createIndexBuffer = function() {
        var e = this._scene.getEngine()
          , t = [];
        t.push(0),
        t.push(1),
        t.push(2),
        t.push(0),
        t.push(2),
        t.push(3),
        this._indexBuffer = e.createIndexBuffer(t)
    }
    ,
    i.prototype._rebuild = function() {
        var e = this._vertexBuffers[VertexBuffer.PositionKind];
        e && e._rebuild(),
        this._createIndexBuffer()
    }
    ,
    i.prototype.render = function() {
        if (!!this.isEnabled) {
            var r = this._scene.getEngine()
              , e = "";
            this.alphaTest && (e = "#define ALPHATEST"),
            this.texture && !this.texture.gammaSpace && (e += `\r
#define LINEAR`),
            this._previousDefines !== e && (this._previousDefines = e,
            this._drawWrapper.effect = r.createEffect("layer", [VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], e));
            var t = this._drawWrapper.effect;
            if (!(!t || !t.isReady() || !this.texture || !this.texture.isReady())) {
                var r = this._scene.getEngine();
                this.onBeforeRenderObservable.notifyObservers(this),
                r.enableEffect(this._drawWrapper),
                r.setState(!1),
                t.setTexture("textureSampler", this.texture),
                t.setMatrix("textureMatrix", this.texture.getTextureMatrix()),
                t.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a),
                t.setVector2("offset", this.offset),
                t.setVector2("scale", this.scale),
                r.bindBuffers(this._vertexBuffers, this._indexBuffer, t),
                this.alphaTest ? r.drawElementsType(Material.TriangleFillMode, 0, 6) : (r.setAlphaMode(this.alphaBlendingMode),
                r.drawElementsType(Material.TriangleFillMode, 0, 6),
                r.setAlphaMode(0)),
                this.onAfterRenderObservable.notifyObservers(this)
            }
        }
    }
    ,
    i.prototype.dispose = function() {
        var e = this._vertexBuffers[VertexBuffer.PositionKind];
        e && (e.dispose(),
        this._vertexBuffers[VertexBuffer.PositionKind] = null),
        this._indexBuffer && (this._scene.getEngine()._releaseBuffer(this._indexBuffer),
        this._indexBuffer = null),
        this.texture && (this.texture.dispose(),
        this.texture = null),
        this.renderTargetTextures = [];
        var t = this._scene.layers.indexOf(this);
        this._scene.layers.splice(t, 1),
        this.onDisposeObservable.notifyObservers(this),
        this.onDisposeObservable.clear(),
        this.onAfterRenderObservable.clear(),
        this.onBeforeRenderObservable.clear()
    }
    ,
    i
}()
  , name$z = "boundingBoxRendererFragmentDeclaration"
  , shader$z = `uniform vec4 color;
`;
ShaderStore.IncludesShadersStore[name$z] = shader$z;
var name$y = "boundingBoxRendererUboDeclaration"
  , shader$y = `layout(std140,column_major) uniform;
uniform BoundingBoxRenderer {
vec4 color;
mat4 world;
mat4 viewProjection;
mat4 viewProjectionR;
};
`;
ShaderStore.IncludesShadersStore[name$y] = shader$y;
var name$x = "boundingBoxRendererPixelShader"
  , shader$x = `#include<__decl__boundingBoxRendererFragment>
void main(void) {
gl_FragColor=color;
}`;
ShaderStore.ShadersStore[name$x] = shader$x;
var name$w = "boundingBoxRendererVertexDeclaration"
  , shader$w = `uniform mat4 world;
uniform mat4 viewProjection;
#ifdef MULTIVIEW
uniform mat4 viewProjectionR;
#endif
`;
ShaderStore.IncludesShadersStore[name$w] = shader$w;
var name$v = "boundingBoxRendererVertexShader"
  , shader$v = `
attribute vec3 position;
#include<__decl__boundingBoxRendererVertex>
void main(void) {
vec4 worldPos=world*vec4(position,1.0);
#ifdef MULTIVIEW
if (gl_ViewID_OVR == 0u) {
gl_Position=viewProjection*worldPos;
} else {
gl_Position=viewProjectionR*worldPos;
}
#else
gl_Position=viewProjection*worldPos;
#endif
}
`;
ShaderStore.ShadersStore[name$v] = shader$v;
Object.defineProperty(Scene.prototype, "forceShowBoundingBoxes", {
    get: function() {
        return this._forceShowBoundingBoxes || !1
    },
    set: function(i) {
        this._forceShowBoundingBoxes = i,
        i && this.getBoundingBoxRenderer()
    },
    enumerable: !0,
    configurable: !0
});
Scene.prototype.getBoundingBoxRenderer = function() {
    return this._boundingBoxRenderer || (this._boundingBoxRenderer = new BoundingBoxRenderer(this)),
    this._boundingBoxRenderer
}
;
Object.defineProperty(AbstractMesh.prototype, "showBoundingBox", {
    get: function() {
        return this._showBoundingBox || !1
    },
    set: function(i) {
        this._showBoundingBox = i,
        i && this.getScene().getBoundingBoxRenderer()
    },
    enumerable: !0,
    configurable: !0
});
var BoundingBoxRenderer = function() {
    function i(e) {
        this.name = SceneComponentConstants.NAME_BOUNDINGBOXRENDERER,
        this.frontColor = new Color3(1,1,1),
        this.backColor = new Color3(.1,.1,.1),
        this.showBackLines = !0,
        this.onBeforeBoxRenderingObservable = new Observable,
        this.onAfterBoxRenderingObservable = new Observable,
        this.onResourcesReadyObservable = new Observable,
        this.enabled = !0,
        this.renderList = new SmartArray(32),
        this._vertexBuffers = {},
        this._fillIndexBuffer = null,
        this._fillIndexData = null,
        this.scene = e,
        e._addComponent(this),
        this._uniformBufferFront = new UniformBuffer(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererFront"),
        this._buildUniformLayout(this._uniformBufferFront),
        this._uniformBufferBack = new UniformBuffer(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererBack"),
        this._buildUniformLayout(this._uniformBufferBack)
    }
    return i.prototype._buildUniformLayout = function(e) {
        e.addUniform("color", 4),
        e.addUniform("world", 16),
        e.addUniform("viewProjection", 16),
        e.addUniform("viewProjectionR", 16),
        e.create()
    }
    ,
    i.prototype.register = function() {
        this.scene._beforeEvaluateActiveMeshStage.registerStep(SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset),
        this.scene._preActiveMeshStage.registerStep(SceneComponentConstants.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER, this, this._preActiveMesh),
        this.scene._evaluateSubMeshStage.registerStep(SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh),
        this.scene._afterRenderingGroupDrawStage.registerStep(SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER, this, this.render)
    }
    ,
    i.prototype._evaluateSubMesh = function(e, t) {
        if (e.showSubMeshesBoundingBox) {
            var r = t.getBoundingInfo();
            r != null && (r.boundingBox._tag = e.renderingGroupId,
            this.renderList.push(r.boundingBox))
        }
    }
    ,
    i.prototype._preActiveMesh = function(e) {
        if (e.showBoundingBox || this.scene.forceShowBoundingBoxes) {
            var t = e.getBoundingInfo();
            t.boundingBox._tag = e.renderingGroupId,
            this.renderList.push(t.boundingBox)
        }
    }
    ,
    i.prototype._prepareResources = function() {
        if (!this._colorShader) {
            this._colorShader = new ShaderMaterial("colorShader",this.scene,"boundingBoxRenderer",{
                attributes: [VertexBuffer.PositionKind],
                uniforms: ["world", "viewProjection", "color"],
                uniformBuffers: ["BoundingBoxRenderer"]
            },!1),
            this._colorShader.reservedDataStore = {
                hidden: !0
            },
            this._colorShaderForOcclusionQuery = new ShaderMaterial("colorShaderOccQuery",this.scene,"boundingBoxRenderer",{
                attributes: [VertexBuffer.PositionKind],
                uniforms: ["world", "viewProjection", "color"],
                uniformBuffers: ["BoundingBoxRenderer"]
            },!0),
            this._colorShaderForOcclusionQuery.reservedDataStore = {
                hidden: !0
            };
            var e = this.scene.getEngine()
              , t = CreateBoxVertexData({
                size: 1
            });
            this._vertexBuffers[VertexBuffer.PositionKind] = new VertexBuffer(e,t.positions,VertexBuffer.PositionKind,!1),
            this._createIndexBuffer(),
            this._fillIndexData = t.indices,
            this.onResourcesReadyObservable.notifyObservers(this)
        }
    }
    ,
    i.prototype._createIndexBuffer = function() {
        var e = this.scene.getEngine();
        this._indexBuffer = e.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])
    }
    ,
    i.prototype.rebuild = function() {
        var e = this._vertexBuffers[VertexBuffer.PositionKind];
        e && e._rebuild(),
        this._createIndexBuffer()
    }
    ,
    i.prototype.reset = function() {
        this.renderList.reset()
    }
    ,
    i.prototype.render = function(e) {
        var t, r;
        if (!(this.renderList.length === 0 || !this.enabled) && (this._prepareResources(),
        !!this._colorShader.isReady())) {
            var n = this.scene.getEngine();
            n.setDepthWrite(!1);
            for (var o = this.frontColor.toColor4(), a = this.backColor.toColor4(), s = this.scene.getTransformMatrix(), l = 0; l < this.renderList.length; l++) {
                var u = this.renderList.data[l];
                if (u._tag === e) {
                    this._createWrappersForBoundingBox(u),
                    this.onBeforeBoxRenderingObservable.notifyObservers(u);
                    var c = u.minimum
                      , h = u.maximum
                      , f = h.subtract(c)
                      , d = c.add(f.scale(.5))
                      , _ = Matrix.Scaling(f.x, f.y, f.z).multiply(Matrix.Translation(d.x, d.y, d.z)).multiply(u.getWorldMatrix())
                      , g = n.useReverseDepthBuffer;
                    if (this.showBackLines) {
                        var m = (t = u._drawWrapperBack) !== null && t !== void 0 ? t : this._colorShader._getDrawWrapper();
                        this._colorShader._preBind(m),
                        n.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect()),
                        g ? n.setDepthFunctionToLessOrEqual() : n.setDepthFunctionToGreaterOrEqual(),
                        this._uniformBufferBack.bindToEffect(m.effect, "BoundingBoxRenderer"),
                        this._uniformBufferBack.updateDirectColor4("color", a),
                        this._uniformBufferBack.updateMatrix("world", _),
                        this._uniformBufferBack.updateMatrix("viewProjection", s),
                        this._uniformBufferBack.update(),
                        n.drawElementsType(Material.LineListDrawMode, 0, 24)
                    }
                    var v = (r = u._drawWrapperFront) !== null && r !== void 0 ? r : this._colorShader._getDrawWrapper();
                    this._colorShader._preBind(v),
                    n.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect()),
                    g ? n.setDepthFunctionToGreater() : n.setDepthFunctionToLess(),
                    this._uniformBufferFront.bindToEffect(v.effect, "BoundingBoxRenderer"),
                    this._uniformBufferFront.updateDirectColor4("color", o),
                    this._uniformBufferFront.updateMatrix("world", _),
                    this._uniformBufferFront.updateMatrix("viewProjection", s),
                    this._uniformBufferFront.update(),
                    n.drawElementsType(Material.LineListDrawMode, 0, 24),
                    this.onAfterBoxRenderingObservable.notifyObservers(u)
                }
            }
            this._colorShader.unbind(),
            n.setDepthFunctionToLessOrEqual(),
            n.setDepthWrite(!0)
        }
    }
    ,
    i.prototype._createWrappersForBoundingBox = function(e) {
        if (!e._drawWrapperFront) {
            var t = this.scene.getEngine();
            e._drawWrapperFront = new DrawWrapper(t),
            e._drawWrapperBack = new DrawWrapper(t),
            e._drawWrapperFront.setEffect(this._colorShader.getEffect()),
            e._drawWrapperBack.setEffect(this._colorShader.getEffect())
        }
    }
    ,
    i.prototype.renderOcclusionBoundingBox = function(e) {
        var t = this.scene.getEngine();
        this._renderPassIdForOcclusionQuery === void 0 && (this._renderPassIdForOcclusionQuery = t.createRenderPassId("Render pass for occlusion query"));
        var r = t.currentRenderPassId;
        t.currentRenderPassId = this._renderPassIdForOcclusionQuery,
        this._prepareResources();
        var n = e.subMeshes[0];
        if (!this._colorShaderForOcclusionQuery.isReady(e, void 0, n) || !e.hasBoundingInfo) {
            t.currentRenderPassId = r;
            return
        }
        this._fillIndexBuffer || (this._fillIndexBuffer = t.createIndexBuffer(this._fillIndexData));
        var o = t.useReverseDepthBuffer;
        t.setDepthWrite(!1),
        t.setColorWrite(!1);
        var a = e.getBoundingInfo().boundingBox
          , s = a.minimum
          , l = a.maximum
          , u = l.subtract(s)
          , c = s.add(u.scale(.5))
          , h = Matrix.Scaling(u.x, u.y, u.z).multiply(Matrix.Translation(c.x, c.y, c.z)).multiply(a.getWorldMatrix())
          , f = n._drawWrapper;
        this._colorShaderForOcclusionQuery._preBind(f),
        t.bindBuffers(this._vertexBuffers, this._fillIndexBuffer, f.effect),
        o ? t.setDepthFunctionToGreater() : t.setDepthFunctionToLess(),
        this.scene.resetCachedMaterial(),
        this._uniformBufferFront.bindToEffect(f.effect, "BoundingBoxRenderer"),
        this._uniformBufferFront.updateMatrix("world", h),
        this._uniformBufferFront.updateMatrix("viewProjection", this.scene.getTransformMatrix()),
        this._uniformBufferFront.update(),
        t.drawElementsType(Material.TriangleFillMode, 0, 36),
        this._colorShaderForOcclusionQuery.unbind(),
        t.setDepthFunctionToLessOrEqual(),
        t.setDepthWrite(!0),
        t.setColorWrite(!0),
        t.currentRenderPassId = r
    }
    ,
    i.prototype.dispose = function() {
        if (this._renderPassIdForOcclusionQuery !== void 0 && (this.scene.getEngine().releaseRenderPassId(this._renderPassIdForOcclusionQuery),
        this._renderPassIdForOcclusionQuery = void 0),
        !!this._colorShader) {
            this.onBeforeBoxRenderingObservable.clear(),
            this.onAfterBoxRenderingObservable.clear(),
            this.onResourcesReadyObservable.clear(),
            this.renderList.dispose(),
            this._colorShader.dispose(),
            this._colorShaderForOcclusionQuery.dispose(),
            this._uniformBufferFront.dispose(),
            this._uniformBufferBack.dispose();
            var e = this._vertexBuffers[VertexBuffer.PositionKind];
            e && (e.dispose(),
            this._vertexBuffers[VertexBuffer.PositionKind] = null),
            this.scene.getEngine()._releaseBuffer(this._indexBuffer),
            this._fillIndexBuffer && (this.scene.getEngine()._releaseBuffer(this._fillIndexBuffer),
            this._fillIndexBuffer = null)
        }
    }
    ,
    i
}()
  , DataReader = function() {
    function i(e) {
        this.byteOffset = 0,
        this.buffer = e
    }
    return i.prototype.loadAsync = function(e) {
        var t = this;
        return this.buffer.readAsync(this.byteOffset, e).then(function(r) {
            t._dataView = new DataView(r.buffer,r.byteOffset,r.byteLength),
            t._dataByteOffset = 0
        })
    }
    ,
    i.prototype.readUint32 = function() {
        var e = this._dataView.getUint32(this._dataByteOffset, !0);
        return this._dataByteOffset += 4,
        this.byteOffset += 4,
        e
    }
    ,
    i.prototype.readUint8Array = function(e) {
        var t = new Uint8Array(this._dataView.buffer,this._dataView.byteOffset + this._dataByteOffset,e);
        return this._dataByteOffset += e,
        this.byteOffset += e,
        t
    }
    ,
    i.prototype.readString = function(e) {
        return Decode(this.readUint8Array(e))
    }
    ,
    i.prototype.skipBytes = function(e) {
        this._dataByteOffset += e,
        this.byteOffset += e
    }
    ,
    i
}();
function validateAsync(i, e, t, r) {
    var n = {
        externalResourceFunction: function(o) {
            return r(o).then(function(a) {
                return new Uint8Array(a)
            })
        }
    };
    return t && (n.uri = e === "file:" ? t : e + t),
    i instanceof ArrayBuffer ? GLTFValidator.validateBytes(new Uint8Array(i), n) : GLTFValidator.validateString(i, n)
}
function workerFunc$1() {
    var i = [];
    onmessage = function(e) {
        var t = e.data;
        switch (t.id) {
        case "init":
            {
                importScripts(t.url);
                break
            }
        case "validate":
            {
                validateAsync(t.data, t.rootUrl, t.fileName, function(r) {
                    return new Promise(function(n, o) {
                        var a = i.length;
                        i.push({
                            resolve: n,
                            reject: o
                        }),
                        postMessage({
                            id: "getExternalResource",
                            index: a,
                            uri: r
                        })
                    }
                    )
                }).then(function(r) {
                    postMessage({
                        id: "validate.resolve",
                        value: r
                    })
                }, function(r) {
                    postMessage({
                        id: "validate.reject",
                        reason: r
                    })
                });
                break
            }
        case "getExternalResource.resolve":
            {
                i[t.index].resolve(t.value);
                break
            }
        case "getExternalResource.reject":
            {
                i[t.index].reject(t.reason);
                break
            }
        }
    }
}
var GLTFValidation = function() {
    function i() {}
    return i.ValidateAsync = function(e, t, r, n) {
        var o = this;
        return typeof Worker == "function" ? new Promise(function(a, s) {
            var l = validateAsync + "(" + workerFunc$1 + ")()"
              , u = URL.createObjectURL(new Blob([l],{
                type: "application/javascript"
            }))
              , c = new Worker(u)
              , h = function(d) {
                c.removeEventListener("error", h),
                c.removeEventListener("message", f),
                s(d)
            }
              , f = function(d) {
                var _ = d.data;
                switch (_.id) {
                case "getExternalResource":
                    {
                        n(_.uri).then(function(g) {
                            c.postMessage({
                                id: "getExternalResource.resolve",
                                index: _.index,
                                value: g
                            }, [g])
                        }, function(g) {
                            c.postMessage({
                                id: "getExternalResource.reject",
                                index: _.index,
                                reason: g
                            })
                        });
                        break
                    }
                case "validate.resolve":
                    {
                        c.removeEventListener("error", h),
                        c.removeEventListener("message", f),
                        a(_.value);
                        break
                    }
                case "validate.reject":
                    c.removeEventListener("error", h),
                    c.removeEventListener("message", f),
                    s(_.reason)
                }
            };
            c.addEventListener("error", h),
            c.addEventListener("message", f),
            c.postMessage({
                id: "init",
                url: o.Configuration.url
            }),
            c.postMessage({
                id: "validate",
                data: e,
                rootUrl: t,
                fileName: r
            })
        }
        ) : (this._LoadScriptPromise || (this._LoadScriptPromise = Tools.LoadScriptAsync(this.Configuration.url)),
        this._LoadScriptPromise.then(function() {
            return validateAsync(e, t, r, n)
        }))
    }
    ,
    i.Configuration = {
        url: "https://preview.babylonjs.com/gltf_validator.js"
    },
    i
}();
function readAsync(i, e, t) {
    try {
        return Promise.resolve(new Uint8Array(i,e,t))
    } catch (r) {
        return Promise.reject(r)
    }
}
var GLTFLoaderCoordinateSystemMode;
(function(i) {
    i[i.AUTO = 0] = "AUTO",
    i[i.FORCE_RIGHT_HANDED = 1] = "FORCE_RIGHT_HANDED"
}
)(GLTFLoaderCoordinateSystemMode || (GLTFLoaderCoordinateSystemMode = {}));
var GLTFLoaderAnimationStartMode;
(function(i) {
    i[i.NONE = 0] = "NONE",
    i[i.FIRST = 1] = "FIRST",
    i[i.ALL = 2] = "ALL"
}
)(GLTFLoaderAnimationStartMode || (GLTFLoaderAnimationStartMode = {}));
var GLTFLoaderState;
(function(i) {
    i[i.LOADING = 0] = "LOADING",
    i[i.READY = 1] = "READY",
    i[i.COMPLETE = 2] = "COMPLETE"
}
)(GLTFLoaderState || (GLTFLoaderState = {}));
var GLTFFileLoader = function() {
    function i() {
        this.onParsedObservable = new Observable,
        this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO,
        this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST,
        this.compileMaterials = !1,
        this.useClipPlane = !1,
        this.compileShadowGenerators = !1,
        this.transparencyAsCoverage = !1,
        this.useRangeRequests = !1,
        this.createInstances = !0,
        this.alwaysComputeBoundingBox = !1,
        this.loadAllMaterials = !1,
        this.useSRGBBuffers = !0,
        this.preprocessUrlAsync = function(e) {
            return Promise.resolve(e)
        }
        ,
        this.onMeshLoadedObservable = new Observable,
        this.onTextureLoadedObservable = new Observable,
        this.onMaterialLoadedObservable = new Observable,
        this.onCameraLoadedObservable = new Observable,
        this.onCompleteObservable = new Observable,
        this.onErrorObservable = new Observable,
        this.onDisposeObservable = new Observable,
        this.onExtensionLoadedObservable = new Observable,
        this.validate = !1,
        this.onValidatedObservable = new Observable,
        this._loader = null,
        this._state = null,
        this._requests = new Array,
        this.name = "gltf",
        this.extensions = {
            ".gltf": {
                isBinary: !1
            },
            ".glb": {
                isBinary: !0
            }
        },
        this.onLoaderStateChangedObservable = new Observable,
        this._logIndentLevel = 0,
        this._loggingEnabled = !1,
        this._log = this._logDisabled,
        this._capturePerformanceCounters = !1,
        this._startPerformanceCounter = this._startPerformanceCounterDisabled,
        this._endPerformanceCounter = this._endPerformanceCounterDisabled
    }
    return Object.defineProperty(i.prototype, "onParsed", {
        set: function(e) {
            this._onParsedObserver && this.onParsedObservable.remove(this._onParsedObserver),
            this._onParsedObserver = this.onParsedObservable.add(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "onMeshLoaded", {
        set: function(e) {
            this._onMeshLoadedObserver && this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver),
            this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "onTextureLoaded", {
        set: function(e) {
            this._onTextureLoadedObserver && this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver),
            this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "onMaterialLoaded", {
        set: function(e) {
            this._onMaterialLoadedObserver && this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver),
            this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "onCameraLoaded", {
        set: function(e) {
            this._onCameraLoadedObserver && this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver),
            this._onCameraLoadedObserver = this.onCameraLoadedObservable.add(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "onComplete", {
        set: function(e) {
            this._onCompleteObserver && this.onCompleteObservable.remove(this._onCompleteObserver),
            this._onCompleteObserver = this.onCompleteObservable.add(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "onError", {
        set: function(e) {
            this._onErrorObserver && this.onErrorObservable.remove(this._onErrorObserver),
            this._onErrorObserver = this.onErrorObservable.add(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "onDispose", {
        set: function(e) {
            this._onDisposeObserver && this.onDisposeObservable.remove(this._onDisposeObserver),
            this._onDisposeObserver = this.onDisposeObservable.add(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "onExtensionLoaded", {
        set: function(e) {
            this._onExtensionLoadedObserver && this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver),
            this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "loggingEnabled", {
        get: function() {
            return this._loggingEnabled
        },
        set: function(e) {
            this._loggingEnabled !== e && (this._loggingEnabled = e,
            this._loggingEnabled ? this._log = this._logEnabled : this._log = this._logDisabled)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "capturePerformanceCounters", {
        get: function() {
            return this._capturePerformanceCounters
        },
        set: function(e) {
            this._capturePerformanceCounters !== e && (this._capturePerformanceCounters = e,
            this._capturePerformanceCounters ? (this._startPerformanceCounter = this._startPerformanceCounterEnabled,
            this._endPerformanceCounter = this._endPerformanceCounterEnabled) : (this._startPerformanceCounter = this._startPerformanceCounterDisabled,
            this._endPerformanceCounter = this._endPerformanceCounterDisabled))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "onValidated", {
        set: function(e) {
            this._onValidatedObserver && this.onValidatedObservable.remove(this._onValidatedObserver),
            this._onValidatedObserver = this.onValidatedObservable.add(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.dispose = function() {
        this._loader && (this._loader.dispose(),
        this._loader = null);
        for (var e = 0, t = this._requests; e < t.length; e++) {
            var r = t[e];
            r.abort()
        }
        this._requests.length = 0,
        delete this._progressCallback,
        this.preprocessUrlAsync = function(n) {
            return Promise.resolve(n)
        }
        ,
        this.onMeshLoadedObservable.clear(),
        this.onTextureLoadedObservable.clear(),
        this.onMaterialLoadedObservable.clear(),
        this.onCameraLoadedObservable.clear(),
        this.onCompleteObservable.clear(),
        this.onExtensionLoadedObservable.clear(),
        this.onDisposeObservable.notifyObservers(void 0),
        this.onDisposeObservable.clear()
    }
    ,
    i.prototype.loadFile = function(e, t, r, n, o, a) {
        var s = this;
        if (this._progressCallback = n,
        o) {
            if (this.useRangeRequests) {
                this.validate && Logger$2.Warn("glTF validation is not supported when range requests are enabled");
                var l = {
                    abort: function() {},
                    onCompleteObservable: new Observable
                }
                  , u = {
                    readAsync: function(c, h) {
                        return new Promise(function(f, d) {
                            s._loadFile(e, t, function(_) {
                                f(new Uint8Array(_))
                            }, !0, function(_) {
                                d(_)
                            }, function(_) {
                                _.setRequestHeader("Range", "bytes=" + c + "-" + (c + h - 1))
                            })
                        }
                        )
                    },
                    byteLength: 0
                };
                return this._unpackBinaryAsync(new DataReader(u)).then(function(c) {
                    l.onCompleteObservable.notifyObservers(l),
                    r(c)
                }, a ? function(c) {
                    return a(void 0, c)
                }
                : void 0),
                l
            }
            return this._loadFile(e, t, function(c) {
                var h = c;
                s._unpackBinaryAsync(new DataReader({
                    readAsync: function(f, d) {
                        return readAsync(h, f, d)
                    },
                    byteLength: h.byteLength
                })).then(function(f) {
                    r(f)
                }, a ? function(f) {
                    return a(void 0, f)
                }
                : void 0)
            }, !0, a)
        }
        return this._loadFile(e, t, function(c) {
            if (t.name)
                s._validate(e, c, "file:", t.name);
            else {
                var h = t;
                s._validate(e, c, Tools.GetFolderPath(h), Tools.GetFilename(h))
            }
            r({
                json: s._parseJson(c)
            })
        }, o, a)
    }
    ,
    i.prototype.importMeshAsync = function(e, t, r, n, o, a) {
        var s = this;
        return Promise.resolve().then(function() {
            return s.onParsedObservable.notifyObservers(r),
            s.onParsedObservable.clear(),
            s._log("Loading " + (a || "")),
            s._loader = s._getLoader(r),
            s._loader.importMeshAsync(e, t, null, r, n, o, a)
        })
    }
    ,
    i.prototype.loadAsync = function(e, t, r, n, o) {
        var a = this;
        return Promise.resolve().then(function() {
            return a.onParsedObservable.notifyObservers(t),
            a.onParsedObservable.clear(),
            a._log("Loading " + (o || "")),
            a._loader = a._getLoader(t),
            a._loader.loadAsync(e, t, r, n, o)
        })
    }
    ,
    i.prototype.loadAssetContainerAsync = function(e, t, r, n, o) {
        var a = this;
        return Promise.resolve().then(function() {
            a.onParsedObservable.notifyObservers(t),
            a.onParsedObservable.clear(),
            a._log("Loading " + (o || "")),
            a._loader = a._getLoader(t);
            var s = new AssetContainer(e)
              , l = [];
            a.onMaterialLoadedObservable.add(function(h) {
                l.push(h)
            });
            var u = [];
            a.onTextureLoadedObservable.add(function(h) {
                u.push(h)
            });
            var c = [];
            return a.onCameraLoadedObservable.add(function(h) {
                c.push(h)
            }),
            a._loader.importMeshAsync(null, e, s, t, r, n, o).then(function(h) {
                return Array.prototype.push.apply(s.geometries, h.geometries),
                Array.prototype.push.apply(s.meshes, h.meshes),
                Array.prototype.push.apply(s.particleSystems, h.particleSystems),
                Array.prototype.push.apply(s.skeletons, h.skeletons),
                Array.prototype.push.apply(s.animationGroups, h.animationGroups),
                Array.prototype.push.apply(s.materials, l),
                Array.prototype.push.apply(s.textures, u),
                Array.prototype.push.apply(s.lights, h.lights),
                Array.prototype.push.apply(s.transformNodes, h.transformNodes),
                Array.prototype.push.apply(s.cameras, c),
                s
            })
        })
    }
    ,
    i.prototype.canDirectLoad = function(e) {
        return e.indexOf("asset") !== -1 && e.indexOf("version") !== -1 || StringTools.StartsWith(e, "data:base64," + i.magicBase64Encoded) || StringTools.StartsWith(e, "data:;base64," + i.magicBase64Encoded) || StringTools.StartsWith(e, "data:application/octet-stream;base64," + i.magicBase64Encoded) || StringTools.StartsWith(e, "data:model/gltf-binary;base64," + i.magicBase64Encoded)
    }
    ,
    i.prototype.directLoad = function(e, t) {
        if (StringTools.StartsWith(t, "base64," + i.magicBase64Encoded) || StringTools.StartsWith(t, ";base64," + i.magicBase64Encoded) || StringTools.StartsWith(t, "application/octet-stream;base64," + i.magicBase64Encoded) || StringTools.StartsWith(t, "model/gltf-binary;base64," + i.magicBase64Encoded)) {
            var r = DecodeBase64UrlToBinary(t);
            return this._validate(e, r),
            this._unpackBinaryAsync(new DataReader({
                readAsync: function(n, o) {
                    return readAsync(r, n, o)
                },
                byteLength: r.byteLength
            }))
        }
        return this._validate(e, t),
        Promise.resolve({
            json: this._parseJson(t)
        })
    }
    ,
    i.prototype.createPlugin = function() {
        return new i
    }
    ,
    Object.defineProperty(i.prototype, "loaderState", {
        get: function() {
            return this._state
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.whenCompleteAsync = function() {
        var e = this;
        return new Promise(function(t, r) {
            e.onCompleteObservable.addOnce(function() {
                t()
            }),
            e.onErrorObservable.addOnce(function(n) {
                r(n)
            })
        }
        )
    }
    ,
    i.prototype._setState = function(e) {
        this._state !== e && (this._state = e,
        this.onLoaderStateChangedObservable.notifyObservers(this._state),
        this._log(GLTFLoaderState[this._state]))
    }
    ,
    i.prototype._loadFile = function(e, t, r, n, o, a) {
        var s = this
          , l = e._loadFile(t, r, function(u) {
            s._onProgress(u, l)
        }, !0, n, o, a);
        return l.onCompleteObservable.add(function(u) {
            s._requests.splice(s._requests.indexOf(u), 1)
        }),
        this._requests.push(l),
        l
    }
    ,
    i.prototype._onProgress = function(e, t) {
        if (!!this._progressCallback) {
            t._lengthComputable = e.lengthComputable,
            t._loaded = e.loaded,
            t._total = e.total;
            for (var r = !0, n = 0, o = 0, a = 0, s = this._requests; a < s.length; a++) {
                var l = s[a];
                if (l._lengthComputable === void 0 || l._loaded === void 0 || l._total === void 0)
                    return;
                r = r && l._lengthComputable,
                n += l._loaded,
                o += l._total
            }
            this._progressCallback({
                lengthComputable: r,
                loaded: n,
                total: r ? o : 0
            })
        }
    }
    ,
    i.prototype._validate = function(e, t, r, n) {
        var o = this;
        r === void 0 && (r = ""),
        n === void 0 && (n = ""),
        this.validate && (this._startPerformanceCounter("Validate JSON"),
        GLTFValidation.ValidateAsync(t, r, n, function(a) {
            return o.preprocessUrlAsync(r + a).then(function(s) {
                return e._loadFileAsync(s, void 0, !0, !0)
            })
        }).then(function(a) {
            o._endPerformanceCounter("Validate JSON"),
            o.onValidatedObservable.notifyObservers(a),
            o.onValidatedObservable.clear()
        }, function(a) {
            o._endPerformanceCounter("Validate JSON"),
            Tools.Warn("Failed to validate: " + a.message),
            o.onValidatedObservable.clear()
        }))
    }
    ,
    i.prototype._getLoader = function(e) {
        var t = e.json.asset || {};
        this._log("Asset version: " + t.version),
        t.minVersion && this._log("Asset minimum version: " + t.minVersion),
        t.generator && this._log("Asset generator: " + t.generator);
        var r = i._parseVersion(t.version);
        if (!r)
            throw new Error("Invalid version: " + t.version);
        if (t.minVersion !== void 0) {
            var n = i._parseVersion(t.minVersion);
            if (!n)
                throw new Error("Invalid minimum version: " + t.minVersion);
            if (i._compareVersion(n, {
                major: 2,
                minor: 0
            }) > 0)
                throw new Error("Incompatible minimum version: " + t.minVersion)
        }
        var o = {
            1: i._CreateGLTF1Loader,
            2: i._CreateGLTF2Loader
        }
          , a = o[r.major];
        if (!a)
            throw new Error("Unsupported version: " + t.version);
        return a(this)
    }
    ,
    i.prototype._parseJson = function(e) {
        this._startPerformanceCounter("Parse JSON"),
        this._log("JSON length: " + e.length);
        var t = JSON.parse(e);
        return this._endPerformanceCounter("Parse JSON"),
        t
    }
    ,
    i.prototype._unpackBinaryAsync = function(e) {
        var t = this;
        return this._startPerformanceCounter("Unpack Binary"),
        e.loadAsync(20).then(function() {
            var r = {
                Magic: 1179937895
            }
              , n = e.readUint32();
            if (n !== r.Magic)
                throw new Error("Unexpected magic: " + n);
            var o = e.readUint32();
            t.loggingEnabled && t._log("Binary version: " + o);
            var a = e.readUint32();
            if (e.buffer.byteLength !== 0 && a !== e.buffer.byteLength)
                throw new Error("Length in header does not match actual data length: " + a + " != " + e.buffer.byteLength);
            var s;
            switch (o) {
            case 1:
                {
                    s = t._unpackBinaryV1Async(e, a);
                    break
                }
            case 2:
                {
                    s = t._unpackBinaryV2Async(e, a);
                    break
                }
            default:
                throw new Error("Unsupported version: " + o)
            }
            return t._endPerformanceCounter("Unpack Binary"),
            s
        })
    }
    ,
    i.prototype._unpackBinaryV1Async = function(e, t) {
        var r = {
            JSON: 0
        }
          , n = e.readUint32()
          , o = e.readUint32();
        if (o !== r.JSON)
            throw new Error("Unexpected content format: " + o);
        var a = t - e.byteOffset
          , s = {
            json: this._parseJson(e.readString(n)),
            bin: null
        };
        if (a !== 0) {
            var l = e.byteOffset;
            s.bin = {
                readAsync: function(u, c) {
                    return e.buffer.readAsync(l + u, c)
                },
                byteLength: a
            }
        }
        return Promise.resolve(s)
    }
    ,
    i.prototype._unpackBinaryV2Async = function(e, t) {
        var r = this
          , n = {
            JSON: 1313821514,
            BIN: 5130562
        }
          , o = e.readUint32()
          , a = e.readUint32();
        if (a !== n.JSON)
            throw new Error("First chunk format is not JSON");
        return e.byteOffset + o === t ? e.loadAsync(o).then(function() {
            return {
                json: r._parseJson(e.readString(o)),
                bin: null
            }
        }) : e.loadAsync(o + 8).then(function() {
            var s = {
                json: r._parseJson(e.readString(o)),
                bin: null
            }
              , l = function() {
                var u = e.readUint32()
                  , c = e.readUint32();
                switch (c) {
                case n.JSON:
                    throw new Error("Unexpected JSON chunk");
                case n.BIN:
                    {
                        var h = e.byteOffset;
                        s.bin = {
                            readAsync: function(f, d) {
                                return e.buffer.readAsync(h + f, d)
                            },
                            byteLength: u
                        },
                        e.skipBytes(u);
                        break
                    }
                default:
                    {
                        e.skipBytes(u);
                        break
                    }
                }
                return e.byteOffset !== t ? e.loadAsync(8).then(l) : Promise.resolve(s)
            };
            return l()
        })
    }
    ,
    i._parseVersion = function(e) {
        if (e === "1.0" || e === "1.0.1")
            return {
                major: 1,
                minor: 0
            };
        var t = (e + "").match(/^(\d+)\.(\d+)/);
        return t ? {
            major: parseInt(t[1]),
            minor: parseInt(t[2])
        } : null
    }
    ,
    i._compareVersion = function(e, t) {
        return e.major > t.major ? 1 : e.major < t.major ? -1 : e.minor > t.minor ? 1 : e.minor < t.minor ? -1 : 0
    }
    ,
    i.prototype._logOpen = function(e) {
        this._log(e),
        this._logIndentLevel++
    }
    ,
    i.prototype._logClose = function() {
        --this._logIndentLevel
    }
    ,
    i.prototype._logEnabled = function(e) {
        var t = i._logSpaces.substr(0, this._logIndentLevel * 2);
        Logger$2.Log("" + t + e)
    }
    ,
    i.prototype._logDisabled = function(e) {}
    ,
    i.prototype._startPerformanceCounterEnabled = function(e) {
        Tools.StartPerformanceCounter(e)
    }
    ,
    i.prototype._startPerformanceCounterDisabled = function(e) {}
    ,
    i.prototype._endPerformanceCounterEnabled = function(e) {
        Tools.EndPerformanceCounter(e)
    }
    ,
    i.prototype._endPerformanceCounterDisabled = function(e) {}
    ,
    i.IncrementalLoading = !0,
    i.HomogeneousCoordinates = !1,
    i.magicBase64Encoded = "Z2xURg",
    i._logSpaces = "                                ",
    i
}();
SceneLoader && SceneLoader.RegisterPlugin(new GLTFFileLoader);
var EComponentType;
(function(i) {
    i[i.BYTE = 5120] = "BYTE",
    i[i.UNSIGNED_BYTE = 5121] = "UNSIGNED_BYTE",
    i[i.SHORT = 5122] = "SHORT",
    i[i.UNSIGNED_SHORT = 5123] = "UNSIGNED_SHORT",
    i[i.FLOAT = 5126] = "FLOAT"
}
)(EComponentType || (EComponentType = {}));
var EShaderType;
(function(i) {
    i[i.FRAGMENT = 35632] = "FRAGMENT",
    i[i.VERTEX = 35633] = "VERTEX"
}
)(EShaderType || (EShaderType = {}));
var EParameterType;
(function(i) {
    i[i.BYTE = 5120] = "BYTE",
    i[i.UNSIGNED_BYTE = 5121] = "UNSIGNED_BYTE",
    i[i.SHORT = 5122] = "SHORT",
    i[i.UNSIGNED_SHORT = 5123] = "UNSIGNED_SHORT",
    i[i.INT = 5124] = "INT",
    i[i.UNSIGNED_INT = 5125] = "UNSIGNED_INT",
    i[i.FLOAT = 5126] = "FLOAT",
    i[i.FLOAT_VEC2 = 35664] = "FLOAT_VEC2",
    i[i.FLOAT_VEC3 = 35665] = "FLOAT_VEC3",
    i[i.FLOAT_VEC4 = 35666] = "FLOAT_VEC4",
    i[i.INT_VEC2 = 35667] = "INT_VEC2",
    i[i.INT_VEC3 = 35668] = "INT_VEC3",
    i[i.INT_VEC4 = 35669] = "INT_VEC4",
    i[i.BOOL = 35670] = "BOOL",
    i[i.BOOL_VEC2 = 35671] = "BOOL_VEC2",
    i[i.BOOL_VEC3 = 35672] = "BOOL_VEC3",
    i[i.BOOL_VEC4 = 35673] = "BOOL_VEC4",
    i[i.FLOAT_MAT2 = 35674] = "FLOAT_MAT2",
    i[i.FLOAT_MAT3 = 35675] = "FLOAT_MAT3",
    i[i.FLOAT_MAT4 = 35676] = "FLOAT_MAT4",
    i[i.SAMPLER_2D = 35678] = "SAMPLER_2D"
}
)(EParameterType || (EParameterType = {}));
var ETextureWrapMode;
(function(i) {
    i[i.CLAMP_TO_EDGE = 33071] = "CLAMP_TO_EDGE",
    i[i.MIRRORED_REPEAT = 33648] = "MIRRORED_REPEAT",
    i[i.REPEAT = 10497] = "REPEAT"
}
)(ETextureWrapMode || (ETextureWrapMode = {}));
var ETextureFilterType;
(function(i) {
    i[i.NEAREST = 9728] = "NEAREST",
    i[i.LINEAR = 9728] = "LINEAR",
    i[i.NEAREST_MIPMAP_NEAREST = 9984] = "NEAREST_MIPMAP_NEAREST",
    i[i.LINEAR_MIPMAP_NEAREST = 9985] = "LINEAR_MIPMAP_NEAREST",
    i[i.NEAREST_MIPMAP_LINEAR = 9986] = "NEAREST_MIPMAP_LINEAR",
    i[i.LINEAR_MIPMAP_LINEAR = 9987] = "LINEAR_MIPMAP_LINEAR"
}
)(ETextureFilterType || (ETextureFilterType = {}));
var ETextureFormat;
(function(i) {
    i[i.ALPHA = 6406] = "ALPHA",
    i[i.RGB = 6407] = "RGB",
    i[i.RGBA = 6408] = "RGBA",
    i[i.LUMINANCE = 6409] = "LUMINANCE",
    i[i.LUMINANCE_ALPHA = 6410] = "LUMINANCE_ALPHA"
}
)(ETextureFormat || (ETextureFormat = {}));
var ECullingType;
(function(i) {
    i[i.FRONT = 1028] = "FRONT",
    i[i.BACK = 1029] = "BACK",
    i[i.FRONT_AND_BACK = 1032] = "FRONT_AND_BACK"
}
)(ECullingType || (ECullingType = {}));
var EBlendingFunction;
(function(i) {
    i[i.ZERO = 0] = "ZERO",
    i[i.ONE = 1] = "ONE",
    i[i.SRC_COLOR = 768] = "SRC_COLOR",
    i[i.ONE_MINUS_SRC_COLOR = 769] = "ONE_MINUS_SRC_COLOR",
    i[i.DST_COLOR = 774] = "DST_COLOR",
    i[i.ONE_MINUS_DST_COLOR = 775] = "ONE_MINUS_DST_COLOR",
    i[i.SRC_ALPHA = 770] = "SRC_ALPHA",
    i[i.ONE_MINUS_SRC_ALPHA = 771] = "ONE_MINUS_SRC_ALPHA",
    i[i.DST_ALPHA = 772] = "DST_ALPHA",
    i[i.ONE_MINUS_DST_ALPHA = 773] = "ONE_MINUS_DST_ALPHA",
    i[i.CONSTANT_COLOR = 32769] = "CONSTANT_COLOR",
    i[i.ONE_MINUS_CONSTANT_COLOR = 32770] = "ONE_MINUS_CONSTANT_COLOR",
    i[i.CONSTANT_ALPHA = 32771] = "CONSTANT_ALPHA",
    i[i.ONE_MINUS_CONSTANT_ALPHA = 32772] = "ONE_MINUS_CONSTANT_ALPHA",
    i[i.SRC_ALPHA_SATURATE = 776] = "SRC_ALPHA_SATURATE"
}
)(EBlendingFunction || (EBlendingFunction = {}));
var GLTFUtils = function() {
    function i() {}
    return i.SetMatrix = function(e, t, r, n, o) {
        var a = null;
        if (r.semantic === "MODEL")
            a = t.getWorldMatrix();
        else if (r.semantic === "PROJECTION")
            a = e.getProjectionMatrix();
        else if (r.semantic === "VIEW")
            a = e.getViewMatrix();
        else if (r.semantic === "MODELVIEWINVERSETRANSPOSE")
            a = Matrix.Transpose(t.getWorldMatrix().multiply(e.getViewMatrix()).invert());
        else if (r.semantic === "MODELVIEW")
            a = t.getWorldMatrix().multiply(e.getViewMatrix());
        else if (r.semantic === "MODELVIEWPROJECTION")
            a = t.getWorldMatrix().multiply(e.getTransformMatrix());
        else if (r.semantic === "MODELINVERSE")
            a = t.getWorldMatrix().invert();
        else if (r.semantic === "VIEWINVERSE")
            a = e.getViewMatrix().invert();
        else if (r.semantic === "PROJECTIONINVERSE")
            a = e.getProjectionMatrix().invert();
        else if (r.semantic === "MODELVIEWINVERSE")
            a = t.getWorldMatrix().multiply(e.getViewMatrix()).invert();
        else if (r.semantic === "MODELVIEWPROJECTIONINVERSE")
            a = t.getWorldMatrix().multiply(e.getTransformMatrix()).invert();
        else if (r.semantic === "MODELINVERSETRANSPOSE")
            a = Matrix.Transpose(t.getWorldMatrix().invert());
        else
            debugger ;if (a)
            switch (r.type) {
            case EParameterType.FLOAT_MAT2:
                o.setMatrix2x2(n, Matrix.GetAsMatrix2x2(a));
                break;
            case EParameterType.FLOAT_MAT3:
                o.setMatrix3x3(n, Matrix.GetAsMatrix3x3(a));
                break;
            case EParameterType.FLOAT_MAT4:
                o.setMatrix(n, a);
                break
            }
    }
    ,
    i.SetUniform = function(e, t, r, n) {
        switch (n) {
        case EParameterType.FLOAT:
            return e.setFloat(t, r),
            !0;
        case EParameterType.FLOAT_VEC2:
            return e.setVector2(t, Vector2.FromArray(r)),
            !0;
        case EParameterType.FLOAT_VEC3:
            return e.setVector3(t, Vector3.FromArray(r)),
            !0;
        case EParameterType.FLOAT_VEC4:
            return e.setVector4(t, Vector4.FromArray(r)),
            !0;
        default:
            return !1
        }
    }
    ,
    i.GetWrapMode = function(e) {
        switch (e) {
        case ETextureWrapMode.CLAMP_TO_EDGE:
            return Texture.CLAMP_ADDRESSMODE;
        case ETextureWrapMode.MIRRORED_REPEAT:
            return Texture.MIRROR_ADDRESSMODE;
        case ETextureWrapMode.REPEAT:
            return Texture.WRAP_ADDRESSMODE;
        default:
            return Texture.WRAP_ADDRESSMODE
        }
    }
    ,
    i.GetByteStrideFromType = function(e) {
        var t = e.type;
        switch (t) {
        case "VEC2":
            return 2;
        case "VEC3":
            return 3;
        case "VEC4":
            return 4;
        case "MAT2":
            return 4;
        case "MAT3":
            return 9;
        case "MAT4":
            return 16;
        default:
            return 1
        }
    }
    ,
    i.GetTextureFilterMode = function(e) {
        switch (e) {
        case ETextureFilterType.LINEAR:
        case ETextureFilterType.LINEAR_MIPMAP_NEAREST:
        case ETextureFilterType.LINEAR_MIPMAP_LINEAR:
            return Texture.TRILINEAR_SAMPLINGMODE;
        case ETextureFilterType.NEAREST:
        case ETextureFilterType.NEAREST_MIPMAP_NEAREST:
            return Texture.NEAREST_SAMPLINGMODE;
        default:
            return Texture.BILINEAR_SAMPLINGMODE
        }
    }
    ,
    i.GetBufferFromBufferView = function(e, t, a, n, o) {
        var a = t.byteOffset + a
          , s = e.loadedBufferViews[t.buffer];
        if (a + n > s.byteLength)
            throw new Error("Buffer access is out of range");
        var l = s.buffer;
        switch (a += s.byteOffset,
        o) {
        case EComponentType.BYTE:
            return new Int8Array(l,a,n);
        case EComponentType.UNSIGNED_BYTE:
            return new Uint8Array(l,a,n);
        case EComponentType.SHORT:
            return new Int16Array(l,a,n);
        case EComponentType.UNSIGNED_SHORT:
            return new Uint16Array(l,a,n);
        default:
            return new Float32Array(l,a,n)
        }
    }
    ,
    i.GetBufferFromAccessor = function(e, t) {
        var r = e.bufferViews[t.bufferView]
          , n = t.count * i.GetByteStrideFromType(t);
        return i.GetBufferFromBufferView(e, r, t.byteOffset, n, t.componentType)
    }
    ,
    i.DecodeBufferToText = function(e) {
        for (var t = "", r = e.byteLength, n = 0; n < r; ++n)
            t += String.fromCharCode(e[n]);
        return t
    }
    ,
    i.GetDefaultMaterial = function(e) {
        if (!i._DefaultMaterial) {
            Effect.ShadersStore.GLTFDefaultMaterialVertexShader = ["precision highp float;", "", "uniform mat4 worldView;", "uniform mat4 projection;", "", "attribute vec3 position;", "", "void main(void)", "{", "    gl_Position = projection * worldView * vec4(position, 1.0);", "}"].join(`
`),
            Effect.ShadersStore.GLTFDefaultMaterialPixelShader = ["precision highp float;", "", "uniform vec4 u_emission;", "", "void main(void)", "{", "    gl_FragColor = u_emission;", "}"].join(`
`);
            var t = {
                vertex: "GLTFDefaultMaterial",
                fragment: "GLTFDefaultMaterial"
            }
              , r = {
                attributes: ["position"],
                uniforms: ["worldView", "projection", "u_emission"],
                samplers: new Array,
                needAlphaBlending: !1
            };
            i._DefaultMaterial = new ShaderMaterial("GLTFDefaultMaterial",e,t,r),
            i._DefaultMaterial.setColor4("u_emission", new Color4(.5,.5,.5,1))
        }
        return i._DefaultMaterial
    }
    ,
    i._DefaultMaterial = null,
    i
}(), ETokenType;
(function(i) {
    i[i.IDENTIFIER = 1] = "IDENTIFIER",
    i[i.UNKNOWN = 2] = "UNKNOWN",
    i[i.END_OF_INPUT = 3] = "END_OF_INPUT"
}
)(ETokenType || (ETokenType = {}));
var Tokenizer = function() {
    function i(e) {
        this._pos = 0,
        this.currentToken = ETokenType.UNKNOWN,
        this.currentIdentifier = "",
        this.currentString = "",
        this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/,
        this._toParse = e,
        this._maxPos = e.length
    }
    return i.prototype.getNextToken = function() {
        if (this.isEnd())
            return ETokenType.END_OF_INPUT;
        if (this.currentString = this.read(),
        this.currentToken = ETokenType.UNKNOWN,
        this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString))
            for (this.currentToken = ETokenType.IDENTIFIER,
            this.currentIdentifier = this.currentString; !this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_"); )
                this.currentIdentifier += this.currentString,
                this.forward();
        return this.currentToken
    }
    ,
    i.prototype.peek = function() {
        return this._toParse[this._pos]
    }
    ,
    i.prototype.read = function() {
        return this._toParse[this._pos++]
    }
    ,
    i.prototype.forward = function() {
        this._pos++
    }
    ,
    i.prototype.isEnd = function() {
        return this._pos >= this._maxPos
    }
    ,
    i
}()
  , glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"]
  , babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"]
  , glTFAnimationPaths = ["translation", "rotation", "scale"]
  , babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"]
  , parseBuffers = function(i, e) {
    for (var t in i) {
        var r = i[t];
        e.buffers[t] = r,
        e.buffersCount++
    }
}
  , parseShaders = function(i, e) {
    for (var t in i) {
        var r = i[t];
        e.shaders[t] = r,
        e.shaderscount++
    }
}
  , parseObject = function(i, e, t) {
    for (var r in i) {
        var n = i[r];
        t[e][r] = n
    }
}
  , normalizeUVs = function(i) {
    if (!!i)
        for (var e = 0; e < i.length / 2; e++)
            i[e * 2 + 1] = 1 - i[e * 2 + 1]
}
  , getAttribute = function(i) {
    if (i.semantic === "NORMAL")
        return "normal";
    if (i.semantic === "POSITION")
        return "position";
    if (i.semantic === "JOINT")
        return "matricesIndices";
    if (i.semantic === "WEIGHT")
        return "matricesWeights";
    if (i.semantic === "COLOR")
        return "color";
    if (i.semantic && i.semantic.indexOf("TEXCOORD_") !== -1) {
        var e = Number(i.semantic.split("_")[1]);
        return "uv" + (e === 0 ? "" : e + 1)
    }
    return null
}
  , loadAnimations = function(i) {
    for (var e in i.animations) {
        var t = i.animations[e];
        if (!(!t.channels || !t.samplers))
            for (var r = null, n = 0; n < t.channels.length; n++) {
                var o = t.channels[n]
                  , a = t.samplers[o.sampler];
                if (!!a) {
                    var s = null
                      , l = null;
                    t.parameters ? (s = t.parameters[a.input],
                    l = t.parameters[a.output]) : (s = a.input,
                    l = a.output);
                    var u = GLTFUtils.GetBufferFromAccessor(i, i.accessors[s])
                      , c = GLTFUtils.GetBufferFromAccessor(i, i.accessors[l])
                      , h = o.target.id
                      , f = i.scene.getNodeById(h);
                    if (f === null && (f = i.scene.getNodeByName(h)),
                    f === null) {
                        Tools.Warn("Creating animation named " + e + ". But cannot find node named " + h + " to attach to");
                        continue
                    }
                    var d = f instanceof Bone
                      , _ = o.target.path
                      , g = glTFAnimationPaths.indexOf(_);
                    g !== -1 && (_ = babylonAnimationPaths[g]);
                    var m = Animation.ANIMATIONTYPE_MATRIX;
                    d || (_ === "rotationQuaternion" ? (m = Animation.ANIMATIONTYPE_QUATERNION,
                    f.rotationQuaternion = new Quaternion) : m = Animation.ANIMATIONTYPE_VECTOR3);
                    var v = null
                      , y = []
                      , b = 0
                      , T = !1;
                    d && r && r.getKeys().length === u.length && (v = r,
                    T = !0),
                    T || (i.scene._blockEntityCollection = !!i.assetContainer,
                    v = new Animation(e,d ? "_matrix" : _,1,m,Animation.ANIMATIONLOOPMODE_CYCLE),
                    i.scene._blockEntityCollection = !1);
                    for (var C = 0; C < u.length; C++) {
                        var A = null;
                        if (_ === "rotationQuaternion" ? (A = Quaternion.FromArray([c[b], c[b + 1], c[b + 2], c[b + 3]]),
                        b += 4) : (A = Vector3.FromArray([c[b], c[b + 1], c[b + 2]]),
                        b += 3),
                        d) {
                            var S = f
                              , P = Vector3.Zero()
                              , R = new Quaternion
                              , M = Vector3.Zero()
                              , x = S.getBaseMatrix();
                            T && r && (x = r.getKeys()[C].value),
                            x.decompose(M, R, P),
                            _ === "position" ? P = A : _ === "rotationQuaternion" ? R = A : M = A,
                            A = Matrix.Compose(M, R, P)
                        }
                        T ? r && (r.getKeys()[C].value = A) : y.push({
                            frame: u[C],
                            value: A
                        })
                    }
                    !T && v && (v.setKeys(y),
                    f.animations.push(v)),
                    r = v,
                    i.scene.stopAnimation(f),
                    i.scene.beginAnimation(f, 0, u[u.length - 1], !0, 1)
                }
            }
    }
}
  , configureBoneTransformation = function(i) {
    var e = null;
    if (i.translation || i.rotation || i.scale) {
        var t = Vector3.FromArray(i.scale || [1, 1, 1])
          , r = Quaternion.FromArray(i.rotation || [0, 0, 0, 1])
          , n = Vector3.FromArray(i.translation || [0, 0, 0]);
        e = Matrix.Compose(t, r, n)
    } else
        e = Matrix.FromArray(i.matrix);
    return e
}
  , getParentBone = function(i, e, t, r) {
    for (var n = 0; n < r.bones.length; n++)
        if (r.bones[n].name === t)
            return r.bones[n];
    var o = i.nodes;
    for (var a in o) {
        var s = o[a];
        if (!!s.jointName)
            for (var l = s.children, n = 0; n < l.length; n++) {
                var u = i.nodes[l[n]];
                if (!!u.jointName && u.jointName === t) {
                    var c = configureBoneTransformation(s)
                      , h = new Bone(s.name || "",r,getParentBone(i, e, s.jointName, r),c);
                    return h.id = a,
                    h
                }
            }
    }
    return null
}
  , getNodeToRoot = function(i, e) {
    for (var t = 0; t < i.length; t++)
        for (var r = i[t], n = 0; n < r.node.children.length; n++) {
            var o = r.node.children[n];
            if (o === e)
                return r.bone
        }
    return null
}
  , getJointNode = function(i, e) {
    var t = i.nodes
      , r = t[e];
    if (r)
        return {
            node: r,
            id: e
        };
    for (var n in t)
        if (r = t[n],
        r.jointName === e)
            return {
                node: r,
                id: n
            };
    return null
}
  , nodeIsInJoints = function(i, e) {
    for (var t = 0; t < i.jointNames.length; t++)
        if (i.jointNames[t] === e)
            return !0;
    return !1
}
  , getNodesToRoot = function(i, e, t, r) {
    for (var n in i.nodes) {
        var o = i.nodes[n]
          , a = n;
        if (!(!o.jointName || nodeIsInJoints(t, o.jointName))) {
            var s = configureBoneTransformation(o)
              , l = new Bone(o.name || "",e,null,s);
            l.id = a,
            r.push({
                bone: l,
                node: o,
                id: a
            })
        }
    }
    for (var u = 0; u < r.length; u++)
        for (var c = r[u], h = c.node.children, f = 0; f < h.length; f++) {
            for (var d = null, _ = 0; _ < r.length; _++)
                if (r[_].id === h[f]) {
                    d = r[_];
                    break
                }
            d && (d.bone._parent = c.bone,
            c.bone.children.push(d.bone))
        }
}
  , importSkeleton = function(i, e, t, r, n) {
    if (r || (r = new Skeleton(e.name || "","",i.scene)),
    !e.babylonSkeleton)
        return r;
    var o = []
      , a = [];
    getNodesToRoot(i, r, e, o),
    r.bones = [];
    for (var s = 0; s < e.jointNames.length; s++) {
        var l = getJointNode(i, e.jointNames[s]);
        if (!!l) {
            var u = l.node;
            if (!u) {
                Tools.Warn("Joint named " + e.jointNames[s] + " does not exist");
                continue
            }
            var n = l.id
              , c = i.scene.getBoneById(n);
            if (c) {
                r.bones.push(c);
                continue
            }
            for (var h = !1, f = null, d = 0; d < s; d++) {
                var _ = getJointNode(i, e.jointNames[d]);
                if (!!_) {
                    var g = _.node;
                    if (!g) {
                        Tools.Warn("Joint named " + e.jointNames[d] + " does not exist when looking for parent");
                        continue
                    }
                    var m = g.children;
                    if (!!m) {
                        h = !1;
                        for (var v = 0; v < m.length; v++)
                            if (m[v] === n) {
                                f = getParentBone(i, e, e.jointNames[d], r),
                                h = !0;
                                break
                            }
                        if (h)
                            break
                    }
                }
            }
            var y = configureBoneTransformation(u);
            !f && o.length > 0 && (f = getNodeToRoot(o, n),
            f && a.indexOf(f) === -1 && a.push(f));
            var b = new Bone(u.jointName || "",r,f,y);
            b.id = n
        }
    }
    var T = r.bones;
    r.bones = [];
    for (var s = 0; s < e.jointNames.length; s++) {
        var l = getJointNode(i, e.jointNames[s]);
        if (!!l) {
            for (var d = 0; d < T.length; d++)
                if (T[d].id === l.id) {
                    r.bones.push(T[d]);
                    break
                }
        }
    }
    r.prepare();
    for (var s = 0; s < a.length; s++)
        r.bones.push(a[s]);
    return r
}
  , importMesh = function(i, e, t, r, n) {
    if (n || (i.scene._blockEntityCollection = !!i.assetContainer,
    n = new Mesh(e.name || "",i.scene),
    n._parentContainer = i.assetContainer,
    i.scene._blockEntityCollection = !1,
    n.id = r),
    !e.babylonNode)
        return n;
    for (var o = [], a = null, s = new Array, l = new Array, u = new Array, c = new Array, h = 0; h < t.length; h++) {
        var f = t[h]
          , d = i.meshes[f];
        if (!!d)
            for (var _ = 0; _ < d.primitives.length; _++) {
                var g = new VertexData
                  , m = d.primitives[_];
                m.mode;
                var v = m.attributes
                  , y = null
                  , b = null;
                for (var T in v)
                    if (y = i.accessors[v[T]],
                    b = GLTFUtils.GetBufferFromAccessor(i, y),
                    T === "NORMAL")
                        g.normals = new Float32Array(b.length),
                        g.normals.set(b);
                    else if (T === "POSITION") {
                        if (GLTFFileLoader.HomogeneousCoordinates) {
                            g.positions = new Float32Array(b.length - b.length / 4);
                            for (var C = 0; C < b.length; C += 4)
                                g.positions[C] = b[C],
                                g.positions[C + 1] = b[C + 1],
                                g.positions[C + 2] = b[C + 2]
                        } else
                            g.positions = new Float32Array(b.length),
                            g.positions.set(b);
                        l.push(g.positions.length)
                    } else if (T.indexOf("TEXCOORD_") !== -1) {
                        var A = Number(T.split("_")[1])
                          , S = VertexBuffer.UVKind + (A === 0 ? "" : A + 1)
                          , P = new Float32Array(b.length);
                        P.set(b),
                        normalizeUVs(P),
                        g.set(P, S)
                    } else
                        T === "JOINT" ? (g.matricesIndices = new Float32Array(b.length),
                        g.matricesIndices.set(b)) : T === "WEIGHT" ? (g.matricesWeights = new Float32Array(b.length),
                        g.matricesWeights.set(b)) : T === "COLOR" && (g.colors = new Float32Array(b.length),
                        g.colors.set(b));
                if (y = i.accessors[m.indices],
                y)
                    b = GLTFUtils.GetBufferFromAccessor(i, y),
                    g.indices = new Int32Array(b.length),
                    g.indices.set(b),
                    c.push(g.indices.length);
                else {
                    for (var R = [], C = 0; C < g.positions.length / 3; C++)
                        R.push(C);
                    g.indices = new Int32Array(R),
                    c.push(g.indices.length)
                }
                a ? a.merge(g) : a = g;
                var M = i.scene.getMaterialById(m.material);
                o.push(M === null ? GLTFUtils.GetDefaultMaterial(i.scene) : M),
                s.push(s.length === 0 ? 0 : s[s.length - 1] + l[l.length - 2]),
                u.push(u.length === 0 ? 0 : u[u.length - 1] + c[c.length - 2])
            }
    }
    var x;
    i.scene._blockEntityCollection = !!i.assetContainer,
    o.length > 1 ? (x = new MultiMaterial("multimat" + r,i.scene),
    x.subMaterials = o) : x = new StandardMaterial("multimat" + r,i.scene),
    o.length === 1 && (x = o[0]),
    x._parentContainer = i.assetContainer,
    n.material || (n.material = x),
    new Geometry(r,i.scene,a,!1,n),
    n.computeWorldMatrix(!0),
    i.scene._blockEntityCollection = !1,
    n.subMeshes = [];
    for (var I = 0, h = 0; h < t.length; h++) {
        var f = t[h]
          , d = i.meshes[f];
        if (!!d)
            for (var _ = 0; _ < d.primitives.length; _++)
                d.primitives[_].mode,
                SubMesh.AddToMesh(I, s[I], l[I], u[I], c[I], n, n, !0),
                I++
    }
    return n
}
  , configureNode = function(i, e, t, r) {
    i.position && (i.position = e),
    (i.rotationQuaternion || i.rotation) && (i.rotationQuaternion = t),
    i.scaling && (i.scaling = r)
}
  , configureNodeFromMatrix = function(i, e, t) {
    if (e.matrix) {
        var r = new Vector3(0,0,0)
          , n = new Quaternion
          , o = new Vector3(0,0,0)
          , a = Matrix.FromArray(e.matrix);
        a.decompose(o, n, r),
        configureNode(i, r, n, o)
    } else
        e.translation && e.rotation && e.scale && configureNode(i, Vector3.FromArray(e.translation), Quaternion.FromArray(e.rotation), Vector3.FromArray(e.scale));
    i.computeWorldMatrix(!0)
}
  , importNode$1 = function(i, e, t, r) {
    var n = null;
    if (i.importOnlyMeshes && (e.skin || e.meshes) && i.importMeshesNames && i.importMeshesNames.length > 0 && i.importMeshesNames.indexOf(e.name || "") === -1)
        return null;
    if (e.skin) {
        if (e.meshes) {
            var o = i.skins[e.skin]
              , a = importMesh(i, e, e.meshes, t, e.babylonNode);
            a.skeleton = i.scene.getLastSkeletonById(e.skin),
            a.skeleton === null && (a.skeleton = importSkeleton(i, o, a, o.babylonSkeleton, e.skin),
            o.babylonSkeleton || (o.babylonSkeleton = a.skeleton)),
            n = a
        }
    } else if (e.meshes) {
        var a = importMesh(i, e, e.mesh ? [e.mesh] : e.meshes, t, e.babylonNode);
        n = a
    } else if (e.light && !e.babylonNode && !i.importOnlyMeshes) {
        var s = i.lights[e.light];
        if (s) {
            if (s.type === "ambient") {
                var l = s[s.type]
                  , u = new HemisphericLight(e.light,Vector3.Zero(),i.scene);
                u.name = e.name || "",
                l.color && (u.diffuse = Color3.FromArray(l.color)),
                n = u
            } else if (s.type === "directional") {
                var c = s[s.type]
                  , h = new DirectionalLight(e.light,Vector3.Zero(),i.scene);
                h.name = e.name || "",
                c.color && (h.diffuse = Color3.FromArray(c.color)),
                n = h
            } else if (s.type === "point") {
                var f = s[s.type]
                  , d = new PointLight(e.light,Vector3.Zero(),i.scene);
                d.name = e.name || "",
                f.color && (d.diffuse = Color3.FromArray(f.color)),
                n = d
            } else if (s.type === "spot") {
                var _ = s[s.type]
                  , g = new SpotLight(e.light,Vector3.Zero(),Vector3.Zero(),0,0,i.scene);
                g.name = e.name || "",
                _.color && (g.diffuse = Color3.FromArray(_.color)),
                _.fallOfAngle && (g.angle = _.fallOfAngle),
                _.fallOffExponent && (g.exponent = _.fallOffExponent),
                n = g
            }
        }
    } else if (e.camera && !e.babylonNode && !i.importOnlyMeshes) {
        var m = i.cameras[e.camera];
        if (m) {
            if (i.scene._blockEntityCollection = !!i.assetContainer,
            m.type === "orthographic") {
                var v = new FreeCamera(e.camera,Vector3.Zero(),i.scene,!1);
                v.name = e.name || "",
                v.mode = Camera$1.ORTHOGRAPHIC_CAMERA,
                v.attachControl(),
                n = v,
                v._parentContainer = i.assetContainer
            } else if (m.type === "perspective") {
                var y = m[m.type]
                  , b = new FreeCamera(e.camera,Vector3.Zero(),i.scene,!1);
                b.name = e.name || "",
                b.attachControl(),
                y.aspectRatio || (y.aspectRatio = i.scene.getEngine().getRenderWidth() / i.scene.getEngine().getRenderHeight()),
                y.znear && y.zfar && (b.maxZ = y.zfar,
                b.minZ = y.znear),
                n = b,
                b._parentContainer = i.assetContainer
            }
            i.scene._blockEntityCollection = !1
        }
    }
    if (!e.jointName) {
        if (e.babylonNode)
            return e.babylonNode;
        if (n === null) {
            i.scene._blockEntityCollection = !!i.assetContainer;
            var T = new Mesh(e.name || "",i.scene);
            T._parentContainer = i.assetContainer,
            i.scene._blockEntityCollection = !1,
            e.babylonNode = T,
            n = T
        }
    }
    if (n !== null) {
        if (e.matrix && n instanceof Mesh)
            configureNodeFromMatrix(n, e);
        else {
            var C = e.translation || [0, 0, 0]
              , A = e.rotation || [0, 0, 0, 1]
              , S = e.scale || [1, 1, 1];
            configureNode(n, Vector3.FromArray(C), Quaternion.FromArray(A), Vector3.FromArray(S))
        }
        n.updateCache(!0),
        e.babylonNode = n
    }
    return n
}
  , traverseNodes = function(i, e, t, r) {
    r === void 0 && (r = !1);
    var n = i.nodes[e]
      , o = null;
    if (i.importOnlyMeshes && !r && i.importMeshesNames ? i.importMeshesNames.indexOf(n.name || "") !== -1 || i.importMeshesNames.length === 0 ? r = !0 : r = !1 : r = !0,
    !n.jointName && r && (o = importNode$1(i, n, e),
    o !== null && (o.id = e,
    o.parent = t)),
    n.children)
        for (var a = 0; a < n.children.length; a++)
            traverseNodes(i, n.children[a], o, r)
}
  , postLoad = function(i) {
    var e = i.currentScene;
    if (e)
        for (var t = 0; t < e.nodes.length; t++)
            traverseNodes(i, e.nodes[t], null);
    else
        for (var r in i.scenes) {
            e = i.scenes[r];
            for (var t = 0; t < e.nodes.length; t++)
                traverseNodes(i, e.nodes[t], null)
        }
    loadAnimations(i);
    for (var t = 0; t < i.scene.skeletons.length; t++) {
        var n = i.scene.skeletons[t];
        i.scene.beginAnimation(n, 0, Number.MAX_VALUE, !0, 1)
    }
}
  , onBindShaderMaterial = function(i, e, t, r, n, o, a) {
    var s = o.values || n.parameters;
    for (var l in t) {
        var u = t[l]
          , c = u.type;
        if (c === EParameterType.FLOAT_MAT2 || c === EParameterType.FLOAT_MAT3 || c === EParameterType.FLOAT_MAT4) {
            if (u.semantic && !u.source && !u.node)
                GLTFUtils.SetMatrix(e.scene, i, u, l, r.getEffect());
            else if (u.semantic && (u.source || u.node)) {
                var h = e.scene.getNodeByName(u.source || u.node || "");
                if (h === null && (h = e.scene.getNodeById(u.source || u.node || "")),
                h === null)
                    continue;
                GLTFUtils.SetMatrix(e.scene, h, u, l, r.getEffect())
            }
        } else {
            var f = s[n.uniforms[l]];
            if (!f)
                continue;
            if (c === EParameterType.SAMPLER_2D) {
                var d = e.textures[o.values ? f : u.value].babylonTexture;
                if (d == null)
                    continue;
                r.getEffect().setTexture(l, d)
            } else
                GLTFUtils.SetUniform(r.getEffect(), l, f, c)
        }
    }
    a(r)
}
  , prepareShaderMaterialUniforms = function(i, e, t, r, n) {
    var o = r.values || t.parameters
      , a = t.uniforms;
    for (var s in n) {
        var l = n[s]
          , u = l.type
          , c = o[a[s]];
        if (c === void 0 && (c = l.value),
        !!c) {
            var h = function(f) {
                return function(d) {
                    l.value && f && (e.setTexture(f, d),
                    delete n[f])
                }
            };
            u === EParameterType.SAMPLER_2D ? GLTFLoaderExtension.LoadTextureAsync(i, r.values ? c : l.value, h(s), function() {
                return h(null)
            }) : l.value && GLTFUtils.SetUniform(e, s, r.values ? c : l.value, u) && delete n[s]
        }
    }
}
  , onShaderCompileError = function(i, e, t) {
    return function(r, n) {
        e.dispose(!0),
        t("Cannot compile program named " + i.name + ". Error: " + n + ". Default material will be applied")
    }
}
  , onShaderCompileSuccess = function(i, e, t, r, n, o) {
    return function(a) {
        prepareShaderMaterialUniforms(i, e, t, r, n),
        e.onBind = function(s) {
            onBindShaderMaterial(s, i, n, e, t, r, o)
        }
    }
}
  , parseShaderUniforms = function(i, e, t) {
    for (var r in e.uniforms) {
        var n = e.uniforms[r]
          , o = e.parameters[n];
        if (i.currentIdentifier === r && o.semantic && !o.source && !o.node) {
            var a = glTFTransforms.indexOf(o.semantic);
            if (a !== -1)
                return delete t[r],
                babylonTransforms[a]
        }
    }
    return i.currentIdentifier
}
  , importMaterials = function(i) {
    for (var e in i.materials)
        GLTFLoaderExtension.LoadMaterialAsync(i, e, function(t) {}, function() {})
}
  , GLTFLoaderBase = function() {
    function i() {}
    return i.CreateRuntime = function(e, t, r) {
        var n = {
            extensions: {},
            accessors: {},
            buffers: {},
            bufferViews: {},
            meshes: {},
            lights: {},
            cameras: {},
            nodes: {},
            images: {},
            textures: {},
            shaders: {},
            programs: {},
            samplers: {},
            techniques: {},
            materials: {},
            animations: {},
            skins: {},
            extensionsUsed: [],
            scenes: {},
            buffersCount: 0,
            shaderscount: 0,
            scene: t,
            rootUrl: r,
            loadedBufferCount: 0,
            loadedBufferViews: {},
            loadedShaderCount: 0,
            importOnlyMeshes: !1,
            dummyNodes: [],
            assetContainer: null
        };
        return e.extensions && parseObject(e.extensions, "extensions", n),
        e.extensionsUsed && parseObject(e.extensionsUsed, "extensionsUsed", n),
        e.buffers && parseBuffers(e.buffers, n),
        e.bufferViews && parseObject(e.bufferViews, "bufferViews", n),
        e.accessors && parseObject(e.accessors, "accessors", n),
        e.meshes && parseObject(e.meshes, "meshes", n),
        e.lights && parseObject(e.lights, "lights", n),
        e.cameras && parseObject(e.cameras, "cameras", n),
        e.nodes && parseObject(e.nodes, "nodes", n),
        e.images && parseObject(e.images, "images", n),
        e.textures && parseObject(e.textures, "textures", n),
        e.shaders && parseShaders(e.shaders, n),
        e.programs && parseObject(e.programs, "programs", n),
        e.samplers && parseObject(e.samplers, "samplers", n),
        e.techniques && parseObject(e.techniques, "techniques", n),
        e.materials && parseObject(e.materials, "materials", n),
        e.animations && parseObject(e.animations, "animations", n),
        e.skins && parseObject(e.skins, "skins", n),
        e.scenes && (n.scenes = e.scenes),
        e.scene && e.scenes && (n.currentScene = e.scenes[e.scene]),
        n
    }
    ,
    i.LoadBufferAsync = function(e, t, r, n, o) {
        var a = e.buffers[t];
        Tools.IsBase64(a.uri) ? setTimeout(function() {
            return r(new Uint8Array(Tools.DecodeBase64(a.uri)))
        }) : Tools.LoadFile(e.rootUrl + a.uri, function(s) {
            return r(new Uint8Array(s))
        }, o, void 0, !0, function(s) {
            s && n(s.status + " " + s.statusText)
        })
    }
    ,
    i.LoadTextureBufferAsync = function(e, t, r, n) {
        var o = e.textures[t];
        if (!o || !o.source) {
            n("");
            return
        }
        if (o.babylonTexture) {
            r(null);
            return
        }
        var a = e.images[o.source];
        Tools.IsBase64(a.uri) ? setTimeout(function() {
            return r(new Uint8Array(Tools.DecodeBase64(a.uri)))
        }) : Tools.LoadFile(e.rootUrl + a.uri, function(s) {
            return r(new Uint8Array(s))
        }, void 0, void 0, !0, function(s) {
            s && n(s.status + " " + s.statusText)
        })
    }
    ,
    i.CreateTextureAsync = function(e, t, r, n, o) {
        var a = e.textures[t];
        if (a.babylonTexture) {
            n(a.babylonTexture);
            return
        }
        var s = e.samplers[a.sampler]
          , l = s.minFilter === ETextureFilterType.NEAREST_MIPMAP_NEAREST || s.minFilter === ETextureFilterType.NEAREST_MIPMAP_LINEAR || s.minFilter === ETextureFilterType.LINEAR_MIPMAP_NEAREST || s.minFilter === ETextureFilterType.LINEAR_MIPMAP_LINEAR
          , u = Texture.BILINEAR_SAMPLINGMODE
          , c = r == null ? new Blob : new Blob([r])
          , h = URL.createObjectURL(c)
          , f = function() {
            return URL.revokeObjectURL(h)
        }
          , d = new Texture(h,e.scene,!l,!0,u,f,f);
        s.wrapS !== void 0 && (d.wrapU = GLTFUtils.GetWrapMode(s.wrapS)),
        s.wrapT !== void 0 && (d.wrapV = GLTFUtils.GetWrapMode(s.wrapT)),
        d.name = t,
        a.babylonTexture = d,
        n(d)
    }
    ,
    i.LoadShaderStringAsync = function(e, t, r, n) {
        var o = e.shaders[t];
        if (Tools.IsBase64(o.uri)) {
            var a = atob(o.uri.split(",")[1]);
            r && r(a)
        } else
            Tools.LoadFile(e.rootUrl + o.uri, r, void 0, void 0, !1, function(s) {
                s && n && n(s.status + " " + s.statusText)
            })
    }
    ,
    i.LoadMaterialAsync = function(e, t, r, n) {
        var o = e.materials[t];
        if (!o.technique) {
            n && n("No technique found.");
            return
        }
        var a = e.techniques[o.technique];
        if (!a) {
            e.scene._blockEntityCollection = !!e.assetContainer;
            var s = new StandardMaterial(t,e.scene);
            s._parentContainer = e.assetContainer,
            e.scene._blockEntityCollection = !1,
            s.diffuseColor = new Color3(.5,.5,.5),
            s.sideOrientation = Material.CounterClockWiseSideOrientation,
            r(s);
            return
        }
        var l = e.programs[a.program]
          , u = a.states
          , c = Effect.ShadersStore[l.vertexShader + "VertexShader"]
          , h = Effect.ShadersStore[l.fragmentShader + "PixelShader"]
          , f = ""
          , d = ""
          , _ = new Tokenizer(c)
          , g = new Tokenizer(h)
          , m = {}
          , v = []
          , y = []
          , b = [];
        for (var T in a.uniforms) {
            var C = a.uniforms[T]
              , A = a.parameters[C];
            if (m[T] = A,
            A.semantic && !A.node && !A.source) {
                var S = glTFTransforms.indexOf(A.semantic);
                S !== -1 ? (v.push(babylonTransforms[S]),
                delete m[T]) : v.push(T)
            } else
                A.type === EParameterType.SAMPLER_2D ? b.push(T) : v.push(T)
        }
        for (var P in a.attributes) {
            var R = a.attributes[P]
              , M = a.parameters[R];
            if (M.semantic) {
                var x = getAttribute(M);
                x && y.push(x)
            }
        }
        for (; !_.isEnd() && _.getNextToken(); ) {
            var I = _.currentToken;
            if (I !== ETokenType.IDENTIFIER) {
                f += _.currentString;
                continue
            }
            var w = !1;
            for (var P in a.attributes) {
                var R = a.attributes[P]
                  , M = a.parameters[R];
                if (_.currentIdentifier === P && M.semantic) {
                    f += getAttribute(M),
                    w = !0;
                    break
                }
            }
            w || (f += parseShaderUniforms(_, a, m))
        }
        for (; !g.isEnd() && g.getNextToken(); ) {
            var I = g.currentToken;
            if (I !== ETokenType.IDENTIFIER) {
                d += g.currentString;
                continue
            }
            d += parseShaderUniforms(g, a, m)
        }
        var O = {
            vertex: l.vertexShader + t,
            fragment: l.fragmentShader + t
        }
          , D = {
            attributes: y,
            uniforms: v,
            samplers: b,
            needAlphaBlending: u && u.enable && u.enable.indexOf(3042) !== -1
        };
        Effect.ShadersStore[l.vertexShader + t + "VertexShader"] = f,
        Effect.ShadersStore[l.fragmentShader + t + "PixelShader"] = d;
        var F = new ShaderMaterial(t,e.scene,O,D);
        if (F.onError = onShaderCompileError(l, F, n),
        F.onCompiled = onShaderCompileSuccess(e, F, a, o, m, r),
        F.sideOrientation = Material.CounterClockWiseSideOrientation,
        u && u.functions) {
            var V = u.functions;
            V.cullFace && V.cullFace[0] !== ECullingType.BACK && (F.backFaceCulling = !1);
            var N = V.blendFuncSeparate;
            N && (N[0] === EBlendingFunction.SRC_ALPHA && N[1] === EBlendingFunction.ONE_MINUS_SRC_ALPHA && N[2] === EBlendingFunction.ONE && N[3] === EBlendingFunction.ONE ? F.alphaMode = Constants.ALPHA_COMBINE : N[0] === EBlendingFunction.ONE && N[1] === EBlendingFunction.ONE && N[2] === EBlendingFunction.ZERO && N[3] === EBlendingFunction.ONE ? F.alphaMode = Constants.ALPHA_ONEONE : N[0] === EBlendingFunction.SRC_ALPHA && N[1] === EBlendingFunction.ONE && N[2] === EBlendingFunction.ZERO && N[3] === EBlendingFunction.ONE ? F.alphaMode = Constants.ALPHA_ADD : N[0] === EBlendingFunction.ZERO && N[1] === EBlendingFunction.ONE_MINUS_SRC_COLOR && N[2] === EBlendingFunction.ONE && N[3] === EBlendingFunction.ONE ? F.alphaMode = Constants.ALPHA_SUBTRACT : N[0] === EBlendingFunction.DST_COLOR && N[1] === EBlendingFunction.ZERO && N[2] === EBlendingFunction.ONE && N[3] === EBlendingFunction.ONE ? F.alphaMode = Constants.ALPHA_MULTIPLY : N[0] === EBlendingFunction.SRC_ALPHA && N[1] === EBlendingFunction.ONE_MINUS_SRC_COLOR && N[2] === EBlendingFunction.ONE && N[3] === EBlendingFunction.ONE && (F.alphaMode = Constants.ALPHA_MAXIMIZED))
        }
    }
    ,
    i
}()
  , GLTFLoader$1 = function() {
    function i() {}
    return i.RegisterExtension = function(e) {
        if (i.Extensions[e.name]) {
            Tools.Error('Tool with the same name "' + e.name + '" already exists');
            return
        }
        i.Extensions[e.name] = e
    }
    ,
    i.prototype.dispose = function() {}
    ,
    i.prototype._importMeshAsync = function(e, t, r, n, o, a, s, l) {
        var u = this;
        return t.useRightHandedSystem = !0,
        GLTFLoaderExtension.LoadRuntimeAsync(t, r, n, function(c) {
            c.assetContainer = o,
            c.importOnlyMeshes = !0,
            e === "" ? c.importMeshesNames = [] : typeof e == "string" ? c.importMeshesNames = [e] : e && !(e instanceof Array) ? c.importMeshesNames = [e] : (c.importMeshesNames = [],
            Tools.Warn("Argument meshesNames must be of type string or string[]")),
            u._createNodes(c);
            var h = new Array
              , f = new Array;
            for (var d in c.nodes) {
                var _ = c.nodes[d];
                _.babylonNode instanceof AbstractMesh && h.push(_.babylonNode)
            }
            for (var g in c.skins) {
                var m = c.skins[g];
                m.babylonSkeleton instanceof Skeleton && f.push(m.babylonSkeleton)
            }
            u._loadBuffersAsync(c, function() {
                u._loadShadersAsync(c, function() {
                    importMaterials(c),
                    postLoad(c),
                    !GLTFFileLoader.IncrementalLoading && a && a(h, f)
                })
            }, s),
            GLTFFileLoader.IncrementalLoading && a && a(h, f)
        }, l),
        !0
    }
    ,
    i.prototype.importMeshAsync = function(e, t, r, n, o, a) {
        var s = this;
        return new Promise(function(l, u) {
            s._importMeshAsync(e, t, n, o, r, function(c, h) {
                l({
                    meshes: c,
                    particleSystems: [],
                    skeletons: h,
                    animationGroups: [],
                    lights: [],
                    transformNodes: [],
                    geometries: []
                })
            }, a, function(c) {
                u(new Error(c))
            })
        }
        )
    }
    ,
    i.prototype._loadAsync = function(e, t, r, n, o, a) {
        var s = this;
        e.useRightHandedSystem = !0,
        GLTFLoaderExtension.LoadRuntimeAsync(e, t, r, function(l) {
            GLTFLoaderExtension.LoadRuntimeExtensionsAsync(l, function() {
                s._createNodes(l),
                s._loadBuffersAsync(l, function() {
                    s._loadShadersAsync(l, function() {
                        importMaterials(l),
                        postLoad(l),
                        GLTFFileLoader.IncrementalLoading || n()
                    })
                }),
                GLTFFileLoader.IncrementalLoading && n()
            }, a)
        }, a)
    }
    ,
    i.prototype.loadAsync = function(e, t, r, n) {
        var o = this;
        return new Promise(function(a, s) {
            o._loadAsync(e, t, r, function() {
                a()
            }, n, function(l) {
                s(new Error(l))
            })
        }
        )
    }
    ,
    i.prototype._loadShadersAsync = function(e, t) {
        var r = !1
          , n = function(s, l) {
            GLTFLoaderExtension.LoadShaderStringAsync(e, s, function(u) {
                u instanceof ArrayBuffer || (e.loadedShaderCount++,
                u && (Effect.ShadersStore[s + (l.type === EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = u),
                e.loadedShaderCount === e.shaderscount && t())
            }, function() {
                Tools.Error("Error when loading shader program named " + s + " located at " + l.uri)
            })
        };
        for (var o in e.shaders) {
            r = !0;
            var a = e.shaders[o];
            a ? n.bind(this, o, a)() : Tools.Error("No shader named: " + o)
        }
        r || t()
    }
    ,
    i.prototype._loadBuffersAsync = function(e, t, r) {
        var n = !1
          , o = function(l, u) {
            GLTFLoaderExtension.LoadBufferAsync(e, l, function(c) {
                e.loadedBufferCount++,
                c && (c.byteLength != e.buffers[l].byteLength && Tools.Error("Buffer named " + l + " is length " + c.byteLength + ". Expected: " + u.byteLength),
                e.loadedBufferViews[l] = c),
                e.loadedBufferCount === e.buffersCount && t()
            }, function() {
                Tools.Error("Error when loading buffer named " + l + " located at " + u.uri)
            })
        };
        for (var a in e.buffers) {
            n = !0;
            var s = e.buffers[a];
            s ? o.bind(this, a, s)() : Tools.Error("No buffer named: " + a)
        }
        n || t()
    }
    ,
    i.prototype._createNodes = function(e) {
        var t = e.currentScene;
        if (t)
            for (var r = 0; r < t.nodes.length; r++)
                traverseNodes(e, t.nodes[r], null);
        else
            for (var n in e.scenes) {
                t = e.scenes[n];
                for (var r = 0; r < t.nodes.length; r++)
                    traverseNodes(e, t.nodes[r], null)
            }
    }
    ,
    i.Extensions = {},
    i
}()
  , GLTFLoaderExtension = function() {
    function i(e) {
        this._name = e
    }
    return Object.defineProperty(i.prototype, "name", {
        get: function() {
            return this._name
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.loadRuntimeAsync = function(e, t, r, n, o) {
        return !1
    }
    ,
    i.prototype.loadRuntimeExtensionsAsync = function(e, t, r) {
        return !1
    }
    ,
    i.prototype.loadBufferAsync = function(e, t, r, n, o) {
        return !1
    }
    ,
    i.prototype.loadTextureBufferAsync = function(e, t, r, n) {
        return !1
    }
    ,
    i.prototype.createTextureAsync = function(e, t, r, n, o) {
        return !1
    }
    ,
    i.prototype.loadShaderStringAsync = function(e, t, r, n) {
        return !1
    }
    ,
    i.prototype.loadMaterialAsync = function(e, t, r, n) {
        return !1
    }
    ,
    i.LoadRuntimeAsync = function(e, t, r, n, o) {
        i.ApplyExtensions(function(a) {
            return a.loadRuntimeAsync(e, t, r, n, o)
        }, function() {
            setTimeout(function() {
                !n || n(GLTFLoaderBase.CreateRuntime(t.json, e, r))
            })
        })
    }
    ,
    i.LoadRuntimeExtensionsAsync = function(e, t, r) {
        i.ApplyExtensions(function(n) {
            return n.loadRuntimeExtensionsAsync(e, t, r)
        }, function() {
            setTimeout(function() {
                t()
            })
        })
    }
    ,
    i.LoadBufferAsync = function(e, t, r, n, o) {
        i.ApplyExtensions(function(a) {
            return a.loadBufferAsync(e, t, r, n, o)
        }, function() {
            GLTFLoaderBase.LoadBufferAsync(e, t, r, n, o)
        })
    }
    ,
    i.LoadTextureAsync = function(e, t, r, n) {
        i.LoadTextureBufferAsync(e, t, function(o) {
            o && i.CreateTextureAsync(e, t, o, r, n)
        }, n)
    }
    ,
    i.LoadShaderStringAsync = function(e, t, r, n) {
        i.ApplyExtensions(function(o) {
            return o.loadShaderStringAsync(e, t, r, n)
        }, function() {
            GLTFLoaderBase.LoadShaderStringAsync(e, t, r, n)
        })
    }
    ,
    i.LoadMaterialAsync = function(e, t, r, n) {
        i.ApplyExtensions(function(o) {
            return o.loadMaterialAsync(e, t, r, n)
        }, function() {
            GLTFLoaderBase.LoadMaterialAsync(e, t, r, n)
        })
    }
    ,
    i.LoadTextureBufferAsync = function(e, t, r, n) {
        i.ApplyExtensions(function(o) {
            return o.loadTextureBufferAsync(e, t, r, n)
        }, function() {
            GLTFLoaderBase.LoadTextureBufferAsync(e, t, r, n)
        })
    }
    ,
    i.CreateTextureAsync = function(e, t, r, n, o) {
        i.ApplyExtensions(function(a) {
            return a.createTextureAsync(e, t, r, n, o)
        }, function() {
            GLTFLoaderBase.CreateTextureAsync(e, t, r, n, o)
        })
    }
    ,
    i.ApplyExtensions = function(e, t) {
        for (var r in GLTFLoader$1.Extensions) {
            var n = GLTFLoader$1.Extensions[r];
            if (e(n))
                return
        }
        t()
    }
    ,
    i
}();
GLTFFileLoader._CreateGLTF1Loader = function() {
    return new GLTFLoader$1
}
;
var BinaryExtensionBufferName = "binary_glTF"
  , GLTFBinaryExtension = function(i) {
    __extends(e, i);
    function e() {
        return i.call(this, "KHR_binary_glTF") || this
    }
    return e.prototype.loadRuntimeAsync = function(t, r, n, o, a) {
        var s = r.json.extensionsUsed;
        return !s || s.indexOf(this.name) === -1 || !r.bin ? !1 : (this._bin = r.bin,
        o(GLTFLoaderBase.CreateRuntime(r.json, t, n)),
        !0)
    }
    ,
    e.prototype.loadBufferAsync = function(t, r, n, o) {
        return t.extensionsUsed.indexOf(this.name) === -1 || r !== BinaryExtensionBufferName ? !1 : (this._bin.readAsync(0, this._bin.byteLength).then(n, function(a) {
            return o(a.message)
        }),
        !0)
    }
    ,
    e.prototype.loadTextureBufferAsync = function(t, r, n, o) {
        var a = t.textures[r]
          , s = t.images[a.source];
        if (!s.extensions || !(this.name in s.extensions))
            return !1;
        var l = s.extensions[this.name]
          , u = t.bufferViews[l.bufferView]
          , c = GLTFUtils.GetBufferFromBufferView(t, u, 0, u.byteLength, EComponentType.UNSIGNED_BYTE);
        return n(c),
        !0
    }
    ,
    e.prototype.loadShaderStringAsync = function(t, r, n, o) {
        var a = t.shaders[r];
        if (!a.extensions || !(this.name in a.extensions))
            return !1;
        var s = a.extensions[this.name]
          , l = t.bufferViews[s.bufferView]
          , u = GLTFUtils.GetBufferFromBufferView(t, l, 0, l.byteLength, EComponentType.UNSIGNED_BYTE);
        return setTimeout(function() {
            var c = GLTFUtils.DecodeBufferToText(u);
            n(c)
        }),
        !0
    }
    ,
    e
}(GLTFLoaderExtension);
GLTFLoader$1.RegisterExtension(new GLTFBinaryExtension);
var GLTFMaterialsCommonExtension = function(i) {
    __extends(e, i);
    function e() {
        return i.call(this, "KHR_materials_common") || this
    }
    return e.prototype.loadRuntimeExtensionsAsync = function(t, r, n) {
        if (!t.extensions)
            return !1;
        var o = t.extensions[this.name];
        if (!o)
            return !1;
        var a = o.lights;
        if (a)
            for (var s in a) {
                var l = a[s];
                switch (l.type) {
                case "ambient":
                    var u = new HemisphericLight(l.name,new Vector3(0,1,0),t.scene)
                      , c = l.ambient;
                    c && (u.diffuse = Color3.FromArray(c.color || [1, 1, 1]));
                    break;
                case "point":
                    var h = new PointLight(l.name,new Vector3(10,10,10),t.scene)
                      , f = l.point;
                    f && (h.diffuse = Color3.FromArray(f.color || [1, 1, 1]));
                    break;
                case "directional":
                    var d = new DirectionalLight(l.name,new Vector3(0,-1,0),t.scene)
                      , _ = l.directional;
                    _ && (d.diffuse = Color3.FromArray(_.color || [1, 1, 1]));
                    break;
                case "spot":
                    var g = l.spot;
                    if (g) {
                        var m = new SpotLight(l.name,new Vector3(0,10,0),new Vector3(0,-1,0),g.fallOffAngle || Math.PI,g.fallOffExponent || 0,t.scene);
                        m.diffuse = Color3.FromArray(g.color || [1, 1, 1])
                    }
                    break;
                default:
                    Tools.Warn('GLTF Material Common extension: light type "' + l.type + "\u201D not supported");
                    break
                }
            }
        return !1
    }
    ,
    e.prototype.loadMaterialAsync = function(t, r, n, o) {
        var a = t.materials[r];
        if (!a || !a.extensions)
            return !1;
        var s = a.extensions[this.name];
        if (!s)
            return !1;
        var l = new StandardMaterial(r,t.scene);
        return l.sideOrientation = Material.CounterClockWiseSideOrientation,
        s.technique === "CONSTANT" && (l.disableLighting = !0),
        l.backFaceCulling = s.doubleSided === void 0 ? !1 : !s.doubleSided,
        l.alpha = s.values.transparency === void 0 ? 1 : s.values.transparency,
        l.specularPower = s.values.shininess === void 0 ? 0 : s.values.shininess,
        typeof s.values.ambient == "string" ? this._loadTexture(t, s.values.ambient, l, "ambientTexture", o) : l.ambientColor = Color3.FromArray(s.values.ambient || [0, 0, 0]),
        typeof s.values.diffuse == "string" ? this._loadTexture(t, s.values.diffuse, l, "diffuseTexture", o) : l.diffuseColor = Color3.FromArray(s.values.diffuse || [0, 0, 0]),
        typeof s.values.emission == "string" ? this._loadTexture(t, s.values.emission, l, "emissiveTexture", o) : l.emissiveColor = Color3.FromArray(s.values.emission || [0, 0, 0]),
        typeof s.values.specular == "string" ? this._loadTexture(t, s.values.specular, l, "specularTexture", o) : l.specularColor = Color3.FromArray(s.values.specular || [0, 0, 0]),
        !0
    }
    ,
    e.prototype._loadTexture = function(t, r, n, o, a) {
        GLTFLoaderBase.LoadTextureBufferAsync(t, r, function(s) {
            GLTFLoaderBase.CreateTextureAsync(t, r, s, function(l) {
                return n[o] = l
            }, a)
        }, a)
    }
    ,
    e
}(GLTFLoaderExtension);
GLTFLoader$1.RegisterExtension(new GLTFMaterialsCommonExtension);
var Deferred = function() {
    function i() {
        var e = this;
        this.promise = new Promise(function(t, r) {
            e._resolve = t,
            e._reject = r
        }
        )
    }
    return Object.defineProperty(i.prototype, "resolve", {
        get: function() {
            return this._resolve
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "reject", {
        get: function() {
            return this._reject
        },
        enumerable: !1,
        configurable: !0
    }),
    i
}()
  , PBRMaterial = function(i) {
    __extends(e, i);
    function e(t, r) {
        var n = i.call(this, t, r) || this;
        return n.directIntensity = 1,
        n.emissiveIntensity = 1,
        n.environmentIntensity = 1,
        n.specularIntensity = 1,
        n.disableBumpMap = !1,
        n.ambientTextureStrength = 1,
        n.ambientTextureImpactOnAnalyticalLights = e.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,
        n.metallicF0Factor = 1,
        n.metallicReflectanceColor = Color3.White(),
        n.useOnlyMetallicFromMetallicReflectanceTexture = !1,
        n.ambientColor = new Color3(0,0,0),
        n.albedoColor = new Color3(1,1,1),
        n.reflectivityColor = new Color3(1,1,1),
        n.reflectionColor = new Color3(1,1,1),
        n.emissiveColor = new Color3(0,0,0),
        n.microSurface = 1,
        n.useLightmapAsShadowmap = !1,
        n.useAlphaFromAlbedoTexture = !1,
        n.forceAlphaTest = !1,
        n.alphaCutOff = .4,
        n.useSpecularOverAlpha = !0,
        n.useMicroSurfaceFromReflectivityMapAlpha = !1,
        n.useRoughnessFromMetallicTextureAlpha = !0,
        n.useRoughnessFromMetallicTextureGreen = !1,
        n.useMetallnessFromMetallicTextureBlue = !1,
        n.useAmbientOcclusionFromMetallicTextureRed = !1,
        n.useAmbientInGrayScale = !1,
        n.useAutoMicroSurfaceFromReflectivityMap = !1,
        n.useRadianceOverAlpha = !0,
        n.useObjectSpaceNormalMap = !1,
        n.useParallax = !1,
        n.useParallaxOcclusion = !1,
        n.parallaxScaleBias = .05,
        n.disableLighting = !1,
        n.forceIrradianceInFragment = !1,
        n.maxSimultaneousLights = 4,
        n.invertNormalMapX = !1,
        n.invertNormalMapY = !1,
        n.twoSidedLighting = !1,
        n.useAlphaFresnel = !1,
        n.useLinearAlphaFresnel = !1,
        n.environmentBRDFTexture = null,
        n.forceNormalForward = !1,
        n.enableSpecularAntiAliasing = !1,
        n.useHorizonOcclusion = !0,
        n.useRadianceOcclusion = !0,
        n.unlit = !1,
        n._environmentBRDFTexture = GetEnvironmentBRDFTexture(r),
        n
    }
    return Object.defineProperty(e.prototype, "refractionTexture", {
        get: function() {
            return this.subSurface.refractionTexture
        },
        set: function(t) {
            this.subSurface.refractionTexture = t,
            t ? this.subSurface.isRefractionEnabled = !0 : this.subSurface.linkRefractionWithTransparency || (this.subSurface.isRefractionEnabled = !1)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "indexOfRefraction", {
        get: function() {
            return this.subSurface.indexOfRefraction
        },
        set: function(t) {
            this.subSurface.indexOfRefraction = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "invertRefractionY", {
        get: function() {
            return this.subSurface.invertRefractionY
        },
        set: function(t) {
            this.subSurface.invertRefractionY = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "linkRefractionWithTransparency", {
        get: function() {
            return this.subSurface.linkRefractionWithTransparency
        },
        set: function(t) {
            this.subSurface.linkRefractionWithTransparency = t,
            t && (this.subSurface.isRefractionEnabled = !0)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "usePhysicalLightFalloff", {
        get: function() {
            return this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL
        },
        set: function(t) {
            t !== this.usePhysicalLightFalloff && (this._markAllSubMeshesAsTexturesDirty(),
            t ? this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL : this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_STANDARD)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "useGLTFLightFalloff", {
        get: function() {
            return this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF
        },
        set: function(t) {
            t !== this.useGLTFLightFalloff && (this._markAllSubMeshesAsTexturesDirty(),
            t ? this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_GLTF : this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_STANDARD)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "imageProcessingConfiguration", {
        get: function() {
            return this._imageProcessingConfiguration
        },
        set: function(t) {
            this._attachImageProcessingConfiguration(t),
            this._markAllSubMeshesAsTexturesDirty()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cameraColorCurvesEnabled", {
        get: function() {
            return this.imageProcessingConfiguration.colorCurvesEnabled
        },
        set: function(t) {
            this.imageProcessingConfiguration.colorCurvesEnabled = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cameraColorGradingEnabled", {
        get: function() {
            return this.imageProcessingConfiguration.colorGradingEnabled
        },
        set: function(t) {
            this.imageProcessingConfiguration.colorGradingEnabled = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cameraToneMappingEnabled", {
        get: function() {
            return this._imageProcessingConfiguration.toneMappingEnabled
        },
        set: function(t) {
            this._imageProcessingConfiguration.toneMappingEnabled = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cameraExposure", {
        get: function() {
            return this._imageProcessingConfiguration.exposure
        },
        set: function(t) {
            this._imageProcessingConfiguration.exposure = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cameraContrast", {
        get: function() {
            return this._imageProcessingConfiguration.contrast
        },
        set: function(t) {
            this._imageProcessingConfiguration.contrast = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cameraColorGradingTexture", {
        get: function() {
            return this._imageProcessingConfiguration.colorGradingTexture
        },
        set: function(t) {
            this._imageProcessingConfiguration.colorGradingTexture = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cameraColorCurves", {
        get: function() {
            return this._imageProcessingConfiguration.colorCurves
        },
        set: function(t) {
            this._imageProcessingConfiguration.colorCurves = t
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getClassName = function() {
        return "PBRMaterial"
    }
    ,
    e.prototype.clone = function(t) {
        var r = this
          , n = SerializationHelper.Clone(function() {
            return new e(t,r.getScene())
        }, this);
        return n.id = t,
        n.name = t,
        this.stencil.copyTo(n.stencil),
        this.clearCoat.copyTo(n.clearCoat),
        this.anisotropy.copyTo(n.anisotropy),
        this.brdf.copyTo(n.brdf),
        this.sheen.copyTo(n.sheen),
        this.subSurface.copyTo(n.subSurface),
        n
    }
    ,
    e.prototype.serialize = function() {
        var t = SerializationHelper.Serialize(this);
        return t.customType = "BABYLON.PBRMaterial",
        t.stencil = this.stencil.serialize(),
        t.clearCoat = this.clearCoat.serialize(),
        t.anisotropy = this.anisotropy.serialize(),
        t.brdf = this.brdf.serialize(),
        t.sheen = this.sheen.serialize(),
        t.subSurface = this.subSurface.serialize(),
        t
    }
    ,
    e.Parse = function(t, r, n) {
        var o = SerializationHelper.Parse(function() {
            return new e(t.name,r)
        }, t, r, n);
        return t.stencil && o.stencil.parse(t.stencil, r, n),
        t.clearCoat && o.clearCoat.parse(t.clearCoat, r, n),
        t.anisotropy && o.anisotropy.parse(t.anisotropy, r, n),
        t.brdf && o.brdf.parse(t.brdf, r, n),
        t.sheen && o.sheen.parse(t.sheen, r, n),
        t.subSurface && o.subSurface.parse(t.subSurface, r, n),
        o
    }
    ,
    e.PBRMATERIAL_OPAQUE = PBRBaseMaterial.PBRMATERIAL_OPAQUE,
    e.PBRMATERIAL_ALPHATEST = PBRBaseMaterial.PBRMATERIAL_ALPHATEST,
    e.PBRMATERIAL_ALPHABLEND = PBRBaseMaterial.PBRMATERIAL_ALPHABLEND,
    e.PBRMATERIAL_ALPHATESTANDBLEND = PBRBaseMaterial.PBRMATERIAL_ALPHATESTANDBLEND,
    e.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = PBRBaseMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "directIntensity", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "emissiveIntensity", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "environmentIntensity", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "specularIntensity", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "disableBumpMap", void 0),
    __decorate([serializeAsTexture(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "albedoTexture", void 0),
    __decorate([serializeAsTexture(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "ambientTexture", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "ambientTextureStrength", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "ambientTextureImpactOnAnalyticalLights", void 0),
    __decorate([serializeAsTexture(), expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")], e.prototype, "opacityTexture", void 0),
    __decorate([serializeAsTexture(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "reflectionTexture", void 0),
    __decorate([serializeAsTexture(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "emissiveTexture", void 0),
    __decorate([serializeAsTexture(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "reflectivityTexture", void 0),
    __decorate([serializeAsTexture(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "metallicTexture", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "metallic", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "roughness", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "metallicF0Factor", void 0),
    __decorate([serializeAsColor3(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "metallicReflectanceColor", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "useOnlyMetallicFromMetallicReflectanceTexture", void 0),
    __decorate([serializeAsTexture(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "metallicReflectanceTexture", void 0),
    __decorate([serializeAsTexture(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "reflectanceTexture", void 0),
    __decorate([serializeAsTexture(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "microSurfaceTexture", void 0),
    __decorate([serializeAsTexture(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "bumpTexture", void 0),
    __decorate([serializeAsTexture(), expandToProperty("_markAllSubMeshesAsTexturesDirty", null)], e.prototype, "lightmapTexture", void 0),
    __decorate([serializeAsColor3("ambient"), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "ambientColor", void 0),
    __decorate([serializeAsColor3("albedo"), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "albedoColor", void 0),
    __decorate([serializeAsColor3("reflectivity"), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "reflectivityColor", void 0),
    __decorate([serializeAsColor3("reflection"), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "reflectionColor", void 0),
    __decorate([serializeAsColor3("emissive"), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "emissiveColor", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "microSurface", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "useLightmapAsShadowmap", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")], e.prototype, "useAlphaFromAlbedoTexture", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")], e.prototype, "forceAlphaTest", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")], e.prototype, "alphaCutOff", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "useSpecularOverAlpha", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "useRoughnessFromMetallicTextureAlpha", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "useRoughnessFromMetallicTextureGreen", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "useMetallnessFromMetallicTextureBlue", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "useAmbientInGrayScale", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0),
    __decorate([serialize()], e.prototype, "usePhysicalLightFalloff", null),
    __decorate([serialize()], e.prototype, "useGLTFLightFalloff", null),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "useRadianceOverAlpha", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "useObjectSpaceNormalMap", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "useParallax", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "useParallaxOcclusion", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "parallaxScaleBias", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsLightsDirty")], e.prototype, "disableLighting", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "forceIrradianceInFragment", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsLightsDirty")], e.prototype, "maxSimultaneousLights", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "invertNormalMapX", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "invertNormalMapY", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "twoSidedLighting", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "useAlphaFresnel", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "useLinearAlphaFresnel", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "environmentBRDFTexture", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "forceNormalForward", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "enableSpecularAntiAliasing", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "useHorizonOcclusion", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "useRadianceOcclusion", void 0),
    __decorate([serialize(), expandToProperty("_markAllSubMeshesAsMiscDirty")], e.prototype, "unlit", void 0),
    e
}(PBRBaseMaterial);
RegisterClass("BABYLON.PBRMaterial", PBRMaterial);
var MorphTarget = function() {
    function i(e, t, r) {
        t === void 0 && (t = 0),
        r === void 0 && (r = null),
        this.name = e,
        this.animations = new Array,
        this._positions = null,
        this._normals = null,
        this._tangents = null,
        this._uvs = null,
        this._uniqueId = 0,
        this.onInfluenceChanged = new Observable,
        this._onDataLayoutChanged = new Observable,
        this._animationPropertiesOverride = null,
        this._scene = r || EngineStore.LastCreatedScene,
        this.influence = t,
        this._scene && (this._uniqueId = this._scene.getUniqueId())
    }
    return Object.defineProperty(i.prototype, "influence", {
        get: function() {
            return this._influence
        },
        set: function(e) {
            if (this._influence !== e) {
                var t = this._influence;
                this._influence = e,
                this.onInfluenceChanged.hasObservers() && this.onInfluenceChanged.notifyObservers(t === 0 || e === 0)
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "animationPropertiesOverride", {
        get: function() {
            return !this._animationPropertiesOverride && this._scene ? this._scene.animationPropertiesOverride : this._animationPropertiesOverride
        },
        set: function(e) {
            this._animationPropertiesOverride = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "uniqueId", {
        get: function() {
            return this._uniqueId
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "hasPositions", {
        get: function() {
            return !!this._positions
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "hasNormals", {
        get: function() {
            return !!this._normals
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "hasTangents", {
        get: function() {
            return !!this._tangents
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "hasUVs", {
        get: function() {
            return !!this._uvs
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.setPositions = function(e) {
        var t = this.hasPositions;
        this._positions = e,
        t !== this.hasPositions && this._onDataLayoutChanged.notifyObservers(void 0)
    }
    ,
    i.prototype.getPositions = function() {
        return this._positions
    }
    ,
    i.prototype.setNormals = function(e) {
        var t = this.hasNormals;
        this._normals = e,
        t !== this.hasNormals && this._onDataLayoutChanged.notifyObservers(void 0)
    }
    ,
    i.prototype.getNormals = function() {
        return this._normals
    }
    ,
    i.prototype.setTangents = function(e) {
        var t = this.hasTangents;
        this._tangents = e,
        t !== this.hasTangents && this._onDataLayoutChanged.notifyObservers(void 0)
    }
    ,
    i.prototype.getTangents = function() {
        return this._tangents
    }
    ,
    i.prototype.setUVs = function(e) {
        var t = this.hasUVs;
        this._uvs = e,
        t !== this.hasUVs && this._onDataLayoutChanged.notifyObservers(void 0)
    }
    ,
    i.prototype.getUVs = function() {
        return this._uvs
    }
    ,
    i.prototype.clone = function() {
        var e = this
          , t = SerializationHelper.Clone(function() {
            return new i(e.name,e.influence,e._scene)
        }, this);
        return t._positions = this._positions,
        t._normals = this._normals,
        t._tangents = this._tangents,
        t._uvs = this._uvs,
        t
    }
    ,
    i.prototype.serialize = function() {
        var e = {};
        return e.name = this.name,
        e.influence = this.influence,
        e.positions = Array.prototype.slice.call(this.getPositions()),
        this.id != null && (e.id = this.id),
        this.hasNormals && (e.normals = Array.prototype.slice.call(this.getNormals())),
        this.hasTangents && (e.tangents = Array.prototype.slice.call(this.getTangents())),
        this.hasUVs && (e.uvs = Array.prototype.slice.call(this.getUVs())),
        SerializationHelper.AppendSerializedAnimations(this, e),
        e
    }
    ,
    i.prototype.getClassName = function() {
        return "MorphTarget"
    }
    ,
    i.Parse = function(e) {
        var t = new i(e.name,e.influence);
        if (t.setPositions(e.positions),
        e.id != null && (t.id = e.id),
        e.normals && t.setNormals(e.normals),
        e.tangents && t.setTangents(e.tangents),
        e.uvs && t.setUVs(e.uvs),
        e.animations)
            for (var r = 0; r < e.animations.length; r++) {
                var n = e.animations[r]
                  , o = GetClass("BABYLON.Animation");
                o && t.animations.push(o.Parse(n))
            }
        return t
    }
    ,
    i.FromMesh = function(e, t, r) {
        t || (t = e.name);
        var n = new i(t,r,e.getScene());
        return n.setPositions(e.getVerticesData(VertexBuffer.PositionKind)),
        e.isVerticesDataPresent(VertexBuffer.NormalKind) && n.setNormals(e.getVerticesData(VertexBuffer.NormalKind)),
        e.isVerticesDataPresent(VertexBuffer.TangentKind) && n.setTangents(e.getVerticesData(VertexBuffer.TangentKind)),
        e.isVerticesDataPresent(VertexBuffer.UVKind) && n.setUVs(e.getVerticesData(VertexBuffer.UVKind)),
        n
    }
    ,
    __decorate([serialize()], i.prototype, "id", void 0),
    i
}()
  , RawTexture2DArray = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a, s, l, u, c, h) {
        l === void 0 && (l = !0),
        u === void 0 && (u = !1),
        c === void 0 && (c = Texture.TRILINEAR_SAMPLINGMODE),
        h === void 0 && (h = 0);
        var f = i.call(this, null, s, !l, u) || this;
        return f.format = a,
        f._texture = s.getEngine().createRawTexture2DArray(t, r, n, o, a, l, u, c, null, h),
        f._depth = o,
        f.is2DArray = !0,
        f
    }
    return Object.defineProperty(e.prototype, "depth", {
        get: function() {
            return this._depth
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.update = function(t) {
        !this._texture || this._getEngine().updateRawTexture2DArray(this._texture, t, this._texture.format, this._texture.invertY, null, this._texture.type)
    }
    ,
    e.CreateRGBATexture = function(t, r, n, o, a, s, l, u, c) {
        return s === void 0 && (s = !0),
        l === void 0 && (l = !1),
        u === void 0 && (u = 3),
        c === void 0 && (c = 0),
        new e(t,r,n,o,5,a,s,l,u,c)
    }
    ,
    e
}(Texture)
  , MorphTargetManager = function() {
    function i(e) {
        if (e === void 0 && (e = null),
        this._targets = new Array,
        this._targetInfluenceChangedObservers = new Array,
        this._targetDataLayoutChangedObservers = new Array,
        this._activeTargets = new SmartArray(16),
        this._supportsNormals = !1,
        this._supportsTangents = !1,
        this._supportsUVs = !1,
        this._vertexCount = 0,
        this._textureVertexStride = 0,
        this._textureWidth = 0,
        this._textureHeight = 1,
        this._uniqueId = 0,
        this._tempInfluences = new Array,
        this._canUseTextureForTargets = !1,
        this._blockCounter = 0,
        this._parentContainer = null,
        this.optimizeInfluencers = !0,
        this.enableNormalMorphing = !0,
        this.enableTangentMorphing = !0,
        this.enableUVMorphing = !0,
        this._useTextureToStoreTargets = !0,
        e || (e = EngineStore.LastCreatedScene),
        this._scene = e,
        this._scene) {
            this._scene.morphTargetManagers.push(this),
            this._uniqueId = this._scene.getUniqueId();
            var t = this._scene.getEngine().getCaps();
            this._canUseTextureForTargets = t.canUseGLVertexID && t.textureFloat && t.maxVertexTextureImageUnits > 0
        }
    }
    return Object.defineProperty(i.prototype, "areUpdatesFrozen", {
        get: function() {
            return this._blockCounter > 0
        },
        set: function(e) {
            e ? this._blockCounter++ : (this._blockCounter--,
            this._blockCounter <= 0 && (this._blockCounter = 0,
            this._syncActiveTargets(!0)))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "uniqueId", {
        get: function() {
            return this._uniqueId
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "vertexCount", {
        get: function() {
            return this._vertexCount
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "supportsNormals", {
        get: function() {
            return this._supportsNormals && this.enableNormalMorphing
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "supportsTangents", {
        get: function() {
            return this._supportsTangents && this.enableTangentMorphing
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "supportsUVs", {
        get: function() {
            return this._supportsUVs && this.enableUVMorphing
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "numTargets", {
        get: function() {
            return this._targets.length
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "numInfluencers", {
        get: function() {
            return this._activeTargets.length
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "influences", {
        get: function() {
            return this._influences
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "useTextureToStoreTargets", {
        get: function() {
            return this._useTextureToStoreTargets
        },
        set: function(e) {
            this._useTextureToStoreTargets = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "isUsingTextureForTargets", {
        get: function() {
            return i.EnableTextureStorage && this.useTextureToStoreTargets && this._canUseTextureForTargets
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.getActiveTarget = function(e) {
        return this._activeTargets.data[e]
    }
    ,
    i.prototype.getTarget = function(e) {
        return this._targets[e]
    }
    ,
    i.prototype.addTarget = function(e) {
        var t = this;
        this._targets.push(e),
        this._targetInfluenceChangedObservers.push(e.onInfluenceChanged.add(function(r) {
            t._syncActiveTargets(r)
        })),
        this._targetDataLayoutChangedObservers.push(e._onDataLayoutChanged.add(function() {
            t._syncActiveTargets(!0)
        })),
        this._syncActiveTargets(!0)
    }
    ,
    i.prototype.removeTarget = function(e) {
        var t = this._targets.indexOf(e);
        t >= 0 && (this._targets.splice(t, 1),
        e.onInfluenceChanged.remove(this._targetInfluenceChangedObservers.splice(t, 1)[0]),
        e._onDataLayoutChanged.remove(this._targetDataLayoutChangedObservers.splice(t, 1)[0]),
        this._syncActiveTargets(!0))
    }
    ,
    i.prototype._bind = function(e) {
        e.setFloat3("morphTargetTextureInfo", this._textureVertexStride, this._textureWidth, this._textureHeight),
        e.setFloatArray("morphTargetTextureIndices", this._morphTargetTextureIndices),
        e.setTexture("morphTargets", this._targetStoreTexture)
    }
    ,
    i.prototype.clone = function() {
        for (var e = new i(this._scene), t = 0, r = this._targets; t < r.length; t++) {
            var n = r[t];
            e.addTarget(n.clone())
        }
        return e.enableNormalMorphing = this.enableNormalMorphing,
        e.enableTangentMorphing = this.enableTangentMorphing,
        e.enableUVMorphing = this.enableUVMorphing,
        e
    }
    ,
    i.prototype.serialize = function() {
        var e = {};
        e.id = this.uniqueId,
        e.targets = [];
        for (var t = 0, r = this._targets; t < r.length; t++) {
            var n = r[t];
            e.targets.push(n.serialize())
        }
        return e
    }
    ,
    i.prototype._syncActiveTargets = function(e) {
        if (!this.areUpdatesFrozen) {
            var t = 0;
            this._activeTargets.reset(),
            this._supportsNormals = !0,
            this._supportsTangents = !0,
            this._supportsUVs = !0,
            this._vertexCount = 0,
            (!this._morphTargetTextureIndices || this._morphTargetTextureIndices.length !== this._targets.length) && (this._morphTargetTextureIndices = new Float32Array(this._targets.length));
            for (var r = -1, n = 0, o = this._targets; n < o.length; n++) {
                var a = o[n];
                if (r++,
                !(a.influence === 0 && this.optimizeInfluencers)) {
                    this._activeTargets.push(a),
                    this._morphTargetTextureIndices[t] = r,
                    this._tempInfluences[t++] = a.influence,
                    this._supportsNormals = this._supportsNormals && a.hasNormals,
                    this._supportsTangents = this._supportsTangents && a.hasTangents,
                    this._supportsUVs = this._supportsUVs && a.hasUVs;
                    var s = a.getPositions();
                    if (s) {
                        var l = s.length / 3;
                        if (this._vertexCount === 0)
                            this._vertexCount = l;
                        else if (this._vertexCount !== l) {
                            Logger$2.Error("Incompatible target. Targets must all have the same vertices count.");
                            return
                        }
                    }
                }
            }
            (!this._influences || this._influences.length !== t) && (this._influences = new Float32Array(t));
            for (var u = 0; u < t; u++)
                this._influences[u] = this._tempInfluences[u];
            e && this.synchronize()
        }
    }
    ,
    i.prototype.synchronize = function() {
        if (!(!this._scene || this.areUpdatesFrozen)) {
            if (this.isUsingTextureForTargets && this._vertexCount) {
                this._textureVertexStride = 1,
                this._supportsNormals && this._textureVertexStride++,
                this._supportsTangents && this._textureVertexStride++,
                this._supportsUVs && this._textureVertexStride++,
                this._textureWidth = this._vertexCount * this._textureVertexStride,
                this._textureHeight = 1;
                var e = this._scene.getEngine().getCaps().maxTextureSize;
                this._textureWidth > e && (this._textureHeight = Math.ceil(this._textureWidth / e),
                this._textureWidth = e);
                var t = !0;
                if (this._targetStoreTexture) {
                    var r = this._targetStoreTexture.getSize();
                    r.width === this._textureWidth && r.height === this._textureHeight && this._targetStoreTexture.depth === this._targets.length && (t = !1)
                }
                if (t) {
                    this._targetStoreTexture && this._targetStoreTexture.dispose();
                    for (var n = this._targets.length, o = new Float32Array(n * this._textureWidth * this._textureHeight * 4), a = 0, s = 0; s < n; s++) {
                        var l = this._targets[s]
                          , u = l.getPositions()
                          , c = l.getNormals()
                          , h = l.getUVs()
                          , f = l.getTangents();
                        if (!u) {
                            s === 0 && Logger$2.Error("Invalid morph target. Target must have positions.");
                            return
                        }
                        a = s * this._textureWidth * this._textureHeight * 4;
                        for (var d = 0; d < this._vertexCount; d++)
                            o[a] = u[d * 3],
                            o[a + 1] = u[d * 3 + 1],
                            o[a + 2] = u[d * 3 + 2],
                            a += 4,
                            c && (o[a] = c[d * 3],
                            o[a + 1] = c[d * 3 + 1],
                            o[a + 2] = c[d * 3 + 2],
                            a += 4),
                            h && (o[a] = h[d * 2],
                            o[a + 1] = h[d * 2 + 1],
                            a += 4),
                            f && (o[a] = f[d * 3],
                            o[a + 1] = f[d * 3 + 1],
                            o[a + 2] = f[d * 3 + 2],
                            a += 4)
                    }
                    this._targetStoreTexture = RawTexture2DArray.CreateRGBATexture(o, this._textureWidth, this._textureHeight, n, this._scene, !1, !1, 1, 1)
                }
            }
            for (var _ = 0, g = this._scene.meshes; _ < g.length; _++) {
                var m = g[_];
                m.morphTargetManager === this && m._syncGeometryWithMorphTargetManager()
            }
        }
    }
    ,
    i.prototype.dispose = function() {
        if (this._targetStoreTexture && this._targetStoreTexture.dispose(),
        this._targetStoreTexture = null,
        this._scene && (this._scene.removeMorphTargetManager(this),
        this._parentContainer)) {
            var e = this._parentContainer.morphTargetManagers.indexOf(this);
            e > -1 && this._parentContainer.morphTargetManagers.splice(e, 1),
            this._parentContainer = null
        }
    }
    ,
    i.Parse = function(e, t) {
        var r = new i(t);
        r._uniqueId = e.id;
        for (var n = 0, o = e.targets; n < o.length; n++) {
            var a = o[n];
            r.addTarget(MorphTarget.Parse(a))
        }
        return r
    }
    ,
    i.EnableTextureStorage = !0,
    i
}()
  , ArrayItem = function() {
    function i() {}
    return i.Get = function(e, t, r) {
        if (!t || r == null || !t[r])
            throw new Error(e + ": Failed to find index (" + r + ")");
        return t[r]
    }
    ,
    i.Assign = function(e) {
        if (e)
            for (var t = 0; t < e.length; t++)
                e[t].index = t
    }
    ,
    i
}()
  , GLTFLoader = function() {
    function i(e) {
        this._completePromises = new Array,
        this._assetContainer = null,
        this._babylonLights = [],
        this._disableInstancedMesh = 0,
        this._disposed = !1,
        this._extensions = new Array,
        this._rootBabylonMesh = null,
        this._defaultBabylonMaterialData = {},
        this._parent = e
    }
    return i.RegisterExtension = function(e, t) {
        i.UnregisterExtension(e) && Logger$2.Warn("Extension with the name '" + e + "' already exists"),
        i._RegisteredExtensions[e] = {
            factory: t
        }
    }
    ,
    i.UnregisterExtension = function(e) {
        return i._RegisteredExtensions[e] ? (delete i._RegisteredExtensions[e],
        !0) : !1
    }
    ,
    Object.defineProperty(i.prototype, "gltf", {
        get: function() {
            return this._gltf
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "bin", {
        get: function() {
            return this._bin
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "parent", {
        get: function() {
            return this._parent
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "babylonScene", {
        get: function() {
            return this._babylonScene
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "rootBabylonMesh", {
        get: function() {
            return this._rootBabylonMesh
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.dispose = function() {
        if (!this._disposed) {
            this._disposed = !0,
            this._completePromises.length = 0;
            for (var e in this._extensions) {
                var t = this._extensions[e];
                t.dispose && t.dispose(),
                delete this._extensions[e]
            }
            this._gltf = null,
            this._babylonScene = null,
            this._rootBabylonMesh = null,
            this._parent.dispose()
        }
    }
    ,
    i.prototype.importMeshAsync = function(e, t, r, n, o, a, s) {
        var l = this;
        return s === void 0 && (s = ""),
        Promise.resolve().then(function() {
            l._babylonScene = t,
            l._assetContainer = r,
            l._loadData(n);
            var u = null;
            if (e) {
                var c = {};
                if (l._gltf.nodes)
                    for (var h = 0, f = l._gltf.nodes; h < f.length; h++) {
                        var d = f[h];
                        d.name && (c[d.name] = d.index)
                    }
                var _ = e instanceof Array ? e : [e];
                u = _.map(function(g) {
                    var m = c[g];
                    if (m === void 0)
                        throw new Error("Failed to find node '" + g + "'");
                    return m
                })
            }
            return l._loadAsync(o, s, u, function() {
                return {
                    meshes: l._getMeshes(),
                    particleSystems: [],
                    skeletons: l._getSkeletons(),
                    animationGroups: l._getAnimationGroups(),
                    lights: l._babylonLights,
                    transformNodes: l._getTransformNodes(),
                    geometries: l._getGeometries()
                }
            })
        })
    }
    ,
    i.prototype.loadAsync = function(e, t, r, n, o) {
        var a = this;
        return o === void 0 && (o = ""),
        Promise.resolve().then(function() {
            return a._babylonScene = e,
            a._loadData(t),
            a._loadAsync(r, o, null, function() {})
        })
    }
    ,
    i.prototype._loadAsync = function(e, t, r, n) {
        var o = this;
        return Promise.resolve().then(function() {
            o._rootUrl = e,
            o._uniqueRootUrl = !StringTools.StartsWith(e, "file:") && t ? e : "" + e + Date.now() + "/",
            o._fileName = t,
            o._loadExtensions(),
            o._checkExtensions();
            var a = GLTFLoaderState[GLTFLoaderState.LOADING] + " => " + GLTFLoaderState[GLTFLoaderState.READY]
              , s = GLTFLoaderState[GLTFLoaderState.LOADING] + " => " + GLTFLoaderState[GLTFLoaderState.COMPLETE];
            o._parent._startPerformanceCounter(a),
            o._parent._startPerformanceCounter(s),
            o._parent._setState(GLTFLoaderState.LOADING),
            o._extensionsOnLoading();
            var l = new Array
              , u = o._babylonScene.blockMaterialDirtyMechanism;
            if (o._babylonScene.blockMaterialDirtyMechanism = !0,
            r)
                l.push(o.loadSceneAsync("/nodes", {
                    nodes: r,
                    index: -1
                }));
            else if (o._gltf.scene != null || o._gltf.scenes && o._gltf.scenes[0]) {
                var c = ArrayItem.Get("/scene", o._gltf.scenes, o._gltf.scene || 0);
                l.push(o.loadSceneAsync("/scenes/" + c.index, c))
            }
            if (o.parent.loadAllMaterials && o._gltf.materials)
                for (var h = 0; h < o._gltf.materials.length; ++h) {
                    var f = o._gltf.materials[h]
                      , d = "/materials/" + h
                      , _ = Material.TriangleFillMode;
                    l.push(o._loadMaterialAsync(d, f, null, _, function(m) {}))
                }
            o._babylonScene.blockMaterialDirtyMechanism = u,
            o._parent.compileMaterials && l.push(o._compileMaterialsAsync()),
            o._parent.compileShadowGenerators && l.push(o._compileShadowGeneratorsAsync());
            var g = Promise.all(l).then(function() {
                return o._rootBabylonMesh && o._rootBabylonMesh.setEnabled(!0),
                o._extensionsOnReady(),
                o._parent._setState(GLTFLoaderState.READY),
                o._startAnimations(),
                n()
            });
            return g.then(function(m) {
                return o._parent._endPerformanceCounter(a),
                Tools.SetImmediate(function() {
                    o._disposed || Promise.all(o._completePromises).then(function() {
                        o._parent._endPerformanceCounter(s),
                        o._parent._setState(GLTFLoaderState.COMPLETE),
                        o._parent.onCompleteObservable.notifyObservers(void 0),
                        o._parent.onCompleteObservable.clear(),
                        o.dispose()
                    }, function(v) {
                        o._parent.onErrorObservable.notifyObservers(v),
                        o._parent.onErrorObservable.clear(),
                        o.dispose()
                    })
                }),
                m
            })
        }).catch(function(a) {
            throw o._disposed || (o._parent.onErrorObservable.notifyObservers(a),
            o._parent.onErrorObservable.clear(),
            o.dispose()),
            a
        })
    }
    ,
    i.prototype._loadData = function(e) {
        if (this._gltf = e.json,
        this._setupData(),
        e.bin) {
            var t = this._gltf.buffers;
            if (t && t[0] && !t[0].uri) {
                var r = t[0];
                (r.byteLength < e.bin.byteLength - 3 || r.byteLength > e.bin.byteLength) && Logger$2.Warn("Binary buffer length (" + r.byteLength + ") from JSON does not match chunk length (" + e.bin.byteLength + ")"),
                this._bin = e.bin
            } else
                Logger$2.Warn("Unexpected BIN chunk")
        }
    }
    ,
    i.prototype._setupData = function() {
        if (ArrayItem.Assign(this._gltf.accessors),
        ArrayItem.Assign(this._gltf.animations),
        ArrayItem.Assign(this._gltf.buffers),
        ArrayItem.Assign(this._gltf.bufferViews),
        ArrayItem.Assign(this._gltf.cameras),
        ArrayItem.Assign(this._gltf.images),
        ArrayItem.Assign(this._gltf.materials),
        ArrayItem.Assign(this._gltf.meshes),
        ArrayItem.Assign(this._gltf.nodes),
        ArrayItem.Assign(this._gltf.samplers),
        ArrayItem.Assign(this._gltf.scenes),
        ArrayItem.Assign(this._gltf.skins),
        ArrayItem.Assign(this._gltf.textures),
        this._gltf.nodes) {
            for (var e = {}, t = 0, r = this._gltf.nodes; t < r.length; t++) {
                var n = r[t];
                if (n.children)
                    for (var o = 0, a = n.children; o < a.length; o++) {
                        var s = a[o];
                        e[s] = n.index
                    }
            }
            for (var l = this._createRootNode(), u = 0, c = this._gltf.nodes; u < c.length; u++) {
                var n = c[u]
                  , h = e[n.index];
                n.parent = h === void 0 ? l : this._gltf.nodes[h]
            }
        }
    }
    ,
    i.prototype._loadExtensions = function() {
        for (var e in i._RegisteredExtensions) {
            var t = i._RegisteredExtensions[e].factory(this);
            t.name !== e && Logger$2.Warn("The name of the glTF loader extension instance does not match the registered name: " + t.name + " !== " + e),
            this._extensions.push(t),
            this._parent.onExtensionLoadedObservable.notifyObservers(t)
        }
        this._extensions.sort(function(r, n) {
            return (r.order || Number.MAX_VALUE) - (n.order || Number.MAX_VALUE)
        }),
        this._parent.onExtensionLoadedObservable.clear()
    }
    ,
    i.prototype._checkExtensions = function() {
        if (this._gltf.extensionsRequired)
            for (var e = function(a) {
                var s = t._extensions.some(function(l) {
                    return l.name === a && l.enabled
                });
                if (!s)
                    throw new Error("Require extension " + a + " is not available")
            }, t = this, r = 0, n = this._gltf.extensionsRequired; r < n.length; r++) {
                var o = n[r];
                e(o)
            }
    }
    ,
    i.prototype._createRootNode = function() {
        this._babylonScene._blockEntityCollection = !!this._assetContainer,
        this._rootBabylonMesh = new Mesh("__root__",this._babylonScene),
        this._rootBabylonMesh._parentContainer = this._assetContainer,
        this._babylonScene._blockEntityCollection = !1,
        this._rootBabylonMesh.setEnabled(!1);
        var e = {
            _babylonTransformNode: this._rootBabylonMesh,
            index: -1
        };
        switch (this._parent.coordinateSystemMode) {
        case GLTFLoaderCoordinateSystemMode.AUTO:
            {
                this._babylonScene.useRightHandedSystem || (e.rotation = [0, 1, 0, 0],
                e.scale = [1, 1, -1],
                i._LoadTransform(e, this._rootBabylonMesh));
                break
            }
        case GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED:
            {
                this._babylonScene.useRightHandedSystem = !0;
                break
            }
        default:
            throw new Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")")
        }
        return this._parent.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh),
        e
    }
    ,
    i.prototype.loadSceneAsync = function(e, t) {
        var r = this
          , n = this._extensionsLoadSceneAsync(e, t);
        if (n)
            return n;
        var o = new Array;
        if (this.logOpen(e + " " + (t.name || "")),
        t.nodes)
            for (var a = 0, s = t.nodes; a < s.length; a++) {
                var l = s[a]
                  , u = ArrayItem.Get(e + "/nodes/" + l, this._gltf.nodes, l);
                o.push(this.loadNodeAsync("/nodes/" + u.index, u, function(g) {
                    g.parent = r._rootBabylonMesh
                }))
            }
        if (this._gltf.nodes)
            for (var c = 0, h = this._gltf.nodes; c < h.length; c++) {
                var u = h[c];
                if (u._babylonTransformNode && u._babylonBones)
                    for (var f = 0, d = u._babylonBones; f < d.length; f++) {
                        var _ = d[f];
                        _.linkTransformNode(u._babylonTransformNode)
                    }
            }
        return o.push(this._loadAnimationsAsync()),
        this.logClose(),
        Promise.all(o).then(function() {})
    }
    ,
    i.prototype._forEachPrimitive = function(e, t) {
        if (e._primitiveBabylonMeshes)
            for (var r = 0, n = e._primitiveBabylonMeshes; r < n.length; r++) {
                var o = n[r];
                t(o)
            }
    }
    ,
    i.prototype._getGeometries = function() {
        var e = new Array
          , t = this._gltf.nodes;
        if (t)
            for (var r = 0, n = t; r < n.length; r++) {
                var o = n[r];
                this._forEachPrimitive(o, function(a) {
                    var s = a.geometry;
                    s && e.indexOf(s) === -1 && e.push(s)
                })
            }
        return e
    }
    ,
    i.prototype._getMeshes = function() {
        var e = new Array;
        this._rootBabylonMesh && e.push(this._rootBabylonMesh);
        var t = this._gltf.nodes;
        if (t)
            for (var r = 0, n = t; r < n.length; r++) {
                var o = n[r];
                this._forEachPrimitive(o, function(a) {
                    e.push(a)
                })
            }
        return e
    }
    ,
    i.prototype._getTransformNodes = function() {
        var e = new Array
          , t = this._gltf.nodes;
        if (t)
            for (var r = 0, n = t; r < n.length; r++) {
                var o = n[r];
                o._babylonTransformNode && o._babylonTransformNode.getClassName() === "TransformNode" && e.push(o._babylonTransformNode)
            }
        return e
    }
    ,
    i.prototype._getSkeletons = function() {
        var e = new Array
          , t = this._gltf.skins;
        if (t)
            for (var r = 0, n = t; r < n.length; r++) {
                var o = n[r];
                o._data && e.push(o._data.babylonSkeleton)
            }
        return e
    }
    ,
    i.prototype._getAnimationGroups = function() {
        var e = new Array
          , t = this._gltf.animations;
        if (t)
            for (var r = 0, n = t; r < n.length; r++) {
                var o = n[r];
                o._babylonAnimationGroup && e.push(o._babylonAnimationGroup)
            }
        return e
    }
    ,
    i.prototype._startAnimations = function() {
        switch (this._parent.animationStartMode) {
        case GLTFLoaderAnimationStartMode.NONE:
            break;
        case GLTFLoaderAnimationStartMode.FIRST:
            {
                var e = this._getAnimationGroups();
                e.length !== 0 && e[0].start(!0);
                break
            }
        case GLTFLoaderAnimationStartMode.ALL:
            {
                for (var e = this._getAnimationGroups(), t = 0, r = e; t < r.length; t++) {
                    var n = r[t];
                    n.start(!0)
                }
                break
            }
        default:
            {
                Logger$2.Error("Invalid animation start mode (" + this._parent.animationStartMode + ")");
                return
            }
        }
    }
    ,
    i.prototype.loadNodeAsync = function(e, t, r) {
        var n = this;
        r === void 0 && (r = function() {}
        );
        var o = this._extensionsLoadNodeAsync(e, t, r);
        if (o)
            return o;
        if (t._babylonTransformNode)
            throw new Error(e + ": Invalid recursive node hierarchy");
        var a = new Array;
        this.logOpen(e + " " + (t.name || ""));
        var s = function(c) {
            if (i.AddPointerMetadata(c, e),
            i._LoadTransform(t, c),
            t.camera != null) {
                var h = ArrayItem.Get(e + "/camera", n._gltf.cameras, t.camera);
                a.push(n.loadCameraAsync("/cameras/" + h.index, h, function(m) {
                    m.parent = c
                }))
            }
            if (t.children)
                for (var f = 0, d = t.children; f < d.length; f++) {
                    var _ = d[f]
                      , g = ArrayItem.Get(e + "/children/" + _, n._gltf.nodes, _);
                    a.push(n.loadNodeAsync("/nodes/" + g.index, g, function(m) {
                        m.parent = c
                    }))
                }
            r(c)
        };
        if (t.mesh == null) {
            var l = t.name || "node" + t.index;
            this._babylonScene._blockEntityCollection = !!this._assetContainer,
            t._babylonTransformNode = new TransformNode(l,this._babylonScene),
            t._babylonTransformNode._parentContainer = this._assetContainer,
            this._babylonScene._blockEntityCollection = !1,
            s(t._babylonTransformNode)
        } else {
            var u = ArrayItem.Get(e + "/mesh", this._gltf.meshes, t.mesh);
            a.push(this._loadMeshAsync("/meshes/" + u.index, t, u, s))
        }
        return this.logClose(),
        Promise.all(a).then(function() {
            return n._forEachPrimitive(t, function(c) {
                c.geometry && c.geometry.useBoundingInfoFromGeometry ? c._updateBoundingInfo() : c.refreshBoundingInfo(!0)
            }),
            t._babylonTransformNode
        })
    }
    ,
    i.prototype._loadMeshAsync = function(e, t, r, n) {
        var o = r.primitives;
        if (!o || !o.length)
            throw new Error(e + ": Primitives are missing");
        o[0].index == null && ArrayItem.Assign(o);
        var a = new Array;
        this.logOpen(e + " " + (r.name || ""));
        var s = t.name || "node" + t.index;
        if (o.length === 1) {
            var l = r.primitives[0];
            a.push(this._loadMeshPrimitiveAsync(e + "/primitives/" + l.index, s, t, r, l, function(f) {
                t._babylonTransformNode = f,
                t._primitiveBabylonMeshes = [f]
            }))
        } else {
            this._babylonScene._blockEntityCollection = !!this._assetContainer,
            t._babylonTransformNode = new TransformNode(s,this._babylonScene),
            t._babylonTransformNode._parentContainer = this._assetContainer,
            this._babylonScene._blockEntityCollection = !1,
            t._primitiveBabylonMeshes = [];
            for (var u = 0, c = o; u < c.length; u++) {
                var l = c[u];
                a.push(this._loadMeshPrimitiveAsync(e + "/primitives/" + l.index, s + "_primitive" + l.index, t, r, l, function(d) {
                    d.parent = t._babylonTransformNode,
                    t._primitiveBabylonMeshes.push(d)
                }))
            }
        }
        if (t.skin != null) {
            var h = ArrayItem.Get(e + "/skin", this._gltf.skins, t.skin);
            a.push(this._loadSkinAsync("/skins/" + h.index, t, h))
        }
        return n(t._babylonTransformNode),
        this.logClose(),
        Promise.all(a).then(function() {
            return t._babylonTransformNode
        })
    }
    ,
    i.prototype._loadMeshPrimitiveAsync = function(e, t, r, n, o, a) {
        var s = this
          , l = this._extensionsLoadMeshPrimitiveAsync(e, t, r, n, o, a);
        if (l)
            return l;
        this.logOpen("" + e);
        var u = this._disableInstancedMesh === 0 && this._parent.createInstances && r.skin == null && !n.primitives[0].targets, c, h;
        if (u && o._instanceData)
            this._babylonScene._blockEntityCollection = !!this._assetContainer,
            c = o._instanceData.babylonSourceMesh.createInstance(t),
            c._parentContainer = this._assetContainer,
            this._babylonScene._blockEntityCollection = !1,
            h = o._instanceData.promise;
        else {
            var f = new Array;
            this._babylonScene._blockEntityCollection = !!this._assetContainer;
            var d = new Mesh(t,this._babylonScene);
            d._parentContainer = this._assetContainer,
            this._babylonScene._blockEntityCollection = !1,
            d.overrideMaterialSideOrientation = this._babylonScene.useRightHandedSystem ? Material.CounterClockWiseSideOrientation : Material.ClockWiseSideOrientation,
            this._createMorphTargets(e, r, n, o, d),
            f.push(this._loadVertexDataAsync(e, o, d).then(function(v) {
                return s._loadMorphTargetsAsync(e, o, d, v).then(function() {
                    s._babylonScene._blockEntityCollection = !!s._assetContainer,
                    v.applyToMesh(d),
                    v._parentContainer = s._assetContainer,
                    s._babylonScene._blockEntityCollection = !1
                })
            }));
            var _ = i._GetDrawMode(e, o.mode);
            if (o.material == null) {
                var g = this._defaultBabylonMaterialData[_];
                g || (g = this._createDefaultMaterial("__GLTFLoader._default", _),
                this._parent.onMaterialLoadedObservable.notifyObservers(g),
                this._defaultBabylonMaterialData[_] = g),
                d.material = g
            } else {
                var m = ArrayItem.Get(e + "/material", this._gltf.materials, o.material);
                f.push(this._loadMaterialAsync("/materials/" + m.index, m, d, _, function(v) {
                    d.material = v
                }))
            }
            h = Promise.all(f),
            u && (o._instanceData = {
                babylonSourceMesh: d,
                promise: h
            }),
            c = d
        }
        return i.AddPointerMetadata(c, e),
        this._parent.onMeshLoadedObservable.notifyObservers(c),
        a(c),
        this.logClose(),
        h.then(function() {
            return c
        })
    }
    ,
    i.prototype._loadVertexDataAsync = function(e, t, r) {
        var n = this
          , o = this._extensionsLoadVertexDataAsync(e, t, r);
        if (o)
            return o;
        var a = t.attributes;
        if (!a)
            throw new Error(e + ": Attributes are missing");
        var s = new Array
          , l = new Geometry(r.name,this._babylonScene);
        if (t.indices == null)
            r.isUnIndexed = !0;
        else {
            var u = ArrayItem.Get(e + "/indices", this._gltf.accessors, t.indices);
            s.push(this._loadIndicesAccessorAsync("/accessors/" + u.index, u).then(function(h) {
                l.setIndices(h)
            }))
        }
        var c = function(h, f, d) {
            if (a[h] != null) {
                r._delayInfo = r._delayInfo || [],
                r._delayInfo.indexOf(f) === -1 && r._delayInfo.push(f);
                var _ = ArrayItem.Get(e + "/attributes/" + h, n._gltf.accessors, a[h]);
                s.push(n._loadVertexAccessorAsync("/accessors/" + _.index, _, f).then(function(g) {
                    if (g.getKind() === VertexBuffer.PositionKind && !n.parent.alwaysComputeBoundingBox && !r.skeleton) {
                        var m = _.min
                          , v = _.max;
                        if (m !== void 0 && v !== void 0) {
                            if (_.normalized && _.componentType !== 5126) {
                                var y = 1;
                                switch (_.componentType) {
                                case 5120:
                                    y = 127;
                                    break;
                                case 5121:
                                    y = 255;
                                    break;
                                case 5122:
                                    y = 32767;
                                    break;
                                case 5123:
                                    y = 65535;
                                    break
                                }
                                for (var b = 0; b < 3; ++b)
                                    m[b] = Math.max(m[b] / y, -1),
                                    v[b] = Math.max(v[b] / y, -1)
                            }
                            var T = TmpVectors.Vector3[0]
                              , C = TmpVectors.Vector3[1];
                            T.copyFromFloats.apply(T, m),
                            C.copyFromFloats.apply(C, v),
                            l._boundingInfo = new BoundingInfo(T,C),
                            l.useBoundingInfoFromGeometry = !0
                        }
                    }
                    l.setVerticesBuffer(g, _.count)
                })),
                f == VertexBuffer.MatricesIndicesExtraKind && (r.numBoneInfluencers = 8),
                d && d(_)
            }
        };
        return c("POSITION", VertexBuffer.PositionKind),
        c("NORMAL", VertexBuffer.NormalKind),
        c("TANGENT", VertexBuffer.TangentKind),
        c("TEXCOORD_0", VertexBuffer.UVKind),
        c("TEXCOORD_1", VertexBuffer.UV2Kind),
        c("TEXCOORD_2", VertexBuffer.UV3Kind),
        c("TEXCOORD_3", VertexBuffer.UV4Kind),
        c("TEXCOORD_4", VertexBuffer.UV5Kind),
        c("TEXCOORD_5", VertexBuffer.UV6Kind),
        c("JOINTS_0", VertexBuffer.MatricesIndicesKind),
        c("WEIGHTS_0", VertexBuffer.MatricesWeightsKind),
        c("JOINTS_1", VertexBuffer.MatricesIndicesExtraKind),
        c("WEIGHTS_1", VertexBuffer.MatricesWeightsExtraKind),
        c("COLOR_0", VertexBuffer.ColorKind, function(h) {
            h.type === "VEC4" && (r.hasVertexAlpha = !0)
        }),
        Promise.all(s).then(function() {
            return l
        })
    }
    ,
    i.prototype._createMorphTargets = function(e, t, r, n, o) {
        if (!!n.targets) {
            if (t._numMorphTargets == null)
                t._numMorphTargets = n.targets.length;
            else if (n.targets.length !== t._numMorphTargets)
                throw new Error(e + ": Primitives do not have the same number of targets");
            var a = r.extras ? r.extras.targetNames : null;
            o.morphTargetManager = new MorphTargetManager(o.getScene()),
            o.morphTargetManager.areUpdatesFrozen = !0;
            for (var s = 0; s < n.targets.length; s++) {
                var l = t.weights ? t.weights[s] : r.weights ? r.weights[s] : 0
                  , u = a ? a[s] : "morphTarget" + s;
                o.morphTargetManager.addTarget(new MorphTarget(u,l,o.getScene()))
            }
        }
    }
    ,
    i.prototype._loadMorphTargetsAsync = function(e, t, r, n) {
        if (!t.targets)
            return Promise.resolve();
        for (var o = new Array, a = r.morphTargetManager, s = 0; s < a.numTargets; s++) {
            var l = a.getTarget(s);
            o.push(this._loadMorphTargetVertexDataAsync(e + "/targets/" + s, n, t.targets[s], l))
        }
        return Promise.all(o).then(function() {
            a.areUpdatesFrozen = !1
        })
    }
    ,
    i.prototype._loadMorphTargetVertexDataAsync = function(e, t, r, n) {
        var o = this
          , a = new Array
          , s = function(l, u, c) {
            if (r[l] != null) {
                var h = t.getVertexBuffer(u);
                if (!!h) {
                    var f = ArrayItem.Get(e + "/" + l, o._gltf.accessors, r[l]);
                    a.push(o._loadFloatAccessorAsync("/accessors/" + f.index, f).then(function(d) {
                        c(h, d)
                    }))
                }
            }
        };
        return s("POSITION", VertexBuffer.PositionKind, function(l, u) {
            var c = new Float32Array(u.length);
            l.forEach(u.length, function(h, f) {
                c[f] = u[f] + h
            }),
            n.setPositions(c)
        }),
        s("NORMAL", VertexBuffer.NormalKind, function(l, u) {
            var c = new Float32Array(u.length);
            l.forEach(c.length, function(h, f) {
                c[f] = u[f] + h
            }),
            n.setNormals(c)
        }),
        s("TANGENT", VertexBuffer.TangentKind, function(l, u) {
            var c = new Float32Array(u.length / 3 * 4)
              , h = 0;
            l.forEach(u.length / 3 * 4, function(f, d) {
                (d + 1) % 4 !== 0 && (c[h] = u[h] + f,
                h++)
            }),
            n.setTangents(c)
        }),
        Promise.all(a).then(function() {})
    }
    ,
    i._LoadTransform = function(e, t) {
        if (e.skin == null) {
            var r = Vector3.Zero()
              , n = Quaternion.Identity()
              , o = Vector3.One();
            if (e.matrix) {
                var a = Matrix.FromArray(e.matrix);
                a.decompose(o, n, r)
            } else
                e.translation && (r = Vector3.FromArray(e.translation)),
                e.rotation && (n = Quaternion.FromArray(e.rotation)),
                e.scale && (o = Vector3.FromArray(e.scale));
            t.position = r,
            t.rotationQuaternion = n,
            t.scaling = o
        }
    }
    ,
    i.prototype._loadSkinAsync = function(e, t, r) {
        var n = this
          , o = this._extensionsLoadSkinAsync(e, t, r);
        if (o)
            return o;
        var a = function(c) {
            n._forEachPrimitive(t, function(h) {
                h.skeleton = c
            })
        };
        if (r._data)
            return a(r._data.babylonSkeleton),
            r._data.promise;
        var s = "skeleton" + r.index;
        this._babylonScene._blockEntityCollection = !!this._assetContainer;
        var l = new Skeleton(r.name || s,s,this._babylonScene);
        l._parentContainer = this._assetContainer,
        this._babylonScene._blockEntityCollection = !1,
        l.overrideMesh = this._rootBabylonMesh,
        this._loadBones(e, r, l),
        a(l);
        var u = this._loadSkinInverseBindMatricesDataAsync(e, r).then(function(c) {
            n._updateBoneMatrices(l, c)
        });
        return r._data = {
            babylonSkeleton: l,
            promise: u
        },
        u
    }
    ,
    i.prototype._loadBones = function(e, t, r) {
        for (var n = {}, o = 0, a = t.joints; o < a.length; o++) {
            var s = a[o]
              , l = ArrayItem.Get(e + "/joints/" + s, this._gltf.nodes, s);
            this._loadBone(l, t, r, n)
        }
    }
    ,
    i.prototype._loadBone = function(e, t, r, n) {
        var o = n[e.index];
        if (o)
            return o;
        var a = null;
        e.parent && e.parent._babylonTransformNode !== this._rootBabylonMesh && (a = this._loadBone(e.parent, t, r, n));
        var s = t.joints.indexOf(e.index);
        return o = new Bone(e.name || "joint" + e.index,r,a,this._getNodeMatrix(e),null,null,s),
        n[e.index] = o,
        e._babylonBones = e._babylonBones || [],
        e._babylonBones.push(o),
        o
    }
    ,
    i.prototype._loadSkinInverseBindMatricesDataAsync = function(e, t) {
        if (t.inverseBindMatrices == null)
            return Promise.resolve(null);
        var r = ArrayItem.Get(e + "/inverseBindMatrices", this._gltf.accessors, t.inverseBindMatrices);
        return this._loadFloatAccessorAsync("/accessors/" + r.index, r)
    }
    ,
    i.prototype._updateBoneMatrices = function(e, t) {
        for (var r = 0, n = e.bones; r < n.length; r++) {
            var o = n[r]
              , a = Matrix.Identity()
              , s = o._index;
            t && s !== -1 && (Matrix.FromArrayToRef(t, s * 16, a),
            a.invertToRef(a));
            var l = o.getParent();
            l && a.multiplyToRef(l.getInvertedAbsoluteTransform(), a),
            o.updateMatrix(a, !1, !1),
            o._updateDifferenceMatrix(void 0, !1)
        }
    }
    ,
    i.prototype._getNodeMatrix = function(e) {
        return e.matrix ? Matrix.FromArray(e.matrix) : Matrix.Compose(e.scale ? Vector3.FromArray(e.scale) : Vector3.One(), e.rotation ? Quaternion.FromArray(e.rotation) : Quaternion.Identity(), e.translation ? Vector3.FromArray(e.translation) : Vector3.Zero())
    }
    ,
    i.prototype.loadCameraAsync = function(e, t, r) {
        r === void 0 && (r = function() {}
        );
        var n = this._extensionsLoadCameraAsync(e, t, r);
        if (n)
            return n;
        var o = new Array;
        this.logOpen(e + " " + (t.name || "")),
        this._babylonScene._blockEntityCollection = !!this._assetContainer;
        var a = new FreeCamera(t.name || "camera" + t.index,Vector3.Zero(),this._babylonScene,!1);
        switch (a._parentContainer = this._assetContainer,
        this._babylonScene._blockEntityCollection = !1,
        a.ignoreParentScaling = !0,
        a.rotation = new Vector3(0,Math.PI,0),
        t.type) {
        case "perspective":
            {
                var s = t.perspective;
                if (!s)
                    throw new Error(e + ": Camera perspective properties are missing");
                a.fov = s.yfov,
                a.minZ = s.znear,
                a.maxZ = s.zfar || 0;
                break
            }
        case "orthographic":
            {
                if (!t.orthographic)
                    throw new Error(e + ": Camera orthographic properties are missing");
                a.mode = Camera$1.ORTHOGRAPHIC_CAMERA,
                a.orthoLeft = -t.orthographic.xmag,
                a.orthoRight = t.orthographic.xmag,
                a.orthoBottom = -t.orthographic.ymag,
                a.orthoTop = t.orthographic.ymag,
                a.minZ = t.orthographic.znear,
                a.maxZ = t.orthographic.zfar;
                break
            }
        default:
            throw new Error(e + ": Invalid camera type (" + t.type + ")")
        }
        return i.AddPointerMetadata(a, e),
        this._parent.onCameraLoadedObservable.notifyObservers(a),
        r(a),
        this.logClose(),
        Promise.all(o).then(function() {
            return a
        })
    }
    ,
    i.prototype._loadAnimationsAsync = function() {
        var e = this._gltf.animations;
        if (!e)
            return Promise.resolve();
        for (var t = new Array, r = 0; r < e.length; r++) {
            var n = e[r];
            t.push(this.loadAnimationAsync("/animations/" + n.index, n).then(function(o) {
                o.targetedAnimations.length === 0 && o.dispose()
            }))
        }
        return Promise.all(t).then(function() {})
    }
    ,
    i.prototype.loadAnimationAsync = function(e, t) {
        var r = this._extensionsLoadAnimationAsync(e, t);
        if (r)
            return r;
        this._babylonScene._blockEntityCollection = !!this._assetContainer;
        var n = new AnimationGroup(t.name || "animation" + t.index,this._babylonScene);
        n._parentContainer = this._assetContainer,
        this._babylonScene._blockEntityCollection = !1,
        t._babylonAnimationGroup = n;
        var o = new Array;
        ArrayItem.Assign(t.channels),
        ArrayItem.Assign(t.samplers);
        for (var a = 0, s = t.channels; a < s.length; a++) {
            var l = s[a];
            o.push(this._loadAnimationChannelAsync(e + "/channels/" + l.index, e, t, l, n))
        }
        return Promise.all(o).then(function() {
            return n.normalize(0),
            n
        })
    }
    ,
    i.prototype._loadAnimationChannelAsync = function(e, t, r, n, o, a) {
        var s = this;
        if (a === void 0 && (a = null),
        n.target.node == null)
            return Promise.resolve();
        var l = ArrayItem.Get(e + "/target/node", this._gltf.nodes, n.target.node);
        if (n.target.path === "weights" && !l._numMorphTargets || n.target.path !== "weights" && !l._babylonTransformNode)
            return Promise.resolve();
        var u = ArrayItem.Get(e + "/sampler", r.samplers, n.sampler);
        return this._loadAnimationSamplerAsync(t + "/samplers/" + n.sampler, u).then(function(c) {
            var h, f;
            switch (n.target.path) {
            case "translation":
                {
                    h = "position",
                    f = Animation.ANIMATIONTYPE_VECTOR3;
                    break
                }
            case "rotation":
                {
                    h = "rotationQuaternion",
                    f = Animation.ANIMATIONTYPE_QUATERNION;
                    break
                }
            case "scale":
                {
                    h = "scaling",
                    f = Animation.ANIMATIONTYPE_VECTOR3;
                    break
                }
            case "weights":
                {
                    h = "influence",
                    f = Animation.ANIMATIONTYPE_FLOAT;
                    break
                }
            default:
                throw new Error(e + "/target/path: Invalid value (" + n.target.path + ")")
            }
            var d = 0, _;
            switch (h) {
            case "position":
                {
                    _ = function() {
                        var A = Vector3.FromArray(c.output, d);
                        return d += 3,
                        A
                    }
                    ;
                    break
                }
            case "rotationQuaternion":
                {
                    _ = function() {
                        var A = Quaternion.FromArray(c.output, d);
                        return d += 4,
                        A
                    }
                    ;
                    break
                }
            case "scaling":
                {
                    _ = function() {
                        var A = Vector3.FromArray(c.output, d);
                        return d += 3,
                        A
                    }
                    ;
                    break
                }
            case "influence":
                {
                    _ = function() {
                        for (var A = new Array(l._numMorphTargets), S = 0; S < l._numMorphTargets; S++)
                            A[S] = c.output[d++];
                        return A
                    }
                    ;
                    break
                }
            }
            var g;
            switch (c.interpolation) {
            case "STEP":
                {
                    g = function(A) {
                        return {
                            frame: c.input[A],
                            value: _(),
                            interpolation: AnimationKeyInterpolation.STEP
                        }
                    }
                    ;
                    break
                }
            case "LINEAR":
                {
                    g = function(A) {
                        return {
                            frame: c.input[A],
                            value: _()
                        }
                    }
                    ;
                    break
                }
            case "CUBICSPLINE":
                {
                    g = function(A) {
                        return {
                            frame: c.input[A],
                            inTangent: _(),
                            value: _(),
                            outTangent: _()
                        }
                    }
                    ;
                    break
                }
            }
            for (var m = new Array(c.input.length), v = 0; v < c.input.length; v++)
                m[v] = g(v);
            if (h === "influence")
                for (var y = function(A) {
                    var S = o.name + "_channel" + o.targetedAnimations.length
                      , P = new Animation(S,h,1,f);
                    P.setKeys(m.map(function(R) {
                        return {
                            frame: R.frame,
                            inTangent: R.inTangent ? R.inTangent[A] : void 0,
                            value: R.value[A],
                            outTangent: R.outTangent ? R.outTangent[A] : void 0
                        }
                    })),
                    s._forEachPrimitive(l, function(R) {
                        var M = R
                          , x = M.morphTargetManager.getTarget(A)
                          , I = P.clone();
                        x.animations.push(I),
                        o.addTargetedAnimation(I, x)
                    })
                }, b = 0; b < l._numMorphTargets; b++)
                    y(b);
            else {
                var T = o.name + "_channel" + o.targetedAnimations.length
                  , C = new Animation(T,h,1,f);
                C.setKeys(m),
                a != null && a.animations != null ? (a.animations.push(C),
                o.addTargetedAnimation(C, a)) : (l._babylonTransformNode.animations.push(C),
                o.addTargetedAnimation(C, l._babylonTransformNode))
            }
        })
    }
    ,
    i.prototype._loadAnimationSamplerAsync = function(e, t) {
        if (t._data)
            return t._data;
        var r = t.interpolation || "LINEAR";
        switch (r) {
        case "STEP":
        case "LINEAR":
        case "CUBICSPLINE":
            break;
        default:
            throw new Error(e + "/interpolation: Invalid value (" + t.interpolation + ")")
        }
        var n = ArrayItem.Get(e + "/input", this._gltf.accessors, t.input)
          , o = ArrayItem.Get(e + "/output", this._gltf.accessors, t.output);
        return t._data = Promise.all([this._loadFloatAccessorAsync("/accessors/" + n.index, n), this._loadFloatAccessorAsync("/accessors/" + o.index, o)]).then(function(a) {
            var s = a[0]
              , l = a[1];
            return {
                input: s,
                interpolation: r,
                output: l
            }
        }),
        t._data
    }
    ,
    i.prototype.loadBufferAsync = function(e, t, r, n) {
        var o = this._extensionsLoadBufferAsync(e, t, r, n);
        if (o)
            return o;
        if (!t._data)
            if (t.uri)
                t._data = this.loadUriAsync(e + "/uri", t, t.uri);
            else {
                if (!this._bin)
                    throw new Error(e + ": Uri is missing or the binary glTF is missing its binary chunk");
                t._data = this._bin.readAsync(0, t.byteLength)
            }
        return t._data.then(function(a) {
            try {
                return new Uint8Array(a.buffer,a.byteOffset + r,n)
            } catch (s) {
                throw new Error(e + ": " + s.message)
            }
        })
    }
    ,
    i.prototype.loadBufferViewAsync = function(e, t) {
        var r = this._extensionsLoadBufferViewAsync(e, t);
        if (r)
            return r;
        if (t._data)
            return t._data;
        var n = ArrayItem.Get(e + "/buffer", this._gltf.buffers, t.buffer);
        return t._data = this.loadBufferAsync("/buffers/" + n.index, n, t.byteOffset || 0, t.byteLength),
        t._data
    }
    ,
    i.prototype._loadAccessorAsync = function(e, t, r) {
        var n = this;
        if (t._data)
            return t._data;
        var o = i._GetNumComponents(e, t.type)
          , a = o * VertexBuffer.GetTypeByteLength(t.componentType)
          , s = o * t.count;
        if (t.bufferView == null)
            t._data = Promise.resolve(new r(s));
        else {
            var l = ArrayItem.Get(e + "/bufferView", this._gltf.bufferViews, t.bufferView);
            t._data = this.loadBufferViewAsync("/bufferViews/" + l.index, l).then(function(c) {
                if (t.componentType === 5126 && !t.normalized && (!l.byteStride || l.byteStride === a))
                    return i._GetTypedArray(e, t.componentType, c, t.byteOffset, s);
                var h = new r(s);
                return VertexBuffer.ForEach(c, t.byteOffset || 0, l.byteStride || a, o, t.componentType, h.length, t.normalized || !1, function(f, d) {
                    h[d] = f
                }),
                h
            })
        }
        if (t.sparse) {
            var u = t.sparse;
            t._data = t._data.then(function(c) {
                var h = c
                  , f = ArrayItem.Get(e + "/sparse/indices/bufferView", n._gltf.bufferViews, u.indices.bufferView)
                  , d = ArrayItem.Get(e + "/sparse/values/bufferView", n._gltf.bufferViews, u.values.bufferView);
                return Promise.all([n.loadBufferViewAsync("/bufferViews/" + f.index, f), n.loadBufferViewAsync("/bufferViews/" + d.index, d)]).then(function(_) {
                    var g = _[0], m = _[1], v = i._GetTypedArray(e + "/sparse/indices", u.indices.componentType, g, u.indices.byteOffset, u.count), y = o * u.count, b;
                    if (t.componentType === 5126 && !t.normalized)
                        b = i._GetTypedArray(e + "/sparse/values", t.componentType, m, u.values.byteOffset, y);
                    else {
                        var T = i._GetTypedArray(e + "/sparse/values", t.componentType, m, u.values.byteOffset, y);
                        b = new r(y),
                        VertexBuffer.ForEach(T, 0, a, o, t.componentType, b.length, t.normalized || !1, function(R, M) {
                            b[M] = R
                        })
                    }
                    for (var C = 0, A = 0; A < v.length; A++)
                        for (var S = v[A] * o, P = 0; P < o; P++)
                            h[S++] = b[C++];
                    return h
                })
            })
        }
        return t._data
    }
    ,
    i.prototype._loadFloatAccessorAsync = function(e, t) {
        return this._loadAccessorAsync(e, t, Float32Array)
    }
    ,
    i.prototype._loadIndicesAccessorAsync = function(e, t) {
        if (t.type !== "SCALAR")
            throw new Error(e + "/type: Invalid value " + t.type);
        if (t.componentType !== 5121 && t.componentType !== 5123 && t.componentType !== 5125)
            throw new Error(e + "/componentType: Invalid value " + t.componentType);
        if (t._data)
            return t._data;
        if (t.sparse) {
            var r = i._GetTypedArrayConstructor(e + "/componentType", t.componentType);
            t._data = this._loadAccessorAsync(e, t, r)
        } else {
            var n = ArrayItem.Get(e + "/bufferView", this._gltf.bufferViews, t.bufferView);
            t._data = this.loadBufferViewAsync("/bufferViews/" + n.index, n).then(function(o) {
                return i._GetTypedArray(e, t.componentType, o, t.byteOffset, t.count)
            })
        }
        return t._data
    }
    ,
    i.prototype._loadVertexBufferViewAsync = function(e, t) {
        var r = this;
        return e._babylonBuffer || (e._babylonBuffer = this.loadBufferViewAsync("/bufferViews/" + e.index, e).then(function(n) {
            return new Buffer(r._babylonScene.getEngine(),n,!1)
        })),
        e._babylonBuffer
    }
    ,
    i.prototype._loadVertexAccessorAsync = function(e, t, r) {
        var n = this, o;
        if (!((o = t._babylonVertexBuffer) === null || o === void 0) && o[r])
            return t._babylonVertexBuffer[r];
        if (t._babylonVertexBuffer || (t._babylonVertexBuffer = {}),
        t.sparse)
            t._babylonVertexBuffer[r] = this._loadFloatAccessorAsync(e, t).then(function(s) {
                return new VertexBuffer(n._babylonScene.getEngine(),s,r,!1)
            });
        else if (r === VertexBuffer.MatricesIndicesKind || r === VertexBuffer.MatricesIndicesExtraKind)
            t._babylonVertexBuffer[r] = this._loadFloatAccessorAsync(e, t).then(function(s) {
                return new VertexBuffer(n._babylonScene.getEngine(),s,r,!1)
            });
        else {
            var a = ArrayItem.Get(e + "/bufferView", this._gltf.bufferViews, t.bufferView);
            t._babylonVertexBuffer[r] = this._loadVertexBufferViewAsync(a, r).then(function(s) {
                var l = i._GetNumComponents(e, t.type);
                return new VertexBuffer(n._babylonScene.getEngine(),s,r,!1,!1,a.byteStride,!1,t.byteOffset,l,t.componentType,t.normalized,!0,1,!0)
            })
        }
        return t._babylonVertexBuffer[r]
    }
    ,
    i.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function(e, t, r) {
        if (!(r instanceof PBRMaterial))
            throw new Error(e + ": Material type not supported");
        var n = new Array;
        return t && (t.baseColorFactor ? (r.albedoColor = Color3.FromArray(t.baseColorFactor),
        r.alpha = t.baseColorFactor[3]) : r.albedoColor = Color3.White(),
        r.metallic = t.metallicFactor == null ? 1 : t.metallicFactor,
        r.roughness = t.roughnessFactor == null ? 1 : t.roughnessFactor,
        t.baseColorTexture && n.push(this.loadTextureInfoAsync(e + "/baseColorTexture", t.baseColorTexture, function(o) {
            o.name = r.name + " (Base Color)",
            r.albedoTexture = o
        })),
        t.metallicRoughnessTexture && (t.metallicRoughnessTexture.nonColorData = !0,
        n.push(this.loadTextureInfoAsync(e + "/metallicRoughnessTexture", t.metallicRoughnessTexture, function(o) {
            o.name = r.name + " (Metallic Roughness)",
            r.metallicTexture = o
        })),
        r.useMetallnessFromMetallicTextureBlue = !0,
        r.useRoughnessFromMetallicTextureGreen = !0,
        r.useRoughnessFromMetallicTextureAlpha = !1)),
        Promise.all(n).then(function() {})
    }
    ,
    i.prototype._loadMaterialAsync = function(e, t, r, n, o) {
        o === void 0 && (o = function() {}
        );
        var a = this._extensionsLoadMaterialAsync(e, t, r, n, o);
        if (a)
            return a;
        t._data = t._data || {};
        var s = t._data[n];
        if (!s) {
            this.logOpen(e + " " + (t.name || ""));
            var l = this.createMaterial(e, t, n);
            s = {
                babylonMaterial: l,
                babylonMeshes: [],
                promise: this.loadMaterialPropertiesAsync(e, t, l)
            },
            t._data[n] = s,
            i.AddPointerMetadata(l, e),
            this._parent.onMaterialLoadedObservable.notifyObservers(l),
            this.logClose()
        }
        return r && (s.babylonMeshes.push(r),
        r.onDisposeObservable.addOnce(function() {
            var u = s.babylonMeshes.indexOf(r);
            u !== -1 && s.babylonMeshes.splice(u, 1)
        })),
        o(s.babylonMaterial),
        s.promise.then(function() {
            return s.babylonMaterial
        })
    }
    ,
    i.prototype._createDefaultMaterial = function(e, t) {
        this._babylonScene._blockEntityCollection = !!this._assetContainer;
        var r = new PBRMaterial(e,this._babylonScene);
        return r._parentContainer = this._assetContainer,
        this._babylonScene._blockEntityCollection = !1,
        r.fillMode = t,
        r.enableSpecularAntiAliasing = !0,
        r.useRadianceOverAlpha = !this._parent.transparencyAsCoverage,
        r.useSpecularOverAlpha = !this._parent.transparencyAsCoverage,
        r.transparencyMode = PBRMaterial.PBRMATERIAL_OPAQUE,
        r.metallic = 1,
        r.roughness = 1,
        r
    }
    ,
    i.prototype.createMaterial = function(e, t, r) {
        var n = this._extensionsCreateMaterial(e, t, r);
        if (n)
            return n;
        var o = t.name || "material" + t.index
          , a = this._createDefaultMaterial(o, r);
        return a
    }
    ,
    i.prototype.loadMaterialPropertiesAsync = function(e, t, r) {
        var n = this._extensionsLoadMaterialPropertiesAsync(e, t, r);
        if (n)
            return n;
        var o = new Array;
        return o.push(this.loadMaterialBasePropertiesAsync(e, t, r)),
        t.pbrMetallicRoughness && o.push(this._loadMaterialMetallicRoughnessPropertiesAsync(e + "/pbrMetallicRoughness", t.pbrMetallicRoughness, r)),
        this.loadMaterialAlphaProperties(e, t, r),
        Promise.all(o).then(function() {})
    }
    ,
    i.prototype.loadMaterialBasePropertiesAsync = function(e, t, r) {
        if (!(r instanceof PBRMaterial))
            throw new Error(e + ": Material type not supported");
        var n = new Array;
        return r.emissiveColor = t.emissiveFactor ? Color3.FromArray(t.emissiveFactor) : new Color3(0,0,0),
        t.doubleSided && (r.backFaceCulling = !1,
        r.twoSidedLighting = !0),
        t.normalTexture && (t.normalTexture.nonColorData = !0,
        n.push(this.loadTextureInfoAsync(e + "/normalTexture", t.normalTexture, function(o) {
            o.name = r.name + " (Normal)",
            r.bumpTexture = o
        })),
        r.invertNormalMapX = !this._babylonScene.useRightHandedSystem,
        r.invertNormalMapY = this._babylonScene.useRightHandedSystem,
        t.normalTexture.scale != null && (r.bumpTexture.level = t.normalTexture.scale),
        r.forceIrradianceInFragment = !0),
        t.occlusionTexture && (t.occlusionTexture.nonColorData = !0,
        n.push(this.loadTextureInfoAsync(e + "/occlusionTexture", t.occlusionTexture, function(o) {
            o.name = r.name + " (Occlusion)",
            r.ambientTexture = o
        })),
        r.useAmbientInGrayScale = !0,
        t.occlusionTexture.strength != null && (r.ambientTextureStrength = t.occlusionTexture.strength)),
        t.emissiveTexture && n.push(this.loadTextureInfoAsync(e + "/emissiveTexture", t.emissiveTexture, function(o) {
            o.name = r.name + " (Emissive)",
            r.emissiveTexture = o
        })),
        Promise.all(n).then(function() {})
    }
    ,
    i.prototype.loadMaterialAlphaProperties = function(e, t, r) {
        if (!(r instanceof PBRMaterial))
            throw new Error(e + ": Material type not supported");
        var n = t.alphaMode || "OPAQUE";
        switch (n) {
        case "OPAQUE":
            {
                r.transparencyMode = PBRMaterial.PBRMATERIAL_OPAQUE;
                break
            }
        case "MASK":
            {
                r.transparencyMode = PBRMaterial.PBRMATERIAL_ALPHATEST,
                r.alphaCutOff = t.alphaCutoff == null ? .5 : t.alphaCutoff,
                r.albedoTexture && (r.albedoTexture.hasAlpha = !0);
                break
            }
        case "BLEND":
            {
                r.transparencyMode = PBRMaterial.PBRMATERIAL_ALPHABLEND,
                r.albedoTexture && (r.albedoTexture.hasAlpha = !0,
                r.useAlphaFromAlbedoTexture = !0);
                break
            }
        default:
            throw new Error(e + "/alphaMode: Invalid value (" + t.alphaMode + ")")
        }
    }
    ,
    i.prototype.loadTextureInfoAsync = function(e, t, r) {
        var n = this;
        r === void 0 && (r = function() {}
        );
        var o = this._extensionsLoadTextureInfoAsync(e, t, r);
        if (o)
            return o;
        if (this.logOpen("" + e),
        t.texCoord >= 6)
            throw new Error(e + "/texCoord: Invalid value (" + t.texCoord + ")");
        var a = ArrayItem.Get(e + "/index", this._gltf.textures, t.index);
        a._textureInfo = t;
        var s = this._loadTextureAsync("/textures/" + t.index, a, function(l) {
            l.coordinatesIndex = t.texCoord || 0,
            i.AddPointerMetadata(l, e),
            n._parent.onTextureLoadedObservable.notifyObservers(l),
            r(l)
        });
        return this.logClose(),
        s
    }
    ,
    i.prototype._loadTextureAsync = function(e, t, r) {
        r === void 0 && (r = function() {}
        );
        var n = this._extensionsLoadTextureAsync(e, t, r);
        if (n)
            return n;
        this.logOpen(e + " " + (t.name || ""));
        var o = t.sampler == null ? i.DefaultSampler : ArrayItem.Get(e + "/sampler", this._gltf.samplers, t.sampler)
          , a = ArrayItem.Get(e + "/source", this._gltf.images, t.source)
          , s = this._createTextureAsync(e, o, a, r, void 0, !t._textureInfo.nonColorData);
        return this.logClose(),
        s
    }
    ,
    i.prototype._createTextureAsync = function(e, t, r, n, o, a) {
        var s = this;
        n === void 0 && (n = function() {}
        );
        var l = this._loadSampler("/samplers/" + t.index, t)
          , u = new Array
          , c = new Deferred;
        this._babylonScene._blockEntityCollection = !!this._assetContainer;
        var h = {
            noMipmap: l.noMipMaps,
            invertY: !1,
            samplingMode: l.samplingMode,
            onLoad: function() {
                s._disposed || c.resolve()
            },
            onError: function(d, _) {
                s._disposed || c.reject(new Error(e + ": " + (_ && _.message ? _.message : d || "Failed to load texture")))
            },
            loaderOptions: o,
            useSRGBBuffer: !!a && this._parent.useSRGBBuffers
        }
          , f = new Texture(null,this._babylonScene,h);
        return f._parentContainer = this._assetContainer,
        this._babylonScene._blockEntityCollection = !1,
        u.push(c.promise),
        u.push(this.loadImageAsync("/images/" + r.index, r).then(function(d) {
            var _ = r.uri || s._fileName + "#image" + r.index
              , g = "data:" + s._uniqueRootUrl + _;
            f.updateURL(g, d)
        })),
        f.wrapU = l.wrapU,
        f.wrapV = l.wrapV,
        n(f),
        Promise.all(u).then(function() {
            return f
        })
    }
    ,
    i.prototype._loadSampler = function(e, t) {
        return t._data || (t._data = {
            noMipMaps: t.minFilter === 9728 || t.minFilter === 9729,
            samplingMode: i._GetTextureSamplingMode(e, t),
            wrapU: i._GetTextureWrapMode(e + "/wrapS", t.wrapS),
            wrapV: i._GetTextureWrapMode(e + "/wrapT", t.wrapT)
        }),
        t._data
    }
    ,
    i.prototype.loadImageAsync = function(e, t) {
        if (!t._data) {
            if (this.logOpen(e + " " + (t.name || "")),
            t.uri) {
                var r = this._babylonScene.getEngine().textureFormatInUse
                  , n = t.uri
                  , o = ""
                  , a = n.lastIndexOf(".png");
                r && a >= 0 && (n = n.substring(0, a),
                n = n + r,
                o = t.uri),
                t._data = this.loadUriAsync(e + "/uri", t, n, o)
            } else {
                var s = ArrayItem.Get(e + "/bufferView", this._gltf.bufferViews, t.bufferView);
                t._data = this.loadBufferViewAsync("/bufferViews/" + s.index, s)
            }
            this.logClose()
        }
        return t._data
    }
    ,
    i.prototype.loadUriAsync = function(e, t, r, n) {
        var o = this
          , a = this._extensionsLoadUriAsync(e, t, r);
        if (a)
            return a;
        if (!i._ValidateUri(r))
            throw new Error(e + ": '" + r + "' is invalid");
        if (IsBase64DataUrl(r)) {
            var s = new Uint8Array(DecodeBase64UrlToBinary(r));
            return this.log(e + ": Decoded " + r.substr(0, 64) + "... (" + s.length + " bytes)"),
            Promise.resolve(s)
        }
        return this.log(e + ": Loading " + r),
        this._parent.preprocessUrlAsync(this._rootUrl + r).then(function(l) {
            return new Promise(function(u, c) {
                o._parent._loadFile(o._babylonScene, l, function(h) {
                    o._disposed || (o.log(e + ": Loaded " + r + " (" + h.byteLength + " bytes)"),
                    t.uri && (t.uri = r),
                    u(new Uint8Array(h)))
                }, !0, function(h) {
                    n ? u(o.loadUriAsync(e, t, n)) : c(new LoadFileError(e + ": Failed to load '" + r + "'" + (h ? ": " + h.status + " " + h.statusText : ""),h))
                })
            }
            )
        })
    }
    ,
    i.AddPointerMetadata = function(e, t) {
        var r = e.metadata = e.metadata || {}
          , n = r.gltf = r.gltf || {}
          , o = n.pointers = n.pointers || [];
        o.push(t)
    }
    ,
    i._GetTextureWrapMode = function(e, t) {
        switch (t = t == null ? 10497 : t,
        t) {
        case 33071:
            return Texture.CLAMP_ADDRESSMODE;
        case 33648:
            return Texture.MIRROR_ADDRESSMODE;
        case 10497:
            return Texture.WRAP_ADDRESSMODE;
        default:
            return Logger$2.Warn(e + ": Invalid value (" + t + ")"),
            Texture.WRAP_ADDRESSMODE
        }
    }
    ,
    i._GetTextureSamplingMode = function(e, t) {
        var r = t.magFilter == null ? 9729 : t.magFilter
          , n = t.minFilter == null ? 9987 : t.minFilter;
        if (r === 9729)
            switch (n) {
            case 9728:
                return Texture.LINEAR_NEAREST;
            case 9729:
                return Texture.LINEAR_LINEAR;
            case 9984:
                return Texture.LINEAR_NEAREST_MIPNEAREST;
            case 9985:
                return Texture.LINEAR_LINEAR_MIPNEAREST;
            case 9986:
                return Texture.LINEAR_NEAREST_MIPLINEAR;
            case 9987:
                return Texture.LINEAR_LINEAR_MIPLINEAR;
            default:
                return Logger$2.Warn(e + "/minFilter: Invalid value (" + n + ")"),
                Texture.LINEAR_LINEAR_MIPLINEAR
            }
        else
            switch (r !== 9728 && Logger$2.Warn(e + "/magFilter: Invalid value (" + r + ")"),
            n) {
            case 9728:
                return Texture.NEAREST_NEAREST;
            case 9729:
                return Texture.NEAREST_LINEAR;
            case 9984:
                return Texture.NEAREST_NEAREST_MIPNEAREST;
            case 9985:
                return Texture.NEAREST_LINEAR_MIPNEAREST;
            case 9986:
                return Texture.NEAREST_NEAREST_MIPLINEAR;
            case 9987:
                return Texture.NEAREST_LINEAR_MIPLINEAR;
            default:
                return Logger$2.Warn(e + "/minFilter: Invalid value (" + n + ")"),
                Texture.NEAREST_NEAREST_MIPNEAREST
            }
    }
    ,
    i._GetTypedArrayConstructor = function(e, t) {
        switch (t) {
        case 5120:
            return Int8Array;
        case 5121:
            return Uint8Array;
        case 5122:
            return Int16Array;
        case 5123:
            return Uint16Array;
        case 5125:
            return Uint32Array;
        case 5126:
            return Float32Array;
        default:
            throw new Error(e + ": Invalid component type " + t)
        }
    }
    ,
    i._GetTypedArray = function(e, t, r, n, o) {
        var a = r.buffer;
        n = r.byteOffset + (n || 0);
        var s = i._GetTypedArrayConstructor(e + "/componentType", t)
          , l = VertexBuffer.GetTypeByteLength(t);
        return n % l !== 0 ? (Logger$2.Warn(e + ": Copying buffer as byte offset (" + n + ") is not a multiple of component type byte length (" + l + ")"),
        new s(a.slice(n, n + o * l),0)) : new s(a,n,o)
    }
    ,
    i._GetNumComponents = function(e, t) {
        switch (t) {
        case "SCALAR":
            return 1;
        case "VEC2":
            return 2;
        case "VEC3":
            return 3;
        case "VEC4":
            return 4;
        case "MAT2":
            return 4;
        case "MAT3":
            return 9;
        case "MAT4":
            return 16
        }
        throw new Error(e + ": Invalid type (" + t + ")")
    }
    ,
    i._ValidateUri = function(e) {
        return Tools.IsBase64(e) || e.indexOf("..") === -1
    }
    ,
    i._GetDrawMode = function(e, t) {
        switch (t == null && (t = 4),
        t) {
        case 0:
            return Material.PointListDrawMode;
        case 1:
            return Material.LineListDrawMode;
        case 2:
            return Material.LineLoopDrawMode;
        case 3:
            return Material.LineStripDrawMode;
        case 4:
            return Material.TriangleFillMode;
        case 5:
            return Material.TriangleStripDrawMode;
        case 6:
            return Material.TriangleFanDrawMode
        }
        throw new Error(e + ": Invalid mesh primitive mode (" + t + ")")
    }
    ,
    i.prototype._compileMaterialsAsync = function() {
        var e = this;
        this._parent._startPerformanceCounter("Compile materials");
        var t = new Array;
        if (this._gltf.materials)
            for (var r = 0, n = this._gltf.materials; r < n.length; r++) {
                var o = n[r];
                if (o._data)
                    for (var a in o._data)
                        for (var s = o._data[a], l = 0, u = s.babylonMeshes; l < u.length; l++) {
                            var c = u[l];
                            c.computeWorldMatrix(!0);
                            var h = s.babylonMaterial;
                            t.push(h.forceCompilationAsync(c)),
                            t.push(h.forceCompilationAsync(c, {
                                useInstances: !0
                            })),
                            this._parent.useClipPlane && (t.push(h.forceCompilationAsync(c, {
                                clipPlane: !0
                            })),
                            t.push(h.forceCompilationAsync(c, {
                                clipPlane: !0,
                                useInstances: !0
                            })))
                        }
            }
        return Promise.all(t).then(function() {
            e._parent._endPerformanceCounter("Compile materials")
        })
    }
    ,
    i.prototype._compileShadowGeneratorsAsync = function() {
        var e = this;
        this._parent._startPerformanceCounter("Compile shadow generators");
        for (var t = new Array, r = this._babylonScene.lights, n = 0, o = r; n < o.length; n++) {
            var a = o[n]
              , s = a.getShadowGenerator();
            s && t.push(s.forceCompilationAsync())
        }
        return Promise.all(t).then(function() {
            e._parent._endPerformanceCounter("Compile shadow generators")
        })
    }
    ,
    i.prototype._forEachExtensions = function(e) {
        for (var t = 0, r = this._extensions; t < r.length; t++) {
            var n = r[t];
            n.enabled && e(n)
        }
    }
    ,
    i.prototype._applyExtensions = function(e, t, r) {
        for (var n = 0, o = this._extensions; n < o.length; n++) {
            var a = o[n];
            if (a.enabled) {
                var s = a.name + "." + t
                  , l = e;
                l._activeLoaderExtensionFunctions = l._activeLoaderExtensionFunctions || {};
                var u = l._activeLoaderExtensionFunctions;
                if (!u[s]) {
                    u[s] = !0;
                    try {
                        var c = r(a);
                        if (c)
                            return c
                    } finally {
                        delete u[s]
                    }
                }
            }
        }
        return null
    }
    ,
    i.prototype._extensionsOnLoading = function() {
        this._forEachExtensions(function(e) {
            return e.onLoading && e.onLoading()
        })
    }
    ,
    i.prototype._extensionsOnReady = function() {
        this._forEachExtensions(function(e) {
            return e.onReady && e.onReady()
        })
    }
    ,
    i.prototype._extensionsLoadSceneAsync = function(e, t) {
        return this._applyExtensions(t, "loadScene", function(r) {
            return r.loadSceneAsync && r.loadSceneAsync(e, t)
        })
    }
    ,
    i.prototype._extensionsLoadNodeAsync = function(e, t, r) {
        return this._applyExtensions(t, "loadNode", function(n) {
            return n.loadNodeAsync && n.loadNodeAsync(e, t, r)
        })
    }
    ,
    i.prototype._extensionsLoadCameraAsync = function(e, t, r) {
        return this._applyExtensions(t, "loadCamera", function(n) {
            return n.loadCameraAsync && n.loadCameraAsync(e, t, r)
        })
    }
    ,
    i.prototype._extensionsLoadVertexDataAsync = function(e, t, r) {
        return this._applyExtensions(t, "loadVertexData", function(n) {
            return n._loadVertexDataAsync && n._loadVertexDataAsync(e, t, r)
        })
    }
    ,
    i.prototype._extensionsLoadMeshPrimitiveAsync = function(e, t, r, n, o, a) {
        return this._applyExtensions(o, "loadMeshPrimitive", function(s) {
            return s._loadMeshPrimitiveAsync && s._loadMeshPrimitiveAsync(e, t, r, n, o, a)
        })
    }
    ,
    i.prototype._extensionsLoadMaterialAsync = function(e, t, r, n, o) {
        return this._applyExtensions(t, "loadMaterial", function(a) {
            return a._loadMaterialAsync && a._loadMaterialAsync(e, t, r, n, o)
        })
    }
    ,
    i.prototype._extensionsCreateMaterial = function(e, t, r) {
        return this._applyExtensions(t, "createMaterial", function(n) {
            return n.createMaterial && n.createMaterial(e, t, r)
        })
    }
    ,
    i.prototype._extensionsLoadMaterialPropertiesAsync = function(e, t, r) {
        return this._applyExtensions(t, "loadMaterialProperties", function(n) {
            return n.loadMaterialPropertiesAsync && n.loadMaterialPropertiesAsync(e, t, r)
        })
    }
    ,
    i.prototype._extensionsLoadTextureInfoAsync = function(e, t, r) {
        return this._applyExtensions(t, "loadTextureInfo", function(n) {
            return n.loadTextureInfoAsync && n.loadTextureInfoAsync(e, t, r)
        })
    }
    ,
    i.prototype._extensionsLoadTextureAsync = function(e, t, r) {
        return this._applyExtensions(t, "loadTexture", function(n) {
            return n._loadTextureAsync && n._loadTextureAsync(e, t, r)
        })
    }
    ,
    i.prototype._extensionsLoadAnimationAsync = function(e, t) {
        return this._applyExtensions(t, "loadAnimation", function(r) {
            return r.loadAnimationAsync && r.loadAnimationAsync(e, t)
        })
    }
    ,
    i.prototype._extensionsLoadSkinAsync = function(e, t, r) {
        return this._applyExtensions(r, "loadSkin", function(n) {
            return n._loadSkinAsync && n._loadSkinAsync(e, t, r)
        })
    }
    ,
    i.prototype._extensionsLoadUriAsync = function(e, t, r) {
        return this._applyExtensions(t, "loadUri", function(n) {
            return n._loadUriAsync && n._loadUriAsync(e, t, r)
        })
    }
    ,
    i.prototype._extensionsLoadBufferViewAsync = function(e, t) {
        return this._applyExtensions(t, "loadBufferView", function(r) {
            return r.loadBufferViewAsync && r.loadBufferViewAsync(e, t)
        })
    }
    ,
    i.prototype._extensionsLoadBufferAsync = function(e, t, r, n) {
        return this._applyExtensions(t, "loadBuffer", function(o) {
            return o.loadBufferAsync && o.loadBufferAsync(e, t, r, n)
        })
    }
    ,
    i.LoadExtensionAsync = function(e, t, r, n) {
        if (!t.extensions)
            return null;
        var o = t.extensions
          , a = o[r];
        return a ? n(e + "/extensions/" + r, a) : null
    }
    ,
    i.LoadExtraAsync = function(e, t, r, n) {
        if (!t.extras)
            return null;
        var o = t.extras
          , a = o[r];
        return a ? n(e + "/extras/" + r, a) : null
    }
    ,
    i.prototype.isExtensionUsed = function(e) {
        return !!this._gltf.extensionsUsed && this._gltf.extensionsUsed.indexOf(e) !== -1
    }
    ,
    i.prototype.logOpen = function(e) {
        this._parent._logOpen(e)
    }
    ,
    i.prototype.logClose = function() {
        this._parent._logClose()
    }
    ,
    i.prototype.log = function(e) {
        this._parent._log(e)
    }
    ,
    i.prototype.startPerformanceCounter = function(e) {
        this._parent._startPerformanceCounter(e)
    }
    ,
    i.prototype.endPerformanceCounter = function(e) {
        this._parent._endPerformanceCounter(e)
    }
    ,
    i._RegisteredExtensions = {},
    i.DefaultSampler = {
        index: -1
    },
    i
}();
GLTFFileLoader._CreateGLTF2Loader = function(i) {
    return new GLTFLoader(i)
}
;
var name$u = "rgbdEncodePixelShader"
  , shader$u = `
varying vec2 vUV;
uniform sampler2D textureSampler;
#include<helperFunctions>
void main(void)
{
gl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);
}`;
ShaderStore.ShadersStore[name$u] = shader$u;
var defaultEnvironmentTextureImageType = "image/png"
  , currentVersion = 2
  , _MagicBytes = [134, 22, 135, 150, 246, 214, 150, 54];
function GetEnvInfo(i) {
    for (var e = new DataView(i.buffer,i.byteOffset,i.byteLength), t = 0, r = 0; r < _MagicBytes.length; r++)
        if (e.getUint8(t++) !== _MagicBytes[r])
            return Logger$2.Error("Not a babylon environment map"),
            null;
    for (var n = "", o = 0; o = e.getUint8(t++); )
        n += String.fromCharCode(o);
    var a = JSON.parse(n);
    return a = normalizeEnvInfo(a),
    a.specular && (a.specular.specularDataPosition = t,
    a.specular.lodGenerationScale = a.specular.lodGenerationScale || .8),
    a
}
function normalizeEnvInfo(i) {
    if (i.version > currentVersion)
        throw new Error('Unsupported babylon environment map version "' + i.version + '". Latest supported version is "' + currentVersion + '".');
    return i.version === 2 || (i = __assign(__assign({}, i), {
        version: 2,
        imageType: defaultEnvironmentTextureImageType
    })),
    i
}
function CreateImageDataArrayBufferViews(i, e) {
    e = normalizeEnvInfo(e);
    var t = e.specular
      , r = Scalar.Log2(e.width);
    if (r = Math.round(r) + 1,
    t.mipmaps.length !== 6 * r)
        throw new Error('Unsupported specular mipmaps number "' + t.mipmaps.length + '"');
    for (var n = new Array(r), o = 0; o < r; o++) {
        n[o] = new Array(6);
        for (var a = 0; a < 6; a++) {
            var s = t.mipmaps[o * 6 + a];
            n[o][a] = new Uint8Array(i.buffer,i.byteOffset + t.specularDataPosition + s.position,s.length)
        }
    }
    return n
}
function UploadEnvLevelsAsync(i, e, t) {
    t = normalizeEnvInfo(t);
    var r = t.specular;
    if (!r)
        return Promise.resolve();
    i._lodGenerationScale = r.lodGenerationScale;
    var n = CreateImageDataArrayBufferViews(e, t);
    return UploadLevelsAsync(i, n, t.imageType)
}
function _OnImageReadyAsync(i, e, t, r, n, o, a, s, l, u, c) {
    return new Promise(function(h, f) {
        if (t) {
            var d = e.createTexture(null, !0, !0, null, 1, null, function(g) {
                f(g)
            }, i);
            r.getEffect().executeWhenCompiled(function() {
                r.externalTextureSamplerBinding = !0,
                r.onApply = function(g) {
                    g._bindTexture("textureSampler", d),
                    g.setFloat2("scale", 1, e._features.needsInvertingBitmap && i instanceof ImageBitmap ? -1 : 1)
                }
                ,
                e.scenes.length && (e.scenes[0].postProcessManager.directRender([r], u, !0, o, a),
                e.restoreDefaultFramebuffer(),
                d.dispose(),
                URL.revokeObjectURL(n),
                h())
            })
        } else {
            if (e._uploadImageToTexture(c, i, o, a),
            s) {
                var _ = l[a];
                _ && e._uploadImageToTexture(_._texture, i, o, 0)
            }
            h()
        }
    }
    )
}
function UploadLevelsAsync(i, e, t) {
    if (t === void 0 && (t = defaultEnvironmentTextureImageType),
    !Tools.IsExponentOfTwo(i.width))
        throw new Error("Texture size must be a power of two");
    var r = Scalar.ILog2(i.width) + 1
      , n = i.getEngine()
      , o = !1
      , a = !1
      , s = null
      , l = null
      , u = null
      , c = n.getCaps();
    if (i.format = 5,
    i.type = 0,
    i.generateMipMaps = !0,
    i._cachedAnisotropicFilteringLevel = null,
    n.updateTextureSamplingMode(3, i),
    c.textureLOD ? n._features.supportRenderAndCopyToLodForFloatTextures ? c.textureHalfFloatRender && c.textureHalfFloatLinearFiltering ? (o = !0,
    i.type = 2) : c.textureFloatRender && c.textureFloatLinearFiltering && (o = !0,
    i.type = 1) : o = !1 : (o = !1,
    a = !0,
    u = {}),
    o)
        s = new PostProcess("rgbdDecode","rgbdDecode",null,null,1,null,3,n,!1,void 0,i.type,void 0,null,!1),
        i._isRGBD = !1,
        i.invertY = !1,
        l = n.createRenderTargetCubeTexture(i.width, {
            generateDepthBuffer: !1,
            generateMipMaps: !0,
            generateStencilBuffer: !1,
            samplingMode: 3,
            type: i.type,
            format: 5
        });
    else if (i._isRGBD = !0,
    i.invertY = !0,
    a)
        for (var h = 3, f = i._lodGenerationScale, d = i._lodGenerationOffset, _ = 0; _ < h; _++) {
            var g = _ / (h - 1)
              , m = 1 - g
              , v = d
              , y = (r - 1) * f + d
              , b = v + (y - v) * m
              , T = Math.round(Math.min(Math.max(b, 0), y))
              , C = new InternalTexture(n,InternalTextureSource.Temp);
            C.isCube = !0,
            C.invertY = !0,
            C.generateMipMaps = !1,
            n.updateTextureSamplingMode(2, C);
            var A = new BaseTexture(null);
            switch (A.isCube = !0,
            A._texture = C,
            u[T] = A,
            _) {
            case 0:
                i._lodTextureLow = A;
                break;
            case 1:
                i._lodTextureMid = A;
                break;
            case 2:
                i._lodTextureHigh = A;
                break
            }
        }
    for (var S = [], P = function(w) {
        for (var O = function(F) {
            var V = e[w][F]
              , N = new Blob([V],{
                type: t
            })
              , L = URL.createObjectURL(N)
              , k = void 0;
            if (typeof Image == "undefined" || n._features.forceBitmapOverHTMLImageElement)
                k = n.createImageBitmap(N, {
                    premultiplyAlpha: "none"
                }).then(function(z) {
                    return _OnImageReadyAsync(z, n, o, s, L, F, w, a, u, l, i)
                });
            else {
                var U = new Image;
                U.src = L,
                k = new Promise(function(z, H) {
                    U.onload = function() {
                        _OnImageReadyAsync(U, n, o, s, L, F, w, a, u, l, i).then(function() {
                            return z()
                        }).catch(function(G) {
                            H(G)
                        })
                    }
                    ,
                    U.onerror = function(G) {
                        H(G)
                    }
                }
                )
            }
            S.push(k)
        }, D = 0; D < 6; D++)
            O(D)
    }, _ = 0; _ < e.length; _++)
        P(_);
    if (e.length < r) {
        var R = void 0
          , M = Math.pow(2, r - 1 - e.length)
          , x = M * M * 4;
        switch (i.type) {
        case 0:
            {
                R = new Uint8Array(x);
                break
            }
        case 2:
            {
                R = new Uint16Array(x);
                break
            }
        case 1:
            {
                R = new Float32Array(x);
                break
            }
        }
        for (var _ = e.length; _ < r; _++)
            for (var I = 0; I < 6; I++)
                n._uploadArrayBufferViewToTexture(i, R, I, _)
    }
    return Promise.all(S).then(function() {
        l && (n._releaseTexture(i),
        l._swapAndDie(i)),
        s && s.dispose(),
        a && (i._lodTextureHigh && i._lodTextureHigh._texture && (i._lodTextureHigh._texture.isReady = !0),
        i._lodTextureMid && i._lodTextureMid._texture && (i._lodTextureMid._texture.isReady = !0),
        i._lodTextureLow && i._lodTextureLow._texture && (i._lodTextureLow._texture.isReady = !0))
    })
}
function UploadEnvSpherical(i, e) {
    e = normalizeEnvInfo(e);
    var t = e.irradiance;
    if (!!t) {
        var r = new SphericalPolynomial;
        Vector3.FromArrayToRef(t.x, 0, r.x),
        Vector3.FromArrayToRef(t.y, 0, r.y),
        Vector3.FromArrayToRef(t.z, 0, r.z),
        Vector3.FromArrayToRef(t.xx, 0, r.xx),
        Vector3.FromArrayToRef(t.yy, 0, r.yy),
        Vector3.FromArrayToRef(t.zz, 0, r.zz),
        Vector3.FromArrayToRef(t.yz, 0, r.yz),
        Vector3.FromArrayToRef(t.zx, 0, r.zx),
        Vector3.FromArrayToRef(t.xy, 0, r.xy),
        i._sphericalPolynomial = r
    }
}
function _UpdateRGBDAsync(i, e, t, r, n) {
    var o = i.getEngine().createRawCubeTexture(null, i.width, i.format, i.type, i.generateMipMaps, i.invertY, i.samplingMode, i._compression)
      , a = UploadLevelsAsync(o, e).then(function() {
        return i
    });
    return i.onRebuildCallback = function(s) {
        return {
            proxy: a,
            isReady: !0,
            isAsync: !0
        }
    }
    ,
    i._source = InternalTextureSource.CubeRawRGBD,
    i._bufferViewArrayArray = e,
    i._lodGenerationScale = r,
    i._lodGenerationOffset = n,
    i._sphericalPolynomial = t,
    UploadLevelsAsync(i, e).then(function() {
        return i.isReady = !0,
        i
    })
}
var RawCubeTexture = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a, s, l, u, c) {
        o === void 0 && (o = 5),
        a === void 0 && (a = 0),
        s === void 0 && (s = !1),
        l === void 0 && (l = !1),
        u === void 0 && (u = 3),
        c === void 0 && (c = null);
        var h = i.call(this, "", t) || this;
        return h._texture = t.getEngine().createRawCubeTexture(r, n, o, a, s, l, u, c),
        h
    }
    return e.prototype.update = function(t, r, n, o, a) {
        a === void 0 && (a = null),
        this._texture.getEngine().updateRawCubeTexture(this._texture, t, r, n, o, a)
    }
    ,
    e.prototype.updateRGBDAsync = function(t, r, n, o) {
        return r === void 0 && (r = null),
        n === void 0 && (n = .8),
        o === void 0 && (o = 0),
        _UpdateRGBDAsync(this._texture, t, r, n, o).then(function() {})
    }
    ,
    e.prototype.clone = function() {
        var t = this;
        return SerializationHelper.Clone(function() {
            var r = t.getScene()
              , n = t._texture
              , o = new e(r,n._bufferViewArray,n.width,n.format,n.type,n.generateMipMaps,n.invertY,n.samplingMode,n._compression);
            return n.source === InternalTextureSource.CubeRawRGBD && o.updateRGBDAsync(n._bufferViewArrayArray, n._sphericalPolynomial, n._lodGenerationScale, n._lodGenerationOffset),
            o
        }, this)
    }
    ,
    e
}(CubeTexture)
  , NAME$p = "EXT_lights_image_based"
  , EXT_lights_image_based = function() {
    function i(e) {
        this.name = NAME$p,
        this._loader = e,
        this.enabled = this._loader.isExtensionUsed(NAME$p)
    }
    return i.prototype.dispose = function() {
        this._loader = null,
        delete this._lights
    }
    ,
    i.prototype.onLoading = function() {
        var e = this._loader.gltf.extensions;
        if (e && e[this.name]) {
            var t = e[this.name];
            this._lights = t.lights
        }
    }
    ,
    i.prototype.loadSceneAsync = function(e, t) {
        var r = this;
        return GLTFLoader.LoadExtensionAsync(e, t, this.name, function(n, o) {
            var a = new Array;
            a.push(r._loader.loadSceneAsync(e, t)),
            r._loader.logOpen("" + n);
            var s = ArrayItem.Get(n + "/light", r._lights, o.light);
            return a.push(r._loadLightAsync("/extensions/" + r.name + "/lights/" + o.light, s).then(function(l) {
                r._loader.babylonScene.environmentTexture = l
            })),
            r._loader.logClose(),
            Promise.all(a).then(function() {})
        })
    }
    ,
    i.prototype._loadLightAsync = function(e, t) {
        var r = this;
        if (!t._loaded) {
            var n = new Array;
            this._loader.logOpen("" + e);
            for (var o = new Array(t.specularImages.length), a = function(u) {
                var c = t.specularImages[u];
                o[u] = new Array(c.length);
                for (var h = function(d) {
                    var _ = e + "/specularImages/" + u + "/" + d;
                    s._loader.logOpen("" + _);
                    var g = c[d]
                      , m = ArrayItem.Get(_, s._loader.gltf.images, g);
                    n.push(s._loader.loadImageAsync("/images/" + g, m).then(function(v) {
                        o[u][d] = v
                    })),
                    s._loader.logClose()
                }, f = 0; f < c.length; f++)
                    h(f)
            }, s = this, l = 0; l < t.specularImages.length; l++)
                a(l);
            this._loader.logClose(),
            t._loaded = Promise.all(n).then(function() {
                var u = new RawCubeTexture(r._loader.babylonScene,null,t.specularImageSize);
                if (u.name = t.name || "environment",
                t._babylonTexture = u,
                t.intensity != null && (u.level = t.intensity),
                t.rotation) {
                    var c = Quaternion.FromArray(t.rotation);
                    r._loader.babylonScene.useRightHandedSystem || (c = Quaternion.Inverse(c)),
                    Matrix.FromQuaternionToRef(c, u.getReflectionTextureMatrix())
                }
                if (!t.irradianceCoefficients)
                    throw new Error(e + ": Irradiance coefficients are missing");
                var h = SphericalHarmonics.FromArray(t.irradianceCoefficients);
                h.scaleInPlace(t.intensity),
                h.convertIrradianceToLambertianRadiance();
                var f = SphericalPolynomial.FromHarmonics(h)
                  , d = (o.length - 1) / Scalar.Log2(t.specularImageSize);
                return u.updateRGBDAsync(o, f, d)
            })
        }
        return t._loaded.then(function() {
            return t._babylonTexture
        })
    }
    ,
    i
}();
GLTFLoader.RegisterExtension(NAME$p, function(i) {
    return new EXT_lights_image_based(i)
});
var NAME$o = "EXT_mesh_gpu_instancing"
  , EXT_mesh_gpu_instancing = function() {
    function i(e) {
        this.name = NAME$o,
        this._loader = e,
        this.enabled = this._loader.isExtensionUsed(NAME$o)
    }
    return i.prototype.dispose = function() {
        this._loader = null
    }
    ,
    i.prototype.loadNodeAsync = function(e, t, r) {
        var n = this;
        return GLTFLoader.LoadExtensionAsync(e, t, this.name, function(o, a) {
            n._loader._disableInstancedMesh++;
            var s = n._loader.loadNodeAsync("/nodes/" + t.index, t, r);
            if (n._loader._disableInstancedMesh--,
            !t._primitiveBabylonMeshes)
                return s;
            var l = new Array
              , u = 0
              , c = function(h) {
                if (a.attributes[h] == null) {
                    l.push(Promise.resolve(null));
                    return
                }
                var f = ArrayItem.Get(o + "/attributes/" + h, n._loader.gltf.accessors, a.attributes[h]);
                if (l.push(n._loader._loadFloatAccessorAsync("/accessors/" + f.bufferView, f)),
                u === 0)
                    u = f.count;
                else if (u !== f.count)
                    throw new Error(o + "/attributes: Instance buffer accessors do not have the same count.")
            };
            return c("TRANSLATION"),
            c("ROTATION"),
            c("SCALE"),
            s.then(function(h) {
                return Promise.all(l).then(function(f) {
                    var d = f[0]
                      , _ = f[1]
                      , g = f[2]
                      , m = new Float32Array(u * 16);
                    TmpVectors.Vector3[0].copyFromFloats(0, 0, 0),
                    TmpVectors.Quaternion[0].copyFromFloats(0, 0, 0, 1),
                    TmpVectors.Vector3[1].copyFromFloats(1, 1, 1);
                    for (var v = 0; v < u; ++v)
                        d && Vector3.FromArrayToRef(d, v * 3, TmpVectors.Vector3[0]),
                        _ && Quaternion.FromArrayToRef(_, v * 4, TmpVectors.Quaternion[0]),
                        g && Vector3.FromArrayToRef(g, v * 3, TmpVectors.Vector3[1]),
                        Matrix.ComposeToRef(TmpVectors.Vector3[1], TmpVectors.Quaternion[0], TmpVectors.Vector3[0], TmpVectors.Matrix[0]),
                        TmpVectors.Matrix[0].copyToArray(m, v * 16);
                    for (var y = 0, b = t._primitiveBabylonMeshes; y < b.length; y++) {
                        var T = b[y];
                        T.thinInstanceSetBuffer("matrix", m, 16, !0)
                    }
                    return h
                })
            })
        })
    }
    ,
    i
}();
GLTFLoader.RegisterExtension(NAME$o, function(i) {
    return new EXT_mesh_gpu_instancing(i)
});
var MeshoptCompression = function() {
    function i() {
        var e = i.Configuration.decoder;
        this._decoderModulePromise = Tools.LoadScriptAsync(Tools.GetAbsoluteUrl(e.url)).then(function() {
            return MeshoptDecoder.ready
        })
    }
    return Object.defineProperty(i, "Default", {
        get: function() {
            return i._Default || (i._Default = new i),
            i._Default
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.dispose = function() {
        delete this._decoderModulePromise
    }
    ,
    i.prototype.decodeGltfBufferAsync = function(e, t, r, n, o) {
        return this._decoderModulePromise.then(function() {
            var a = new Uint8Array(t * r);
            return MeshoptDecoder.decodeGltfBuffer(a, t, r, e, n, o),
            a
        })
    }
    ,
    i.Configuration = {
        decoder: {
            url: "https://preview.babylonjs.com/meshopt_decoder.js"
        }
    },
    i._Default = null,
    i
}()
  , NAME$n = "EXT_meshopt_compression"
  , EXT_meshopt_compression = function() {
    function i(e) {
        this.name = NAME$n,
        this.enabled = e.isExtensionUsed(NAME$n),
        this._loader = e
    }
    return i.prototype.dispose = function() {
        this._loader = null
    }
    ,
    i.prototype.loadBufferViewAsync = function(e, t) {
        var r = this;
        return GLTFLoader.LoadExtensionAsync(e, t, this.name, function(n, o) {
            var a = t;
            if (a._meshOptData)
                return a._meshOptData;
            var s = ArrayItem.Get(e + "/buffer", r._loader.gltf.buffers, o.buffer);
            return a._meshOptData = r._loader.loadBufferAsync("/buffers/" + s.index, s, o.byteOffset || 0, o.byteLength).then(function(l) {
                return MeshoptCompression.Default.decodeGltfBufferAsync(l, o.count, o.byteStride, o.mode, o.filter)
            }),
            a._meshOptData
        })
    }
    ,
    i
}();
GLTFLoader.RegisterExtension(NAME$n, function(i) {
    return new EXT_meshopt_compression(i)
});
var NAME$m = "EXT_texture_webp"
  , EXT_texture_webp = function() {
    function i(e) {
        this.name = NAME$m,
        this._loader = e,
        this.enabled = e.isExtensionUsed(NAME$m)
    }
    return i.prototype.dispose = function() {
        this._loader = null
    }
    ,
    i.prototype._loadTextureAsync = function(e, t, r) {
        var n = this;
        return GLTFLoader.LoadExtensionAsync(e, t, this.name, function(o, a) {
            var s = t.sampler == null ? GLTFLoader.DefaultSampler : ArrayItem.Get(e + "/sampler", n._loader.gltf.samplers, t.sampler)
              , l = ArrayItem.Get(o + "/source", n._loader.gltf.images, a.source);
            return n._loader._createTextureAsync(e, s, l, function(u) {
                r(u)
            }, void 0, !t._textureInfo.nonColorData)
        })
    }
    ,
    i
}();
GLTFLoader.RegisterExtension(NAME$m, function(i) {
    return new EXT_texture_webp(i)
});
var WorkerPool = function() {
    function i(e) {
        this._pendingActions = new Array,
        this._workerInfos = e.map(function(t) {
            return {
                worker: t,
                active: !1
            }
        })
    }
    return i.prototype.dispose = function() {
        for (var e = 0, t = this._workerInfos; e < t.length; e++) {
            var r = t[e];
            r.worker.terminate()
        }
        this._workerInfos = [],
        this._pendingActions = []
    }
    ,
    i.prototype.push = function(e) {
        for (var t = 0, r = this._workerInfos; t < r.length; t++) {
            var n = r[t];
            if (!n.active) {
                this._execute(n, e);
                return
            }
        }
        this._pendingActions.push(e)
    }
    ,
    i.prototype._execute = function(e, t) {
        var r = this;
        e.active = !0,
        t(e.worker, function() {
            e.active = !1;
            var n = r._pendingActions.shift();
            n && r._execute(e, n)
        })
    }
    ,
    i
}();
function createDecoderAsync(i) {
    return new Promise(function(e) {
        DracoDecoderModule({
            wasmBinary: i
        }).then(function(t) {
            e({
                module: t
            })
        })
    }
    )
}
function decodeMesh(i, e, t, r, n) {
    var o = new i.DecoderBuffer;
    o.Init(e, e.byteLength);
    var a = new i.Decoder, s, l;
    try {
        var u = a.GetEncodedGeometryType(o);
        switch (u) {
        case i.TRIANGULAR_MESH:
            s = new i.Mesh,
            l = a.DecodeBufferToMesh(o, s);
            break;
        case i.POINT_CLOUD:
            s = new i.PointCloud,
            l = a.DecodeBufferToPointCloud(o, s);
            break;
        default:
            throw new Error("Invalid geometry type " + u)
        }
        if (!l.ok() || !s.ptr)
            throw new Error(l.error_msg());
        if (u === i.TRIANGULAR_MESH) {
            var c = s.num_faces()
              , h = c * 3
              , f = h * 4
              , d = i._malloc(f);
            try {
                a.GetTrianglesUInt32Array(s, f, d);
                var _ = new Uint32Array(h);
                _.set(new Uint32Array(i.HEAPF32.buffer,d,h)),
                r(_)
            } finally {
                i._free(d)
            }
        }
        var g = function(T, C) {
            var A = C.num_components()
              , S = s.num_points()
              , P = S * A
              , R = P * Float32Array.BYTES_PER_ELEMENT
              , M = i._malloc(R);
            try {
                a.GetAttributeDataArrayForAllPoints(s, C, i.DT_FLOAT32, R, M);
                var x = new Float32Array(i.HEAPF32.buffer,M,P);
                if (T === "color" && A === 3) {
                    for (var I = new Float32Array(S * 4), w = 0, O = 0; w < I.length; w += 4,
                    O += A)
                        I[w + 0] = x[O + 0],
                        I[w + 1] = x[O + 1],
                        I[w + 2] = x[O + 2],
                        I[w + 3] = 1;
                    n(T, I)
                } else {
                    var I = new Float32Array(P);
                    I.set(new Float32Array(i.HEAPF32.buffer,M,P)),
                    n(T, I)
                }
            } finally {
                i._free(M)
            }
        };
        if (t)
            for (var m in t) {
                var v = t[m]
                  , y = a.GetAttributeByUniqueId(s, v);
                g(m, y)
            }
        else {
            var b = {
                position: "POSITION",
                normal: "NORMAL",
                color: "COLOR",
                uv: "TEX_COORD"
            };
            for (var m in b) {
                var v = a.GetAttributeId(s, i[b[m]]);
                if (v !== -1) {
                    var y = a.GetAttribute(s, v);
                    g(m, y)
                }
            }
        }
    } finally {
        s && i.destroy(s),
        i.destroy(a),
        i.destroy(o)
    }
}
function worker$1() {
    var i;
    onmessage = function(e) {
        var t = e.data;
        switch (t.id) {
        case "init":
            {
                var r = t.decoder;
                r.url && (importScripts(r.url),
                i = DracoDecoderModule({
                    wasmBinary: r.wasmBinary
                })),
                postMessage("done");
                break
            }
        case "decodeMesh":
            {
                if (!i)
                    throw new Error("Draco decoder module is not available");
                i.then(function(n) {
                    decodeMesh(n, t.dataView, t.attributes, function(o) {
                        postMessage({
                            id: "indices",
                            value: o
                        }, [o.buffer])
                    }, function(o, a) {
                        postMessage({
                            id: o,
                            value: a
                        }, [a.buffer])
                    }),
                    postMessage("done")
                });
                break
            }
        }
    }
}
var DracoCompression = function() {
    function i(e) {
        e === void 0 && (e = i.DefaultNumWorkers);
        var t = i.Configuration.decoder
          , r = t.wasmUrl && t.wasmBinaryUrl && typeof WebAssembly == "object" ? {
            url: Tools.GetAbsoluteUrl(t.wasmUrl),
            wasmBinaryPromise: Tools.LoadFileAsync(Tools.GetAbsoluteUrl(t.wasmBinaryUrl))
        } : {
            url: Tools.GetAbsoluteUrl(t.fallbackUrl),
            wasmBinaryPromise: Promise.resolve(void 0)
        };
        e && typeof Worker == "function" ? this._workerPoolPromise = r.wasmBinaryPromise.then(function(n) {
            for (var o = decodeMesh + "(" + worker$1 + ")()", a = URL.createObjectURL(new Blob([o],{
                type: "application/javascript"
            })), s = new Array(e), l = 0; l < s.length; l++)
                s[l] = new Promise(function(u, c) {
                    var h = new Worker(a)
                      , f = function(_) {
                        h.removeEventListener("error", f),
                        h.removeEventListener("message", d),
                        c(_)
                    }
                      , d = function(_) {
                        _.data === "done" && (h.removeEventListener("error", f),
                        h.removeEventListener("message", d),
                        u(h))
                    };
                    h.addEventListener("error", f),
                    h.addEventListener("message", d),
                    h.postMessage({
                        id: "init",
                        decoder: {
                            url: r.url,
                            wasmBinary: n
                        }
                    })
                }
                );
            return Promise.all(s).then(function(u) {
                return new WorkerPool(u)
            })
        }) : this._decoderModulePromise = r.wasmBinaryPromise.then(function(n) {
            if (!r.url)
                throw new Error("Draco decoder module is not available");
            return Tools.LoadScriptAsync(r.url).then(function() {
                return createDecoderAsync(n)
            })
        })
    }
    return Object.defineProperty(i, "DecoderAvailable", {
        get: function() {
            var e = i.Configuration.decoder;
            return !!(e.wasmUrl && e.wasmBinaryUrl && typeof WebAssembly == "object" || e.fallbackUrl)
        },
        enumerable: !1,
        configurable: !0
    }),
    i.GetDefaultNumWorkers = function() {
        return typeof navigator != "object" || !navigator.hardwareConcurrency ? 1 : Math.min(Math.floor(navigator.hardwareConcurrency * .5), 4)
    }
    ,
    Object.defineProperty(i, "Default", {
        get: function() {
            return i._Default || (i._Default = new i),
            i._Default
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.dispose = function() {
        this._workerPoolPromise && this._workerPoolPromise.then(function(e) {
            e.dispose()
        }),
        delete this._workerPoolPromise,
        delete this._decoderModulePromise
    }
    ,
    i.prototype.whenReadyAsync = function() {
        return this._workerPoolPromise ? this._workerPoolPromise.then(function() {}) : this._decoderModulePromise ? this._decoderModulePromise.then(function() {}) : Promise.resolve()
    }
    ,
    i.prototype.decodeMeshAsync = function(e, t) {
        var r = e instanceof ArrayBuffer ? new Uint8Array(e) : e;
        if (this._workerPoolPromise)
            return this._workerPoolPromise.then(function(n) {
                return new Promise(function(o, a) {
                    n.push(function(s, l) {
                        var u = new VertexData
                          , c = function(d) {
                            s.removeEventListener("error", c),
                            s.removeEventListener("message", h),
                            a(d),
                            l()
                        }
                          , h = function(d) {
                            d.data === "done" ? (s.removeEventListener("error", c),
                            s.removeEventListener("message", h),
                            o(u),
                            l()) : d.data.id === "indices" ? u.indices = d.data.value : u.set(d.data.value, d.data.id)
                        };
                        s.addEventListener("error", c),
                        s.addEventListener("message", h);
                        var f = new Uint8Array(r.byteLength);
                        f.set(new Uint8Array(r.buffer,r.byteOffset,r.byteLength)),
                        s.postMessage({
                            id: "decodeMesh",
                            dataView: f,
                            attributes: t
                        }, [f.buffer])
                    })
                }
                )
            });
        if (this._decoderModulePromise)
            return this._decoderModulePromise.then(function(n) {
                var o = new VertexData;
                return decodeMesh(n.module, r, t, function(a) {
                    o.indices = a
                }, function(a, s) {
                    o.set(s, a)
                }),
                o
            });
        throw new Error("Draco decoder module is not available")
    }
    ,
    i.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"
        }
    },
    i.DefaultNumWorkers = i.GetDefaultNumWorkers(),
    i._Default = null,
    i
}()
  , NAME$l = "KHR_draco_mesh_compression"
  , KHR_draco_mesh_compression = function() {
    function i(e) {
        this.name = NAME$l,
        this._loader = e,
        this.enabled = DracoCompression.DecoderAvailable && this._loader.isExtensionUsed(NAME$l)
    }
    return i.prototype.dispose = function() {
        delete this.dracoCompression,
        this._loader = null
    }
    ,
    i.prototype._loadVertexDataAsync = function(e, t, r) {
        var n = this;
        return GLTFLoader.LoadExtensionAsync(e, t, this.name, function(o, a) {
            if (t.mode != null) {
                if (t.mode !== 5 && t.mode !== 4)
                    throw new Error(e + ": Unsupported mode " + t.mode);
                if (t.mode === 5)
                    throw new Error(e + ": Mode " + t.mode + " is not currently supported")
            }
            var s = {}
              , l = function(c, h) {
                var f = a.attributes[c];
                f != null && (r._delayInfo = r._delayInfo || [],
                r._delayInfo.indexOf(h) === -1 && r._delayInfo.push(h),
                s[h] = f)
            };
            l("POSITION", VertexBuffer.PositionKind),
            l("NORMAL", VertexBuffer.NormalKind),
            l("TANGENT", VertexBuffer.TangentKind),
            l("TEXCOORD_0", VertexBuffer.UVKind),
            l("TEXCOORD_1", VertexBuffer.UV2Kind),
            l("TEXCOORD_2", VertexBuffer.UV3Kind),
            l("TEXCOORD_3", VertexBuffer.UV4Kind),
            l("TEXCOORD_4", VertexBuffer.UV5Kind),
            l("TEXCOORD_5", VertexBuffer.UV6Kind),
            l("JOINTS_0", VertexBuffer.MatricesIndicesKind),
            l("WEIGHTS_0", VertexBuffer.MatricesWeightsKind),
            l("COLOR_0", VertexBuffer.ColorKind);
            var u = ArrayItem.Get(o, n._loader.gltf.bufferViews, a.bufferView);
            return u._dracoBabylonGeometry || (u._dracoBabylonGeometry = n._loader.loadBufferViewAsync("/bufferViews/" + u.index, u).then(function(c) {
                var h = n.dracoCompression || DracoCompression.Default;
                return h.decodeMeshAsync(c, s).then(function(f) {
                    var d = new Geometry(r.name,n._loader.babylonScene);
                    return f.applyToGeometry(d),
                    d
                }).catch(function(f) {
                    throw new Error(e + ": " + f.message)
                })
            })),
            u._dracoBabylonGeometry
        })
    }
    ,
    i
}();
GLTFLoader.RegisterExtension(NAME$l, function(i) {
    return new KHR_draco_mesh_compression(i)
});
var NAME$k = "KHR_lights_punctual"
  , KHR_lights = function() {
    function i(e) {
        this.name = NAME$k,
        this._loader = e,
        this.enabled = this._loader.isExtensionUsed(NAME$k)
    }
    return i.prototype.dispose = function() {
        this._loader = null,
        delete this._lights
    }
    ,
    i.prototype.onLoading = function() {
        var e = this._loader.gltf.extensions;
        if (e && e[this.name]) {
            var t = e[this.name];
            this._lights = t.lights
        }
    }
    ,
    i.prototype.loadNodeAsync = function(e, t, r) {
        var n = this;
        return GLTFLoader.LoadExtensionAsync(e, t, this.name, function(o, a) {
            return n._loader.loadNodeAsync(e, t, function(s) {
                var l, u = ArrayItem.Get(o, n._lights, a.light), c = u.name || s.name;
                switch (n._loader.babylonScene._blockEntityCollection = !!n._loader._assetContainer,
                u.type) {
                case "directional":
                    {
                        l = new DirectionalLight(c,Vector3.Backward(),n._loader.babylonScene);
                        break
                    }
                case "point":
                    {
                        l = new PointLight(c,Vector3.Zero(),n._loader.babylonScene);
                        break
                    }
                case "spot":
                    {
                        var h = new SpotLight(c,Vector3.Zero(),Vector3.Backward(),0,1,n._loader.babylonScene);
                        h.angle = (u.spot && u.spot.outerConeAngle || Math.PI / 4) * 2,
                        h.innerAngle = (u.spot && u.spot.innerConeAngle || 0) * 2,
                        l = h;
                        break
                    }
                default:
                    throw n._loader.babylonScene._blockEntityCollection = !1,
                    new Error(o + ": Invalid light type (" + u.type + ")")
                }
                l._parentContainer = n._loader._assetContainer,
                n._loader.babylonScene._blockEntityCollection = !1,
                l.falloffType = Light.FALLOFF_GLTF,
                l.diffuse = u.color ? Color3.FromArray(u.color) : Color3.White(),
                l.intensity = u.intensity == null ? 1 : u.intensity,
                l.range = u.range == null ? Number.MAX_VALUE : u.range,
                l.parent = s,
                n._loader._babylonLights.push(l),
                GLTFLoader.AddPointerMetadata(l, o),
                r(s)
            })
        })
    }
    ,
    i
}();
GLTFLoader.RegisterExtension(NAME$k, function(i) {
    return new KHR_lights(i)
});
var NAME$j = "KHR_materials_pbrSpecularGlossiness"
  , KHR_materials_pbrSpecularGlossiness = function() {
    function i(e) {
        this.name = NAME$j,
        this.order = 200,
        this._loader = e,
        this.enabled = this._loader.isExtensionUsed(NAME$j)
    }
    return i.prototype.dispose = function() {
        this._loader = null
    }
    ,
    i.prototype.loadMaterialPropertiesAsync = function(e, t, r) {
        var n = this;
        return GLTFLoader.LoadExtensionAsync(e, t, this.name, function(o, a) {
            var s = new Array;
            return s.push(n._loader.loadMaterialBasePropertiesAsync(e, t, r)),
            s.push(n._loadSpecularGlossinessPropertiesAsync(o, t, a, r)),
            n._loader.loadMaterialAlphaProperties(e, t, r),
            Promise.all(s).then(function() {})
        })
    }
    ,
    i.prototype._loadSpecularGlossinessPropertiesAsync = function(e, t, r, n) {
        if (!(n instanceof PBRMaterial))
            throw new Error(e + ": Material type not supported");
        var o = new Array;
        return n.metallic = null,
        n.roughness = null,
        r.diffuseFactor ? (n.albedoColor = Color3.FromArray(r.diffuseFactor),
        n.alpha = r.diffuseFactor[3]) : n.albedoColor = Color3.White(),
        n.reflectivityColor = r.specularFactor ? Color3.FromArray(r.specularFactor) : Color3.White(),
        n.microSurface = r.glossinessFactor == null ? 1 : r.glossinessFactor,
        r.diffuseTexture && o.push(this._loader.loadTextureInfoAsync(e + "/diffuseTexture", r.diffuseTexture, function(a) {
            a.name = n.name + " (Diffuse)",
            n.albedoTexture = a
        })),
        r.specularGlossinessTexture && (o.push(this._loader.loadTextureInfoAsync(e + "/specularGlossinessTexture", r.specularGlossinessTexture, function(a) {
            a.name = n.name + " (Specular Glossiness)",
            n.reflectivityTexture = a
        })),
        n.reflectivityTexture.hasAlpha = !0,
        n.useMicroSurfaceFromReflectivityMapAlpha = !0),
        Promise.all(o).then(function() {})
    }
    ,
    i
}();
GLTFLoader.RegisterExtension(NAME$j, function(i) {
    return new KHR_materials_pbrSpecularGlossiness(i)
});
var NAME$i = "KHR_materials_unlit"
  , KHR_materials_unlit = function() {
    function i(e) {
        this.name = NAME$i,
        this.order = 210,
        this._loader = e,
        this.enabled = this._loader.isExtensionUsed(NAME$i)
    }
    return i.prototype.dispose = function() {
        this._loader = null
    }
    ,
    i.prototype.loadMaterialPropertiesAsync = function(e, t, r) {
        var n = this;
        return GLTFLoader.LoadExtensionAsync(e, t, this.name, function() {
            return n._loadUnlitPropertiesAsync(e, t, r)
        })
    }
    ,
    i.prototype._loadUnlitPropertiesAsync = function(e, t, r) {
        if (!(r instanceof PBRMaterial))
            throw new Error(e + ": Material type not supported");
        var n = new Array;
        r.unlit = !0;
        var o = t.pbrMetallicRoughness;
        return o && (o.baseColorFactor ? (r.albedoColor = Color3.FromArray(o.baseColorFactor),
        r.alpha = o.baseColorFactor[3]) : r.albedoColor = Color3.White(),
        o.baseColorTexture && n.push(this._loader.loadTextureInfoAsync(e + "/baseColorTexture", o.baseColorTexture, function(a) {
            a.name = r.name + " (Base Color)",
            r.albedoTexture = a
        }))),
        t.doubleSided && (r.backFaceCulling = !1,
        r.twoSidedLighting = !0),
        this._loader.loadMaterialAlphaProperties(e, t, r),
        Promise.all(n).then(function() {})
    }
    ,
    i
}();
GLTFLoader.RegisterExtension(NAME$i, function(i) {
    return new KHR_materials_unlit(i)
});
var NAME$h = "KHR_materials_clearcoat"
  , KHR_materials_clearcoat = function() {
    function i(e) {
        this.name = NAME$h,
        this.order = 190,
        this._loader = e,
        this.enabled = this._loader.isExtensionUsed(NAME$h)
    }
    return i.prototype.dispose = function() {
        this._loader = null
    }
    ,
    i.prototype.loadMaterialPropertiesAsync = function(e, t, r) {
        var n = this;
        return GLTFLoader.LoadExtensionAsync(e, t, this.name, function(o, a) {
            var s = new Array;
            return s.push(n._loader.loadMaterialPropertiesAsync(e, t, r)),
            s.push(n._loadClearCoatPropertiesAsync(o, a, r)),
            Promise.all(s).then(function() {})
        })
    }
    ,
    i.prototype._loadClearCoatPropertiesAsync = function(e, t, r) {
        if (!(r instanceof PBRMaterial))
            throw new Error(e + ": Material type not supported");
        var n = new Array;
        return r.clearCoat.isEnabled = !0,
        r.clearCoat.useRoughnessFromMainTexture = !1,
        r.clearCoat.remapF0OnInterfaceChange = !1,
        t.clearcoatFactor != null ? r.clearCoat.intensity = t.clearcoatFactor : r.clearCoat.intensity = 0,
        t.clearcoatTexture && n.push(this._loader.loadTextureInfoAsync(e + "/clearcoatTexture", t.clearcoatTexture, function(o) {
            o.name = r.name + " (ClearCoat Intensity)",
            r.clearCoat.texture = o
        })),
        t.clearcoatRoughnessFactor != null ? r.clearCoat.roughness = t.clearcoatRoughnessFactor : r.clearCoat.roughness = 0,
        t.clearcoatRoughnessTexture && (t.clearcoatRoughnessTexture.nonColorData = !0,
        n.push(this._loader.loadTextureInfoAsync(e + "/clearcoatRoughnessTexture", t.clearcoatRoughnessTexture, function(o) {
            o.name = r.name + " (ClearCoat Roughness)",
            r.clearCoat.textureRoughness = o
        }))),
        t.clearcoatNormalTexture && (t.clearcoatNormalTexture.nonColorData = !0,
        n.push(this._loader.loadTextureInfoAsync(e + "/clearcoatNormalTexture", t.clearcoatNormalTexture, function(o) {
            o.name = r.name + " (ClearCoat Normal)",
            r.clearCoat.bumpTexture = o
        })),
        r.invertNormalMapX = !r.getScene().useRightHandedSystem,
        r.invertNormalMapY = r.getScene().useRightHandedSystem,
        t.clearcoatNormalTexture.scale != null && (r.clearCoat.bumpTexture.level = t.clearcoatNormalTexture.scale)),
        Promise.all(n).then(function() {})
    }
    ,
    i
}();
GLTFLoader.RegisterExtension(NAME$h, function(i) {
    return new KHR_materials_clearcoat(i)
});
var NAME$g = "KHR_materials_emissive_strength"
  , KHR_materials_emissive_strength = function() {
    function i(e) {
        this.name = NAME$g,
        this.order = 170,
        this._loader = e,
        this.enabled = this._loader.isExtensionUsed(NAME$g)
    }
    return i.prototype.dispose = function() {
        this._loader = null
    }
    ,
    i.prototype.loadMaterialPropertiesAsync = function(e, t, r) {
        var n = this;
        return GLTFLoader.LoadExtensionAsync(e, t, this.name, function(o, a) {
            return n._loader.loadMaterialPropertiesAsync(e, t, r).then(function() {
                n._loadEmissiveProperties(o, a, r)
            })
        })
    }
    ,
    i.prototype._loadEmissiveProperties = function(e, t, r) {
        if (!(r instanceof PBRMaterial))
            throw new Error(e + ": Material type not supported");
        t.emissiveStrength !== void 0 && r.emissiveColor.scaleToRef(t.emissiveStrength, r.emissiveColor)
    }
    ,
    i
}();
GLTFLoader.RegisterExtension(NAME$g, function(i) {
    return new KHR_materials_emissive_strength(i)
});
var NAME$f = "KHR_materials_sheen"
  , KHR_materials_sheen = function() {
    function i(e) {
        this.name = NAME$f,
        this.order = 190,
        this._loader = e,
        this.enabled = this._loader.isExtensionUsed(NAME$f)
    }
    return i.prototype.dispose = function() {
        this._loader = null
    }
    ,
    i.prototype.loadMaterialPropertiesAsync = function(e, t, r) {
        var n = this;
        return GLTFLoader.LoadExtensionAsync(e, t, this.name, function(o, a) {
            var s = new Array;
            return s.push(n._loader.loadMaterialPropertiesAsync(e, t, r)),
            s.push(n._loadSheenPropertiesAsync(o, a, r)),
            Promise.all(s).then(function() {})
        })
    }
    ,
    i.prototype._loadSheenPropertiesAsync = function(e, t, r) {
        if (!(r instanceof PBRMaterial))
            throw new Error(e + ": Material type not supported");
        var n = new Array;
        return r.sheen.isEnabled = !0,
        r.sheen.intensity = 1,
        t.sheenColorFactor != null ? r.sheen.color = Color3.FromArray(t.sheenColorFactor) : r.sheen.color = Color3.Black(),
        t.sheenColorTexture && n.push(this._loader.loadTextureInfoAsync(e + "/sheenColorTexture", t.sheenColorTexture, function(o) {
            o.name = r.name + " (Sheen Color)",
            r.sheen.texture = o
        })),
        t.sheenRoughnessFactor !== void 0 ? r.sheen.roughness = t.sheenRoughnessFactor : r.sheen.roughness = 0,
        t.sheenRoughnessTexture && (t.sheenRoughnessTexture.nonColorData = !0,
        n.push(this._loader.loadTextureInfoAsync(e + "/sheenRoughnessTexture", t.sheenRoughnessTexture, function(o) {
            o.name = r.name + " (Sheen Roughness)",
            r.sheen.textureRoughness = o
        }))),
        r.sheen.albedoScaling = !0,
        r.sheen.useRoughnessFromMainTexture = !1,
        Promise.all(n).then(function() {})
    }
    ,
    i
}();
GLTFLoader.RegisterExtension(NAME$f, function(i) {
    return new KHR_materials_sheen(i)
});
var NAME$e = "KHR_materials_specular"
  , KHR_materials_specular = function() {
    function i(e) {
        this.name = NAME$e,
        this.order = 190,
        this._loader = e,
        this.enabled = this._loader.isExtensionUsed(NAME$e)
    }
    return i.prototype.dispose = function() {
        this._loader = null
    }
    ,
    i.prototype.loadMaterialPropertiesAsync = function(e, t, r) {
        var n = this;
        return GLTFLoader.LoadExtensionAsync(e, t, this.name, function(o, a) {
            var s = new Array;
            return s.push(n._loader.loadMaterialPropertiesAsync(e, t, r)),
            s.push(n._loadSpecularPropertiesAsync(o, a, r)),
            Promise.all(s).then(function() {})
        })
    }
    ,
    i.prototype._loadSpecularPropertiesAsync = function(e, t, r) {
        if (!(r instanceof PBRMaterial))
            throw new Error(e + ": Material type not supported");
        var n = new Array;
        return t.specularFactor !== void 0 && (r.metallicF0Factor = t.specularFactor),
        t.specularColorFactor !== void 0 && (r.metallicReflectanceColor = Color3.FromArray(t.specularColorFactor)),
        t.specularTexture && (t.specularTexture.nonColorData = !0,
        n.push(this._loader.loadTextureInfoAsync(e + "/specularTexture", t.specularTexture, function(o) {
            o.name = r.name + " (Specular F0 Strength)",
            r.metallicReflectanceTexture = o,
            r.useOnlyMetallicFromMetallicReflectanceTexture = !0
        }))),
        t.specularColorTexture && n.push(this._loader.loadTextureInfoAsync(e + "/specularColorTexture", t.specularColorTexture, function(o) {
            o.name = r.name + " (Specular F0 Color)",
            r.reflectanceTexture = o
        })),
        Promise.all(n).then(function() {})
    }
    ,
    i
}();
GLTFLoader.RegisterExtension(NAME$e, function(i) {
    return new KHR_materials_specular(i)
});
var NAME$d = "KHR_materials_ior"
  , KHR_materials_ior = function() {
    function i(e) {
        this.name = NAME$d,
        this.order = 180,
        this._loader = e,
        this.enabled = this._loader.isExtensionUsed(NAME$d)
    }
    return i.prototype.dispose = function() {
        this._loader = null
    }
    ,
    i.prototype.loadMaterialPropertiesAsync = function(e, t, r) {
        var n = this;
        return GLTFLoader.LoadExtensionAsync(e, t, this.name, function(o, a) {
            var s = new Array;
            return s.push(n._loader.loadMaterialPropertiesAsync(e, t, r)),
            s.push(n._loadIorPropertiesAsync(o, a, r)),
            Promise.all(s).then(function() {})
        })
    }
    ,
    i.prototype._loadIorPropertiesAsync = function(e, t, r) {
        if (!(r instanceof PBRMaterial))
            throw new Error(e + ": Material type not supported");
        return t.ior !== void 0 ? r.indexOfRefraction = t.ior : r.indexOfRefraction = i._DEFAULT_IOR,
        Promise.resolve()
    }
    ,
    i._DEFAULT_IOR = 1.5,
    i
}();
GLTFLoader.RegisterExtension(NAME$d, function(i) {
    return new KHR_materials_ior(i)
});
var NAME$c = "KHR_materials_variants"
  , KHR_materials_variants = function() {
    function i(e) {
        this.name = NAME$c,
        this._loader = e,
        this.enabled = this._loader.isExtensionUsed(NAME$c)
    }
    return i.prototype.dispose = function() {
        this._loader = null
    }
    ,
    i.GetAvailableVariants = function(e) {
        var t = this._GetExtensionMetadata(e);
        return t ? Object.keys(t.variants) : []
    }
    ,
    i.prototype.getAvailableVariants = function(e) {
        return i.GetAvailableVariants(e)
    }
    ,
    i.SelectVariant = function(e, t) {
        var r = this._GetExtensionMetadata(e);
        if (!r)
            throw new Error("Cannot select variant on a glTF mesh that does not have the " + NAME$c + " extension");
        var n = function(l) {
            var u = r.variants[l];
            if (u)
                for (var c = 0, h = u; c < h.length; c++) {
                    var f = h[c];
                    f.mesh.material = f.material
                }
        };
        if (t instanceof Array)
            for (var o = 0, a = t; o < a.length; o++) {
                var s = a[o];
                n(s)
            }
        else
            n(t);
        r.lastSelected = t
    }
    ,
    i.prototype.selectVariant = function(e, t) {
        return i.SelectVariant(e, t)
    }
    ,
    i.Reset = function(e) {
        var t = this._GetExtensionMetadata(e);
        if (!t)
            throw new Error("Cannot reset on a glTF mesh that does not have the " + NAME$c + " extension");
        for (var r = 0, n = t.original; r < n.length; r++) {
            var o = n[r];
            o.mesh.material = o.material
        }
        t.lastSelected = null
    }
    ,
    i.prototype.reset = function(e) {
        return i.Reset(e)
    }
    ,
    i.GetLastSelectedVariant = function(e) {
        var t = this._GetExtensionMetadata(e);
        if (!t)
            throw new Error("Cannot get the last selected variant on a glTF mesh that does not have the " + NAME$c + " extension");
        return t.lastSelected
    }
    ,
    i.prototype.getLastSelectedVariant = function(e) {
        return i.GetLastSelectedVariant(e)
    }
    ,
    i._GetExtensionMetadata = function(e) {
        var t, r;
        return ((r = (t = e == null ? void 0 : e.metadata) === null || t === void 0 ? void 0 : t.gltf) === null || r === void 0 ? void 0 : r[NAME$c]) || null
    }
    ,
    i.prototype.onLoading = function() {
        var e = this._loader.gltf.extensions;
        if (e && e[this.name]) {
            var t = e[this.name];
            this._variants = t.variants
        }
    }
    ,
    i.prototype._loadMeshPrimitiveAsync = function(e, t, r, n, o, a) {
        var s = this;
        return GLTFLoader.LoadExtensionAsync(e, o, this.name, function(l, u) {
            var c = new Array;
            return c.push(s._loader._loadMeshPrimitiveAsync(e, t, r, n, o, function(h) {
                if (a(h),
                h instanceof Mesh) {
                    var f = GLTFLoader._GetDrawMode(e, o.mode)
                      , d = s._loader.rootBabylonMesh
                      , _ = d ? d.metadata = d.metadata || {} : {}
                      , g = _.gltf = _.gltf || {}
                      , m = g[NAME$c] = g[NAME$c] || {
                        lastSelected: null,
                        original: [],
                        variants: {}
                    };
                    m.original.push({
                        mesh: h,
                        material: h.material
                    });
                    for (var v = function(b) {
                        var T = u.mappings[b]
                          , C = ArrayItem.Get(l + "/mappings/" + b + "/material", s._loader.gltf.materials, T.material);
                        c.push(s._loader._loadMaterialAsync("#/materials/" + T.material, C, h, f, function(A) {
                            for (var S = function(R) {
                                var M = T.variants[R]
                                  , x = ArrayItem.Get("/extensions/" + NAME$c + "/variants/" + M, s._variants, M);
                                m.variants[x.name] = m.variants[x.name] || [],
                                m.variants[x.name].push({
                                    mesh: h,
                                    material: A
                                }),
                                h.onClonedObservable.add(function(I) {
                                    var w = I
                                      , O = null
                                      , D = w;
                                    do {
                                        if (D = D.parent,
                                        !D)
                                            return;
                                        O = i._GetExtensionMetadata(D)
                                    } while (O === null);
                                    if (d && O === i._GetExtensionMetadata(d)) {
                                        D.metadata = {};
                                        for (var F in d.metadata)
                                            D.metadata[F] = d.metadata[F];
                                        D.metadata.gltf = [];
                                        for (var F in d.metadata.gltf)
                                            D.metadata.gltf[F] = d.metadata.gltf[F];
                                        D.metadata.gltf[NAME$c] = {
                                            lastSelected: null,
                                            original: [],
                                            variants: {}
                                        };
                                        for (var V = 0, N = O.original; V < N.length; V++) {
                                            var L = N[V];
                                            D.metadata.gltf[NAME$c].original.push({
                                                mesh: L.mesh,
                                                material: L.material
                                            })
                                        }
                                        for (var F in O.variants)
                                            if (O.variants.hasOwnProperty(F)) {
                                                D.metadata.gltf[NAME$c].variants[F] = [];
                                                for (var k = 0, U = O.variants[F]; k < U.length; k++) {
                                                    var z = U[k];
                                                    D.metadata.gltf[NAME$c].variants[F].push({
                                                        mesh: z.mesh,
                                                        material: z.material
                                                    })
                                                }
                                            }
                                        O = D.metadata.gltf[NAME$c]
                                    }
                                    for (var H = 0, G = O.original; H < G.length; H++) {
                                        var W = G[H];
                                        W.mesh === h && (W.mesh = w)
                                    }
                                    for (var j = 0, B = O.variants[x.name]; j < B.length; j++) {
                                        var W = B[j];
                                        W.mesh === h && (W.mesh = w)
                                    }
                                })
                            }, P = 0; P < T.variants.length; ++P)
                                S(P)
                        }))
                    }, y = 0; y < u.mappings.length; ++y)
                        v(y)
                }
            })),
            Promise.all(c).then(function(h) {
                var f = h[0];
                return f
            })
        })
    }
    ,
    i
}();
GLTFLoader.RegisterExtension(NAME$c, function(i) {
    return new KHR_materials_variants(i)
});
var TransmissionHelper = function() {
    function i(e, t) {
        var r = this;
        this._opaqueRenderTarget = null,
        this._opaqueMeshesCache = [],
        this._transparentMeshesCache = [],
        this._materialObservers = {},
        this._options = __assign(__assign({}, i._getDefaultOptions()), e),
        this._scene = t,
        this._scene._transmissionHelper = this,
        this.onErrorObservable = new Observable,
        this._scene.onDisposeObservable.addOnce(function(n) {
            r.dispose()
        }),
        this._parseScene(),
        this._setupRenderTargets()
    }
    return i._getDefaultOptions = function() {
        return {
            renderSize: 1024,
            samples: 4,
            lodGenerationScale: 1,
            lodGenerationOffset: -4,
            renderTargetTextureType: Constants.TEXTURETYPE_HALF_FLOAT,
            generateMipmaps: !0
        }
    }
    ,
    i.prototype.updateOptions = function(e) {
        var t = this
          , r = Object.keys(e).filter(function(a) {
            return t._options[a] !== e[a]
        });
        if (!!r.length) {
            var n = __assign(__assign({}, this._options), e)
              , o = this._options;
            this._options = n,
            n.renderSize !== o.renderSize || n.renderTargetTextureType !== o.renderTargetTextureType || n.generateMipmaps !== o.generateMipmaps || !this._opaqueRenderTarget ? this._setupRenderTargets() : (this._opaqueRenderTarget.samples = n.samples,
            this._opaqueRenderTarget.lodGenerationScale = n.lodGenerationScale,
            this._opaqueRenderTarget.lodGenerationOffset = n.lodGenerationOffset)
        }
    }
    ,
    i.prototype.getOpaqueTarget = function() {
        return this._opaqueRenderTarget
    }
    ,
    i.prototype.shouldRenderAsTransmission = function(e) {
        return e ? !!(e instanceof PBRMaterial && e.subSurface.isRefractionEnabled) : !1
    }
    ,
    i.prototype._addMesh = function(e) {
        var t = this;
        this._materialObservers[e.uniqueId] = e.onMaterialChangedObservable.add(this._onMeshMaterialChanged.bind(this)),
        Tools.SetImmediate(function() {
            t.shouldRenderAsTransmission(e.material) ? (e.material.refractionTexture = t._opaqueRenderTarget,
            t._transparentMeshesCache.push(e)) : t._opaqueMeshesCache.push(e)
        })
    }
    ,
    i.prototype._removeMesh = function(e) {
        e.onMaterialChangedObservable.remove(this._materialObservers[e.uniqueId]),
        delete this._materialObservers[e.uniqueId];
        var t = this._transparentMeshesCache.indexOf(e);
        t !== -1 && this._transparentMeshesCache.splice(t, 1),
        t = this._opaqueMeshesCache.indexOf(e),
        t !== -1 && this._opaqueMeshesCache.splice(t, 1)
    }
    ,
    i.prototype._parseScene = function() {
        this._scene.meshes.forEach(this._addMesh.bind(this)),
        this._scene.onNewMeshAddedObservable.add(this._addMesh.bind(this)),
        this._scene.onMeshRemovedObservable.add(this._removeMesh.bind(this))
    }
    ,
    i.prototype._onMeshMaterialChanged = function(e) {
        var t = this._transparentMeshesCache.indexOf(e)
          , r = this._opaqueMeshesCache.indexOf(e)
          , n = this.shouldRenderAsTransmission(e.material);
        n ? (e.material instanceof PBRMaterial && (e.material.subSurface.refractionTexture = this._opaqueRenderTarget),
        r !== -1 ? (this._opaqueMeshesCache.splice(r, 1),
        this._transparentMeshesCache.push(e)) : t === -1 && this._transparentMeshesCache.push(e)) : t !== -1 ? (this._transparentMeshesCache.splice(t, 1),
        this._opaqueMeshesCache.push(e)) : r === -1 && this._opaqueMeshesCache.push(e)
    }
    ,
    i.prototype._setupRenderTargets = function() {
        var e = this, t, r;
        this._opaqueRenderTarget && this._opaqueRenderTarget.dispose(),
        this._opaqueRenderTarget = new RenderTargetTexture("opaqueSceneTexture",this._options.renderSize,this._scene,this._options.generateMipmaps,void 0,this._options.renderTargetTextureType),
        this._opaqueRenderTarget.ignoreCameraViewport = !0,
        this._opaqueRenderTarget.renderList = this._opaqueMeshesCache,
        this._opaqueRenderTarget.clearColor = (r = (t = this._options.clearColor) === null || t === void 0 ? void 0 : t.clone()) !== null && r !== void 0 ? r : this._scene.clearColor.clone(),
        this._opaqueRenderTarget.gammaSpace = !1,
        this._opaqueRenderTarget.lodGenerationScale = this._options.lodGenerationScale,
        this._opaqueRenderTarget.lodGenerationOffset = this._options.lodGenerationOffset,
        this._opaqueRenderTarget.samples = this._options.samples;
        var n, o;
        this._opaqueRenderTarget.onBeforeBindObservable.add(function(a) {
            o = e._scene.environmentIntensity,
            e._scene.environmentIntensity = 1,
            n = e._scene.imageProcessingConfiguration.applyByPostProcess,
            e._options.clearColor ? a.clearColor.copyFrom(e._options.clearColor) : e._scene.clearColor.toLinearSpaceToRef(a.clearColor),
            e._scene.imageProcessingConfiguration._applyByPostProcess = !0
        }),
        this._opaqueRenderTarget.onAfterUnbindObservable.add(function() {
            e._scene.environmentIntensity = o,
            e._scene.imageProcessingConfiguration._applyByPostProcess = n
        }),
        this._transparentMeshesCache.forEach(function(a) {
            e.shouldRenderAsTransmission(a.material) && (a.material.refractionTexture = e._opaqueRenderTarget)
        })
    }
    ,
    i.prototype.dispose = function() {
        this._scene._transmissionHelper = void 0,
        this._opaqueRenderTarget && (this._opaqueRenderTarget.dispose(),
        this._opaqueRenderTarget = null),
        this._transparentMeshesCache = [],
        this._opaqueMeshesCache = []
    }
    ,
    i
}()
  , NAME$b = "KHR_materials_transmission"
  , KHR_materials_transmission = function() {
    function i(e) {
        this.name = NAME$b,
        this.order = 175,
        this._loader = e,
        this.enabled = this._loader.isExtensionUsed(NAME$b),
        this.enabled && (e.parent.transparencyAsCoverage = !0)
    }
    return i.prototype.dispose = function() {
        this._loader = null
    }
    ,
    i.prototype.loadMaterialPropertiesAsync = function(e, t, r) {
        var n = this;
        return GLTFLoader.LoadExtensionAsync(e, t, this.name, function(o, a) {
            var s = new Array;
            return s.push(n._loader.loadMaterialBasePropertiesAsync(e, t, r)),
            s.push(n._loader.loadMaterialPropertiesAsync(e, t, r)),
            s.push(n._loadTransparentPropertiesAsync(o, t, r, a)),
            Promise.all(s).then(function() {})
        })
    }
    ,
    i.prototype._loadTransparentPropertiesAsync = function(e, t, r, n) {
        if (!(r instanceof PBRMaterial))
            throw new Error(e + ": Material type not supported");
        var o = r;
        if (o.subSurface.isRefractionEnabled = !0,
        o.subSurface.volumeIndexOfRefraction = 1,
        o.subSurface.useAlbedoToTintRefraction = !0,
        n.transmissionFactor !== void 0) {
            o.subSurface.refractionIntensity = n.transmissionFactor;
            var a = o.getScene();
            o.subSurface.refractionIntensity && !a._transmissionHelper && new TransmissionHelper({},o.getScene())
        } else
            return o.subSurface.refractionIntensity = 0,
            o.subSurface.isRefractionEnabled = !1,
            Promise.resolve();
        return o.subSurface.minimumThickness = 0,
        o.subSurface.maximumThickness = 0,
        n.transmissionTexture ? (n.transmissionTexture.nonColorData = !0,
        this._loader.loadTextureInfoAsync(e + "/transmissionTexture", n.transmissionTexture, void 0).then(function(s) {
            o.subSurface.refractionIntensityTexture = s,
            o.subSurface.useGltfStyleTextures = !0
        })) : Promise.resolve()
    }
    ,
    i
}();
GLTFLoader.RegisterExtension(NAME$b, function(i) {
    return new KHR_materials_transmission(i)
});
var NAME$a = "KHR_materials_translucency"
  , KHR_materials_translucency = function() {
    function i(e) {
        this.name = NAME$a,
        this.order = 174,
        this._loader = e,
        this.enabled = this._loader.isExtensionUsed(NAME$a),
        this.enabled && (e.parent.transparencyAsCoverage = !0)
    }
    return i.prototype.dispose = function() {
        this._loader = null
    }
    ,
    i.prototype.loadMaterialPropertiesAsync = function(e, t, r) {
        var n = this;
        return GLTFLoader.LoadExtensionAsync(e, t, this.name, function(o, a) {
            var s = new Array;
            return s.push(n._loader.loadMaterialBasePropertiesAsync(e, t, r)),
            s.push(n._loader.loadMaterialPropertiesAsync(e, t, r)),
            s.push(n._loadTranslucentPropertiesAsync(o, t, r, a)),
            Promise.all(s).then(function() {})
        })
    }
    ,
    i.prototype._loadTranslucentPropertiesAsync = function(e, t, r, n) {
        if (!(r instanceof PBRMaterial))
            throw new Error(e + ": Material type not supported");
        var o = r;
        if (o.subSurface.isTranslucencyEnabled = !0,
        o.subSurface.volumeIndexOfRefraction = 1,
        o.subSurface.minimumThickness = 0,
        o.subSurface.maximumThickness = 0,
        o.subSurface.useAlbedoToTintTranslucency = !0,
        n.translucencyFactor !== void 0)
            o.subSurface.translucencyIntensity = n.translucencyFactor;
        else
            return o.subSurface.translucencyIntensity = 0,
            o.subSurface.isTranslucencyEnabled = !1,
            Promise.resolve();
        return n.translucencyTexture ? (n.translucencyTexture.nonColorData = !0,
        this._loader.loadTextureInfoAsync(e + "/translucencyTexture", n.translucencyTexture).then(function(a) {
            o.subSurface.translucencyIntensityTexture = a
        })) : Promise.resolve()
    }
    ,
    i
}();
GLTFLoader.RegisterExtension(NAME$a, function(i) {
    return new KHR_materials_translucency(i)
});
var NAME$9 = "KHR_materials_volume"
  , KHR_materials_volume = function() {
    function i(e) {
        this.name = NAME$9,
        this.order = 173,
        this._loader = e,
        this.enabled = this._loader.isExtensionUsed(NAME$9),
        this.enabled && this._loader._disableInstancedMesh++
    }
    return i.prototype.dispose = function() {
        this.enabled && this._loader._disableInstancedMesh--,
        this._loader = null
    }
    ,
    i.prototype.loadMaterialPropertiesAsync = function(e, t, r) {
        var n = this;
        return GLTFLoader.LoadExtensionAsync(e, t, this.name, function(o, a) {
            var s = new Array;
            return s.push(n._loader.loadMaterialBasePropertiesAsync(e, t, r)),
            s.push(n._loader.loadMaterialPropertiesAsync(e, t, r)),
            s.push(n._loadVolumePropertiesAsync(o, t, r, a)),
            Promise.all(s).then(function() {})
        })
    }
    ,
    i.prototype._loadVolumePropertiesAsync = function(e, t, r, n) {
        if (!(r instanceof PBRMaterial))
            throw new Error(e + ": Material type not supported");
        if (!r.subSurface.isRefractionEnabled && !r.subSurface.isTranslucencyEnabled || !n.thicknessFactor)
            return Promise.resolve();
        r.subSurface.volumeIndexOfRefraction = r.indexOfRefraction;
        var o = n.attenuationDistance !== void 0 ? n.attenuationDistance : Number.MAX_VALUE;
        return r.subSurface.tintColorAtDistance = o,
        n.attenuationColor !== void 0 && n.attenuationColor.length == 3 && r.subSurface.tintColor.copyFromFloats(n.attenuationColor[0], n.attenuationColor[1], n.attenuationColor[2]),
        r.subSurface.minimumThickness = 0,
        r.subSurface.maximumThickness = n.thicknessFactor,
        r.subSurface.useThicknessAsDepth = !0,
        n.thicknessTexture ? (n.thicknessTexture.nonColorData = !0,
        this._loader.loadTextureInfoAsync(e + "/thicknessTexture", n.thicknessTexture).then(function(a) {
            r.subSurface.thicknessTexture = a,
            r.subSurface.useGltfStyleTextures = !0
        })) : Promise.resolve()
    }
    ,
    i
}();
GLTFLoader.RegisterExtension(NAME$9, function(i) {
    return new KHR_materials_volume(i)
});
var NAME$8 = "KHR_mesh_quantization"
  , KHR_mesh_quantization = function() {
    function i(e) {
        this.name = NAME$8,
        this.enabled = e.isExtensionUsed(NAME$8)
    }
    return i.prototype.dispose = function() {}
    ,
    i
}();
GLTFLoader.RegisterExtension(NAME$8, function(i) {
    return new KHR_mesh_quantization(i)
});
var NAME$7 = "KHR_texture_basisu"
  , KHR_texture_basisu = function() {
    function i(e) {
        this.name = NAME$7,
        this._loader = e,
        this.enabled = e.isExtensionUsed(NAME$7)
    }
    return i.prototype.dispose = function() {
        this._loader = null
    }
    ,
    i.prototype._loadTextureAsync = function(e, t, r) {
        var n = this;
        return GLTFLoader.LoadExtensionAsync(e, t, this.name, function(o, a) {
            var s = t.sampler == null ? GLTFLoader.DefaultSampler : ArrayItem.Get(e + "/sampler", n._loader.gltf.samplers, t.sampler)
              , l = ArrayItem.Get(o + "/source", n._loader.gltf.images, a.source);
            return n._loader._createTextureAsync(e, s, l, function(u) {
                r(u)
            }, t._textureInfo.nonColorData ? {
                useRGBAIfASTCBC7NotAvailableWhenUASTC: !0
            } : void 0, !t._textureInfo.nonColorData)
        })
    }
    ,
    i
}();
GLTFLoader.RegisterExtension(NAME$7, function(i) {
    return new KHR_texture_basisu(i)
});
var NAME$6 = "KHR_texture_transform"
  , KHR_texture_transform = function() {
    function i(e) {
        this.name = NAME$6,
        this._loader = e,
        this.enabled = this._loader.isExtensionUsed(NAME$6)
    }
    return i.prototype.dispose = function() {
        this._loader = null
    }
    ,
    i.prototype.loadTextureInfoAsync = function(e, t, r) {
        var n = this;
        return GLTFLoader.LoadExtensionAsync(e, t, this.name, function(o, a) {
            return n._loader.loadTextureInfoAsync(e, t, function(s) {
                if (!(s instanceof Texture))
                    throw new Error(o + ": Texture type not supported");
                a.offset && (s.uOffset = a.offset[0],
                s.vOffset = a.offset[1]),
                s.uRotationCenter = 0,
                s.vRotationCenter = 0,
                a.rotation && (s.wAng = -a.rotation),
                a.scale && (s.uScale = a.scale[0],
                s.vScale = a.scale[1]),
                a.texCoord != null && (s.coordinatesIndex = a.texCoord),
                r(s)
            })
        })
    }
    ,
    i
}();
GLTFLoader.RegisterExtension(NAME$6, function(i) {
    return new KHR_texture_transform(i)
});
var NAME$5 = "KHR_xmp_json_ld"
  , KHR_xmp_json_ld = function() {
    function i(e) {
        this.name = NAME$5,
        this.order = 100,
        this._loader = e,
        this.enabled = this._loader.isExtensionUsed(NAME$5)
    }
    return i.prototype.dispose = function() {
        this._loader = null
    }
    ,
    i.prototype.onLoading = function() {
        var e, t, r;
        if (this._loader.rootBabylonMesh !== null) {
            var n = (e = this._loader.gltf.extensions) === null || e === void 0 ? void 0 : e.KHR_xmp_json_ld
              , o = (r = (t = this._loader.gltf.asset) === null || t === void 0 ? void 0 : t.extensions) === null || r === void 0 ? void 0 : r.KHR_xmp_json_ld;
            if (n && o) {
                var a = +o.packet;
                n.packets && a < n.packets.length && (this._loader.rootBabylonMesh.metadata = this._loader.rootBabylonMesh.metadata || {},
                this._loader.rootBabylonMesh.metadata.xmp = n.packets[a])
            }
        }
    }
    ,
    i
}();
GLTFLoader.RegisterExtension(NAME$5, function(i) {
    return new KHR_xmp_json_ld(i)
});
var AnimationEvent = function() {
    function i(e, t, r) {
        this.frame = e,
        this.action = t,
        this.onlyOnce = r,
        this.isDone = !1
    }
    return i.prototype._clone = function() {
        return new i(this.frame,this.action,this.onlyOnce)
    }
    ,
    i
}()
  , WeightedSound = function() {
    function i(e, t, r) {
        var n = this;
        if (this.loop = !1,
        this._coneInnerAngle = 360,
        this._coneOuterAngle = 360,
        this._volume = 1,
        this.isPlaying = !1,
        this.isPaused = !1,
        this._sounds = [],
        this._weights = [],
        t.length !== r.length)
            throw new Error("Sounds length does not equal weights length");
        this.loop = e,
        this._weights = r;
        for (var o = 0, a = 0, s = r; a < s.length; a++) {
            var l = s[a];
            o += l
        }
        for (var u = o > 0 ? 1 / o : 0, c = 0; c < this._weights.length; c++)
            this._weights[c] *= u;
        this._sounds = t;
        for (var h = 0, f = this._sounds; h < f.length; h++) {
            var d = f[h];
            d.onEndedObservable.add(function() {
                n._onended()
            })
        }
    }
    return Object.defineProperty(i.prototype, "directionalConeInnerAngle", {
        get: function() {
            return this._coneInnerAngle
        },
        set: function(e) {
            if (e !== this._coneInnerAngle) {
                if (this._coneOuterAngle < e) {
                    Logger$2.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
                    return
                }
                this._coneInnerAngle = e;
                for (var t = 0, r = this._sounds; t < r.length; t++) {
                    var n = r[t];
                    n.directionalConeInnerAngle = e
                }
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "directionalConeOuterAngle", {
        get: function() {
            return this._coneOuterAngle
        },
        set: function(e) {
            if (e !== this._coneOuterAngle) {
                if (e < this._coneInnerAngle) {
                    Logger$2.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
                    return
                }
                this._coneOuterAngle = e;
                for (var t = 0, r = this._sounds; t < r.length; t++) {
                    var n = r[t];
                    n.directionalConeOuterAngle = e
                }
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "volume", {
        get: function() {
            return this._volume
        },
        set: function(e) {
            if (e !== this._volume)
                for (var t = 0, r = this._sounds; t < r.length; t++) {
                    var n = r[t];
                    n.setVolume(e)
                }
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype._onended = function() {
        this._currentIndex !== void 0 && (this._sounds[this._currentIndex].autoplay = !1),
        this.loop && this.isPlaying ? this.play() : this.isPlaying = !1
    }
    ,
    i.prototype.pause = function() {
        this.isPaused = !0,
        this._currentIndex !== void 0 && this._sounds[this._currentIndex].pause()
    }
    ,
    i.prototype.stop = function() {
        this.isPlaying = !1,
        this._currentIndex !== void 0 && this._sounds[this._currentIndex].stop()
    }
    ,
    i.prototype.play = function(e) {
        if (!this.isPaused) {
            this.stop();
            for (var t = Math.random(), r = 0, n = 0; n < this._weights.length; n++)
                if (r += this._weights[n],
                t <= r) {
                    this._currentIndex = n;
                    break
                }
        }
        var o = this._sounds[this._currentIndex];
        o.isReady() ? o.play(0, this.isPaused ? void 0 : e) : o.autoplay = !0,
        this.isPlaying = !0,
        this.isPaused = !1
    }
    ,
    i
}()
  , NAME$4 = "MSFT_audio_emitter"
  , MSFT_audio_emitter = function() {
    function i(e) {
        this.name = NAME$4,
        this._loader = e,
        this.enabled = this._loader.isExtensionUsed(NAME$4)
    }
    return i.prototype.dispose = function() {
        this._loader = null,
        this._clips = null,
        this._emitters = null
    }
    ,
    i.prototype.onLoading = function() {
        var e = this._loader.gltf.extensions;
        if (e && e[this.name]) {
            var t = e[this.name];
            this._clips = t.clips,
            this._emitters = t.emitters,
            ArrayItem.Assign(this._clips),
            ArrayItem.Assign(this._emitters)
        }
    }
    ,
    i.prototype.loadSceneAsync = function(e, t) {
        var r = this;
        return GLTFLoader.LoadExtensionAsync(e, t, this.name, function(n, o) {
            var a = new Array;
            a.push(r._loader.loadSceneAsync(e, t));
            for (var s = 0, l = o.emitters; s < l.length; s++) {
                var u = l[s]
                  , c = ArrayItem.Get(n + "/emitters", r._emitters, u);
                if (c.refDistance != null || c.maxDistance != null || c.rolloffFactor != null || c.distanceModel != null || c.innerAngle != null || c.outerAngle != null)
                    throw new Error(n + ": Direction or Distance properties are not allowed on emitters attached to a scene");
                a.push(r._loadEmitterAsync(n + "/emitters/" + c.index, c))
            }
            return Promise.all(a).then(function() {})
        })
    }
    ,
    i.prototype.loadNodeAsync = function(e, t, r) {
        var n = this;
        return GLTFLoader.LoadExtensionAsync(e, t, this.name, function(o, a) {
            var s = new Array;
            return n._loader.loadNodeAsync(o, t, function(l) {
                for (var u = function(d) {
                    var _ = ArrayItem.Get(o + "/emitters", n._emitters, d);
                    s.push(n._loadEmitterAsync(o + "/emitters/" + _.index, _).then(function() {
                        for (var g = 0, m = _._babylonSounds; g < m.length; g++) {
                            var v = m[g];
                            v.attachToMesh(l),
                            (_.innerAngle != null || _.outerAngle != null) && (v.setLocalDirectionToMesh(Vector3.Forward()),
                            v.setDirectionalCone(2 * Tools.ToDegrees(_.innerAngle == null ? Math.PI : _.innerAngle), 2 * Tools.ToDegrees(_.outerAngle == null ? Math.PI : _.outerAngle), 0))
                        }
                    }))
                }, c = 0, h = a.emitters; c < h.length; c++) {
                    var f = h[c];
                    u(f)
                }
                r(l)
            }).then(function(l) {
                return Promise.all(s).then(function() {
                    return l
                })
            })
        })
    }
    ,
    i.prototype.loadAnimationAsync = function(e, t) {
        var r = this;
        return GLTFLoader.LoadExtensionAsync(e, t, this.name, function(n, o) {
            return r._loader.loadAnimationAsync(e, t).then(function(a) {
                var s = new Array;
                ArrayItem.Assign(o.events);
                for (var l = 0, u = o.events; l < u.length; l++) {
                    var c = u[l];
                    s.push(r._loadAnimationEventAsync(n + "/events/" + c.index, e, t, c, a))
                }
                return Promise.all(s).then(function() {
                    return a
                })
            })
        })
    }
    ,
    i.prototype._loadClipAsync = function(e, t) {
        if (t._objectURL)
            return t._objectURL;
        var r;
        if (t.uri)
            r = this._loader.loadUriAsync(e, t, t.uri);
        else {
            var n = ArrayItem.Get(e + "/bufferView", this._loader.gltf.bufferViews, t.bufferView);
            r = this._loader.loadBufferViewAsync("/bufferViews/" + n.index, n)
        }
        return t._objectURL = r.then(function(o) {
            return URL.createObjectURL(new Blob([o],{
                type: t.mimeType
            }))
        }),
        t._objectURL
    }
    ,
    i.prototype._loadEmitterAsync = function(e, t) {
        var r = this;
        if (t._babylonSounds = t._babylonSounds || [],
        !t._babylonData) {
            for (var n = new Array, o = t.name || "emitter" + t.index, a = {
                loop: !1,
                autoplay: !1,
                volume: t.volume == null ? 1 : t.volume
            }, s = function(h) {
                var f = "/extensions/" + l.name + "/clips"
                  , d = ArrayItem.Get(f, l._clips, t.clips[h].clip);
                n.push(l._loadClipAsync(f + "/" + t.clips[h].clip, d).then(function(_) {
                    var g = t._babylonSounds[h] = new Sound(o,_,r._loader.babylonScene,null,a);
                    g.refDistance = t.refDistance || 1,
                    g.maxDistance = t.maxDistance || 256,
                    g.rolloffFactor = t.rolloffFactor || 1,
                    g.distanceModel = t.distanceModel || "exponential"
                }))
            }, l = this, u = 0; u < t.clips.length; u++)
                s(u);
            var c = Promise.all(n).then(function() {
                var h = t.clips.map(function(d) {
                    return d.weight || 1
                })
                  , f = new WeightedSound(t.loop || !1,t._babylonSounds,h);
                t.innerAngle && (f.directionalConeInnerAngle = 2 * Tools.ToDegrees(t.innerAngle)),
                t.outerAngle && (f.directionalConeOuterAngle = 2 * Tools.ToDegrees(t.outerAngle)),
                t.volume && (f.volume = t.volume),
                t._babylonData.sound = f
            });
            t._babylonData = {
                loaded: c
            }
        }
        return t._babylonData.loaded
    }
    ,
    i.prototype._getEventAction = function(e, t, r, n, o) {
        switch (r) {
        case "play":
            return function(a) {
                var s = (o || 0) + (a - n);
                t.play(s)
            }
            ;
        case "stop":
            return function(a) {
                t.stop()
            }
            ;
        case "pause":
            return function(a) {
                t.pause()
            }
            ;
        default:
            throw new Error(e + ": Unsupported action " + r)
        }
    }
    ,
    i.prototype._loadAnimationEventAsync = function(e, t, r, n, o) {
        var a = this;
        if (o.targetedAnimations.length == 0)
            return Promise.resolve();
        var s = o.targetedAnimations[0]
          , l = n.emitter
          , u = ArrayItem.Get("/extensions/" + this.name + "/emitters", this._emitters, l);
        return this._loadEmitterAsync(e, u).then(function() {
            var c = u._babylonData.sound;
            if (c) {
                var h = new AnimationEvent(n.time,a._getEventAction(e, c, n.action, n.time, n.startOffset));
                s.animation.addEvent(h),
                o.onAnimationGroupEndObservable.add(function() {
                    c.stop()
                }),
                o.onAnimationGroupPauseObservable.add(function() {
                    c.pause()
                })
            }
        })
    }
    ,
    i
}();
GLTFLoader.RegisterExtension(NAME$4, function(i) {
    return new MSFT_audio_emitter(i)
});
var NAME$3 = "MSFT_lod"
  , MSFT_lod = function() {
    function i(e) {
        this.name = NAME$3,
        this.order = 100,
        this.maxLODsToLoad = 10,
        this.onNodeLODsLoadedObservable = new Observable,
        this.onMaterialLODsLoadedObservable = new Observable,
        this._bufferLODs = new Array,
        this._nodeIndexLOD = null,
        this._nodeSignalLODs = new Array,
        this._nodePromiseLODs = new Array,
        this._nodeBufferLODs = new Array,
        this._materialIndexLOD = null,
        this._materialSignalLODs = new Array,
        this._materialPromiseLODs = new Array,
        this._materialBufferLODs = new Array,
        this._loader = e,
        this.enabled = this._loader.isExtensionUsed(NAME$3)
    }
    return i.prototype.dispose = function() {
        this._loader = null,
        this._nodeIndexLOD = null,
        this._nodeSignalLODs.length = 0,
        this._nodePromiseLODs.length = 0,
        this._nodeBufferLODs.length = 0,
        this._materialIndexLOD = null,
        this._materialSignalLODs.length = 0,
        this._materialPromiseLODs.length = 0,
        this._materialBufferLODs.length = 0,
        this.onMaterialLODsLoadedObservable.clear(),
        this.onNodeLODsLoadedObservable.clear()
    }
    ,
    i.prototype.onReady = function() {
        for (var e = this, t = function(s) {
            var l = Promise.all(r._nodePromiseLODs[s]).then(function() {
                s !== 0 && (e._loader.endPerformanceCounter("Node LOD " + s),
                e._loader.log("Loaded node LOD " + s)),
                e.onNodeLODsLoadedObservable.notifyObservers(s),
                s !== e._nodePromiseLODs.length - 1 && (e._loader.startPerformanceCounter("Node LOD " + (s + 1)),
                e._loadBufferLOD(e._nodeBufferLODs, s + 1),
                e._nodeSignalLODs[s] && e._nodeSignalLODs[s].resolve())
            });
            r._loader._completePromises.push(l)
        }, r = this, n = 0; n < this._nodePromiseLODs.length; n++)
            t(n);
        for (var o = function(s) {
            var l = Promise.all(a._materialPromiseLODs[s]).then(function() {
                s !== 0 && (e._loader.endPerformanceCounter("Material LOD " + s),
                e._loader.log("Loaded material LOD " + s)),
                e.onMaterialLODsLoadedObservable.notifyObservers(s),
                s !== e._materialPromiseLODs.length - 1 && (e._loader.startPerformanceCounter("Material LOD " + (s + 1)),
                e._loadBufferLOD(e._materialBufferLODs, s + 1),
                e._materialSignalLODs[s] && e._materialSignalLODs[s].resolve())
            });
            a._loader._completePromises.push(l)
        }, a = this, n = 0; n < this._materialPromiseLODs.length; n++)
            o(n)
    }
    ,
    i.prototype.loadSceneAsync = function(e, t) {
        var r = this._loader.loadSceneAsync(e, t);
        return this._loadBufferLOD(this._bufferLODs, 0),
        r
    }
    ,
    i.prototype.loadNodeAsync = function(e, t, r) {
        var n = this;
        return GLTFLoader.LoadExtensionAsync(e, t, this.name, function(o, a) {
            var s, l = n._getLODs(o, t, n._loader.gltf.nodes, a.ids);
            n._loader.logOpen("" + o);
            for (var u = [], c = 0; c < l.length; c++)
                u.push(null);
            for (var h = function(f) {
                var d = l[f];
                f !== 0 && (n._nodeIndexLOD = f,
                n._nodeSignalLODs[f] = n._nodeSignalLODs[f] || new Deferred);
                var _ = function(m, v) {
                    var y, b, T;
                    m.setEnabled(!1),
                    u[v] = m;
                    for (var C = !0, A = 0; A < u.length; A++)
                        u[A] || (C = !1);
                    var S = u[u.length - 1];
                    if (C && S && n._isMesh(S)) {
                        var P = (T = (b = (y = S.metadata) === null || y === void 0 ? void 0 : y.gltf) === null || b === void 0 ? void 0 : b.extras) === null || T === void 0 ? void 0 : T.MSFT_screencoverage;
                        if (P && P.length) {
                            P.reverse(),
                            S.useLODScreenCoverage = !0;
                            for (var A = 0; A < u.length - 1; A++) {
                                var R = u[A];
                                R && n._isMesh(R) && S.addLODLevel(P[A + 1], R)
                            }
                            P[0] > 0 && S.addLODLevel(P[0], null)
                        }
                    }
                }
                  , g = n._loader.loadNodeAsync("/nodes/" + d.index, d, function(m) {
                    return _(m, f)
                }).then(function(m) {
                    var v, y, b, T = (b = (y = (v = l[l.length - 1]._babylonTransformNode.metadata) === null || v === void 0 ? void 0 : v.gltf) === null || y === void 0 ? void 0 : y.extras) === null || b === void 0 ? void 0 : b.MSFT_screencoverage;
                    if (f !== 0 && !T) {
                        var C = l[f - 1];
                        C._babylonTransformNode && (n._disposeTransformNode(C._babylonTransformNode),
                        delete C._babylonTransformNode)
                    }
                    return r(m),
                    m.setEnabled(!0),
                    m
                });
                n._nodePromiseLODs[f] = n._nodePromiseLODs[f] || [],
                f === 0 ? s = g : (n._nodeIndexLOD = null,
                n._nodePromiseLODs[f].push(g))
            }, c = 0; c < l.length; c++)
                h(c);
            return n._loader.logClose(),
            s
        })
    }
    ,
    i.prototype._loadMaterialAsync = function(e, t, r, n, o) {
        var a = this;
        return this._nodeIndexLOD ? null : GLTFLoader.LoadExtensionAsync(e, t, this.name, function(s, l) {
            var u, c = a._getLODs(s, t, a._loader.gltf.materials, l.ids);
            a._loader.logOpen("" + s);
            for (var h = function(d) {
                var _ = c[d];
                d !== 0 && (a._materialIndexLOD = d);
                var g = a._loader._loadMaterialAsync("/materials/" + _.index, _, r, n, function(m) {
                    d === 0 && o(m)
                }).then(function(m) {
                    if (d !== 0) {
                        o(m);
                        var v = c[d - 1]._data;
                        v[n] && (a._disposeMaterials([v[n].babylonMaterial]),
                        delete v[n])
                    }
                    return m
                });
                a._materialPromiseLODs[d] = a._materialPromiseLODs[d] || [],
                d === 0 ? u = g : (a._materialIndexLOD = null,
                a._materialPromiseLODs[d].push(g))
            }, f = 0; f < c.length; f++)
                h(f);
            return a._loader.logClose(),
            u
        })
    }
    ,
    i.prototype._loadUriAsync = function(e, t, r) {
        var n = this;
        if (this._nodeIndexLOD !== null) {
            this._loader.log("deferred");
            var o = this._nodeIndexLOD - 1;
            return this._nodeSignalLODs[o] = this._nodeSignalLODs[o] || new Deferred,
            this._nodeSignalLODs[this._nodeIndexLOD - 1].promise.then(function() {
                return n._loader.loadUriAsync(e, t, r)
            })
        } else if (this._materialIndexLOD !== null) {
            this._loader.log("deferred");
            var o = this._materialIndexLOD - 1;
            return this._materialSignalLODs[o] = this._materialSignalLODs[o] || new Deferred,
            this._materialSignalLODs[o].promise.then(function() {
                return n._loader.loadUriAsync(e, t, r)
            })
        }
        return null
    }
    ,
    i.prototype.loadBufferAsync = function(e, t, r, n) {
        if (this._loader.parent.useRangeRequests && !t.uri) {
            if (!this._loader.bin)
                throw new Error(e + ": Uri is missing or the binary glTF is missing its binary chunk");
            var o = function(a, s) {
                var l = r
                  , u = l + n - 1
                  , c = a[s];
                return c ? (c.start = Math.min(c.start, l),
                c.end = Math.max(c.end, u)) : (c = {
                    start: l,
                    end: u,
                    loaded: new Deferred
                },
                a[s] = c),
                c.loaded.promise.then(function(h) {
                    return new Uint8Array(h.buffer,h.byteOffset + r - c.start,n)
                })
            };
            return this._loader.log("deferred"),
            this._nodeIndexLOD !== null ? o(this._nodeBufferLODs, this._nodeIndexLOD) : this._materialIndexLOD !== null ? o(this._materialBufferLODs, this._materialIndexLOD) : o(this._bufferLODs, 0)
        }
        return null
    }
    ,
    i.prototype._isMesh = function(e) {
        return !!e.addLODLevel
    }
    ,
    i.prototype._loadBufferLOD = function(e, t) {
        var r = e[t];
        r && (this._loader.log("Loading buffer range [" + r.start + "-" + r.end + "]"),
        this._loader.bin.readAsync(r.start, r.end - r.start + 1).then(function(n) {
            r.loaded.resolve(n)
        }, function(n) {
            r.loaded.reject(n)
        }))
    }
    ,
    i.prototype._getLODs = function(e, t, r, n) {
        if (this.maxLODsToLoad <= 0)
            throw new Error("maxLODsToLoad must be greater than zero");
        for (var o = new Array, a = n.length - 1; a >= 0; a--)
            if (o.push(ArrayItem.Get(e + "/ids/" + n[a], r, n[a])),
            o.length === this.maxLODsToLoad)
                return o;
        return o.push(t),
        o
    }
    ,
    i.prototype._disposeTransformNode = function(e) {
        var t = this
          , r = new Array
          , n = e.material;
        n && r.push(n);
        for (var o = 0, a = e.getChildMeshes(); o < a.length; o++) {
            var s = a[o];
            s.material && r.push(s.material)
        }
        e.dispose();
        var l = r.filter(function(u) {
            return t._loader.babylonScene.meshes.every(function(c) {
                return c.material != u
            })
        });
        this._disposeMaterials(l)
    }
    ,
    i.prototype._disposeMaterials = function(e) {
        for (var t = {}, r = 0, n = e; r < n.length; r++) {
            for (var o = n[r], a = 0, s = o.getActiveTextures(); a < s.length; a++) {
                var l = s[a];
                t[l.uniqueId] = l
            }
            o.dispose()
        }
        for (var u in t)
            for (var c = 0, h = this._loader.babylonScene.materials; c < h.length; c++) {
                var o = h[c];
                o.hasTexture(t[u]) && delete t[u]
            }
        for (var u in t)
            t[u].dispose()
    }
    ,
    i
}();
GLTFLoader.RegisterExtension(NAME$3, function(i) {
    return new MSFT_lod(i)
});
var NAME$2 = "MSFT_minecraftMesh"
  , MSFT_minecraftMesh = function() {
    function i(e) {
        this.name = NAME$2,
        this._loader = e,
        this.enabled = this._loader.isExtensionUsed(NAME$2)
    }
    return i.prototype.dispose = function() {
        this._loader = null
    }
    ,
    i.prototype.loadMaterialPropertiesAsync = function(e, t, r) {
        var n = this;
        return GLTFLoader.LoadExtraAsync(e, t, this.name, function(o, a) {
            if (a) {
                if (!(r instanceof PBRMaterial))
                    throw new Error(o + ": Material type not supported");
                var s = n._loader.loadMaterialPropertiesAsync(e, t, r);
                return r.needAlphaBlending() && (r.forceDepthWrite = !0,
                r.separateCullingPass = !0),
                r.backFaceCulling = r.forceDepthWrite,
                r.twoSidedLighting = !0,
                s
            }
            return null
        })
    }
    ,
    i
}();
GLTFLoader.RegisterExtension(NAME$2, function(i) {
    return new MSFT_minecraftMesh(i)
});
var NAME$1 = "MSFT_sRGBFactors"
  , MSFT_sRGBFactors = function() {
    function i(e) {
        this.name = NAME$1,
        this._loader = e,
        this.enabled = this._loader.isExtensionUsed(NAME$1)
    }
    return i.prototype.dispose = function() {
        this._loader = null
    }
    ,
    i.prototype.loadMaterialPropertiesAsync = function(e, t, r) {
        var n = this;
        return GLTFLoader.LoadExtraAsync(e, t, this.name, function(o, a) {
            if (a) {
                if (!(r instanceof PBRMaterial))
                    throw new Error(o + ": Material type not supported");
                var s = n._loader.loadMaterialPropertiesAsync(e, t, r);
                return r.albedoTexture || r.albedoColor.toLinearSpaceToRef(r.albedoColor),
                r.reflectivityTexture || r.reflectivityColor.toLinearSpaceToRef(r.reflectivityColor),
                s
            }
            return null
        })
    }
    ,
    i
}();
GLTFLoader.RegisterExtension(NAME$1, function(i) {
    return new MSFT_sRGBFactors(i)
});
var NAME = "ExtrasAsMetadata"
  , ExtrasAsMetadata = function() {
    function i(e) {
        this.name = NAME,
        this.enabled = !0,
        this._loader = e
    }
    return i.prototype._assignExtras = function(e, t) {
        if (t.extras && Object.keys(t.extras).length > 0) {
            var r = e.metadata = e.metadata || {}
              , n = r.gltf = r.gltf || {};
            n.extras = t.extras
        }
    }
    ,
    i.prototype.dispose = function() {
        this._loader = null
    }
    ,
    i.prototype.loadNodeAsync = function(e, t, r) {
        var n = this;
        return this._loader.loadNodeAsync(e, t, function(o) {
            n._assignExtras(o, t),
            r(o)
        })
    }
    ,
    i.prototype.loadCameraAsync = function(e, t, r) {
        var n = this;
        return this._loader.loadCameraAsync(e, t, function(o) {
            n._assignExtras(o, t),
            r(o)
        })
    }
    ,
    i.prototype.createMaterial = function(e, t, r) {
        var n = this._loader.createMaterial(e, t, r);
        return this._assignExtras(n, t),
        n
    }
    ,
    i
}();
GLTFLoader.RegisterExtension(NAME, function(i) {
    return new ExtrasAsMetadata(i)
});
var MTLFileLoader = function() {
    function i() {
        this.materials = []
    }
    return i.prototype.parseMTL = function(e, t, r, n) {
        if (!(t instanceof ArrayBuffer)) {
            for (var o = t.split(`
`), a = /\s+/, s, l = null, u = 0; u < o.length; u++) {
                var c = o[u].trim();
                if (!(c.length === 0 || c.charAt(0) === "#")) {
                    var h = c.indexOf(" ")
                      , f = h >= 0 ? c.substring(0, h) : c;
                    f = f.toLowerCase();
                    var d = h >= 0 ? c.substring(h + 1).trim() : "";
                    f === "newmtl" ? (l && this.materials.push(l),
                    e._blockEntityCollection = !!n,
                    l = new StandardMaterial(d,e),
                    l._parentContainer = n,
                    e._blockEntityCollection = !1) : f === "kd" && l ? (s = d.split(a, 3).map(parseFloat),
                    l.diffuseColor = Color3.FromArray(s)) : f === "ka" && l ? (s = d.split(a, 3).map(parseFloat),
                    l.ambientColor = Color3.FromArray(s)) : f === "ks" && l ? (s = d.split(a, 3).map(parseFloat),
                    l.specularColor = Color3.FromArray(s)) : f === "ke" && l ? (s = d.split(a, 3).map(parseFloat),
                    l.emissiveColor = Color3.FromArray(s)) : f === "ns" && l ? l.specularPower = parseFloat(d) : f === "d" && l ? l.alpha = parseFloat(d) : f === "map_ka" && l ? l.ambientTexture = i._getTexture(r, d, e) : f === "map_kd" && l ? l.diffuseTexture = i._getTexture(r, d, e) : f === "map_ks" && l ? l.specularTexture = i._getTexture(r, d, e) : f === "map_ns" || (f === "map_bump" && l ? l.bumpTexture = i._getTexture(r, d, e) : f === "map_d" && l && (l.opacityTexture = i._getTexture(r, d, e)))
                }
            }
            l && this.materials.push(l)
        }
    }
    ,
    i._getTexture = function(e, t, r) {
        if (!t)
            return null;
        var n = e;
        if (e === "file:") {
            var o = t.lastIndexOf("\\");
            o === -1 && (o = t.lastIndexOf("/")),
            o > -1 ? n += t.substr(o + 1) : n += t
        } else
            n += t;
        return new Texture(n,r,!1,i.INVERT_TEXTURE_Y)
    }
    ,
    i.INVERT_TEXTURE_Y = !0,
    i
}()
  , SolidParser = function() {
    function i(e, t, r) {
        this._positions = [],
        this._normals = [],
        this._uvs = [],
        this._colors = [],
        this._meshesFromObj = [],
        this._indicesForBabylon = [],
        this._wrappedPositionForBabylon = [],
        this._wrappedUvsForBabylon = [],
        this._wrappedColorsForBabylon = [],
        this._wrappedNormalsForBabylon = [],
        this._tuplePosNorm = [],
        this._curPositionInIndices = 0,
        this._hasMeshes = !1,
        this._unwrappedPositionsForBabylon = [],
        this._unwrappedColorsForBabylon = [],
        this._unwrappedNormalsForBabylon = [],
        this._unwrappedUVForBabylon = [],
        this._triangles = [],
        this._materialNameFromObj = "",
        this._objMeshName = "",
        this._increment = 1,
        this._isFirstMaterial = !0,
        this._grayColor = new Color4(.5,.5,.5,1),
        this._materialToUse = e,
        this._babylonMeshesArray = t,
        this._loadingOptions = r
    }
    return i.prototype._isInArray = function(e, t) {
        e[t[0]] || (e[t[0]] = {
            normals: [],
            idx: []
        });
        var r = e[t[0]].normals.indexOf(t[1]);
        return r === -1 ? -1 : e[t[0]].idx[r]
    }
    ,
    i.prototype._isInArrayUV = function(e, t) {
        e[t[0]] || (e[t[0]] = {
            normals: [],
            idx: [],
            uv: []
        });
        var r = e[t[0]].normals.indexOf(t[1]);
        return r != 1 && t[2] === e[t[0]].uv[r] ? e[t[0]].idx[r] : -1
    }
    ,
    i.prototype._setData = function(e, t, r, n, o, a, s) {
        var l;
        this._loadingOptions.optimizeWithUV ? l = this._isInArrayUV(this._tuplePosNorm, [e, r, t]) : l = this._isInArray(this._tuplePosNorm, [e, r]),
        l === -1 ? (this._indicesForBabylon.push(this._wrappedPositionForBabylon.length),
        this._wrappedPositionForBabylon.push(n),
        this._wrappedUvsForBabylon.push(o),
        this._wrappedNormalsForBabylon.push(a),
        s !== void 0 && this._wrappedColorsForBabylon.push(s),
        this._tuplePosNorm[e].normals.push(r),
        this._tuplePosNorm[e].idx.push(this._curPositionInIndices++),
        this._loadingOptions.optimizeWithUV && this._tuplePosNorm[e].uv.push(t)) : this._indicesForBabylon.push(l)
    }
    ,
    i.prototype._unwrapData = function() {
        for (var e = 0; e < this._wrappedPositionForBabylon.length; e++)
            this._unwrappedPositionsForBabylon.push(this._wrappedPositionForBabylon[e].x, this._wrappedPositionForBabylon[e].y, this._wrappedPositionForBabylon[e].z),
            this._unwrappedNormalsForBabylon.push(this._wrappedNormalsForBabylon[e].x, this._wrappedNormalsForBabylon[e].y, this._wrappedNormalsForBabylon[e].z),
            this._unwrappedUVForBabylon.push(this._wrappedUvsForBabylon[e].x, this._wrappedUvsForBabylon[e].y),
            this._loadingOptions.importVertexColors && this._unwrappedColorsForBabylon.push(this._wrappedColorsForBabylon[e].r, this._wrappedColorsForBabylon[e].g, this._wrappedColorsForBabylon[e].b, this._wrappedColorsForBabylon[e].a);
        this._wrappedPositionForBabylon = [],
        this._wrappedNormalsForBabylon = [],
        this._wrappedUvsForBabylon = [],
        this._wrappedColorsForBabylon = [],
        this._tuplePosNorm = [],
        this._curPositionInIndices = 0
    }
    ,
    i.prototype._getTriangles = function(e, t) {
        for (var r = t; r < e.length - 1; r++)
            this._triangles.push(e[0], e[r], e[r + 1])
    }
    ,
    i.prototype._setDataForCurrentFaceWithPattern1 = function(e, t) {
        this._getTriangles(e, t);
        for (var r = 0; r < this._triangles.length; r++) {
            var n = parseInt(this._triangles[r]) - 1;
            this._setData(n, 0, 0, this._positions[n], Vector2.Zero(), Vector3.Up(), this._loadingOptions.importVertexColors ? this._colors[n] : void 0)
        }
        this._triangles = []
    }
    ,
    i.prototype._setDataForCurrentFaceWithPattern2 = function(e, t) {
        this._getTriangles(e, t);
        for (var r = 0; r < this._triangles.length; r++) {
            var n = this._triangles[r].split("/")
              , o = parseInt(n[0]) - 1
              , a = parseInt(n[1]) - 1;
            this._setData(o, a, 0, this._positions[o], this._uvs[a], Vector3.Up(), this._loadingOptions.importVertexColors ? this._colors[o] : void 0)
        }
        this._triangles = []
    }
    ,
    i.prototype._setDataForCurrentFaceWithPattern3 = function(e, t) {
        this._getTriangles(e, t);
        for (var r = 0; r < this._triangles.length; r++) {
            var n = this._triangles[r].split("/")
              , o = parseInt(n[0]) - 1
              , a = parseInt(n[1]) - 1
              , s = parseInt(n[2]) - 1;
            this._setData(o, a, s, this._positions[o], this._uvs[a], this._normals[s])
        }
        this._triangles = []
    }
    ,
    i.prototype._setDataForCurrentFaceWithPattern4 = function(e, t) {
        this._getTriangles(e, t);
        for (var r = 0; r < this._triangles.length; r++) {
            var n = this._triangles[r].split("//")
              , o = parseInt(n[0]) - 1
              , a = parseInt(n[1]) - 1;
            this._setData(o, 1, a, this._positions[o], Vector2.Zero(), this._normals[a], this._loadingOptions.importVertexColors ? this._colors[o] : void 0)
        }
        this._triangles = []
    }
    ,
    i.prototype._setDataForCurrentFaceWithPattern5 = function(e, t) {
        this._getTriangles(e, t);
        for (var r = 0; r < this._triangles.length; r++) {
            var n = this._triangles[r].split("/")
              , o = this._positions.length + parseInt(n[0])
              , a = this._uvs.length + parseInt(n[1])
              , s = this._normals.length + parseInt(n[2]);
            this._setData(o, a, s, this._positions[o], this._uvs[a], this._normals[s], this._loadingOptions.importVertexColors ? this._colors[o] : void 0)
        }
        this._triangles = []
    }
    ,
    i.prototype._addPreviousObjMesh = function() {
        this._meshesFromObj.length > 0 && (this._handledMesh = this._meshesFromObj[this._meshesFromObj.length - 1],
        this._unwrapData(),
        this._indicesForBabylon.reverse(),
        this._handledMesh.indices = this._indicesForBabylon.slice(),
        this._handledMesh.positions = this._unwrappedPositionsForBabylon.slice(),
        this._handledMesh.normals = this._unwrappedNormalsForBabylon.slice(),
        this._handledMesh.uvs = this._unwrappedUVForBabylon.slice(),
        this._loadingOptions.importVertexColors && (this._handledMesh.colors = this._unwrappedColorsForBabylon.slice()),
        this._indicesForBabylon = [],
        this._unwrappedPositionsForBabylon = [],
        this._unwrappedColorsForBabylon = [],
        this._unwrappedNormalsForBabylon = [],
        this._unwrappedUVForBabylon = [])
    }
    ,
    i.prototype._optimizeNormals = function(e) {
        var t = e.getVerticesData(VertexBuffer.PositionKind)
          , r = e.getVerticesData(VertexBuffer.NormalKind)
          , n = {};
        if (!(!t || !r)) {
            for (var o = 0; o < t.length / 3; o++) {
                var a = t[o * 3 + 0]
                  , s = t[o * 3 + 1]
                  , l = t[o * 3 + 2]
                  , u = a + "_" + s + "_" + l
                  , c = n[u];
                c || (c = [],
                n[u] = c),
                c.push(o)
            }
            var h = new Vector3;
            for (var u in n) {
                var c = n[u];
                if (!(c.length < 2)) {
                    for (var f = c[0], o = 1; o < c.length; ++o) {
                        var d = c[o];
                        r[f * 3 + 0] += r[d * 3 + 0],
                        r[f * 3 + 1] += r[d * 3 + 1],
                        r[f * 3 + 2] += r[d * 3 + 2]
                    }
                    h.copyFromFloats(r[f * 3 + 0], r[f * 3 + 1], r[f * 3 + 2]),
                    h.normalize();
                    for (var o = 0; o < c.length; ++o) {
                        var d = c[o];
                        r[d * 3 + 0] = h.x,
                        r[d * 3 + 1] = h.y,
                        r[d * 3 + 2] = h.z
                    }
                }
            }
            e.setVerticesData(VertexBuffer.NormalKind, r)
        }
    }
    ,
    i.prototype.parse = function(e, t, r, n, o) {
        for (var a, s = t.split(`
`), l = 0; l < s.length; l++) {
            var u = s[l].trim().replace(/\s\s/g, " "), c;
            if (!(u.length === 0 || u.charAt(0) === "#"))
                if (i.VertexPattern.test(u)) {
                    if (c = u.match(/[^ ]+/g),
                    this._positions.push(new Vector3(parseFloat(c[1]),parseFloat(c[2]),parseFloat(c[3]))),
                    this._loadingOptions.importVertexColors)
                        if (c.length >= 7) {
                            var h = parseFloat(c[4])
                              , f = parseFloat(c[5])
                              , d = parseFloat(c[6]);
                            this._colors.push(new Color4(h > 1 ? h / 255 : h,f > 1 ? f / 255 : f,d > 1 ? d / 255 : d,c.length === 7 || c[7] === void 0 ? 1 : parseFloat(c[7])))
                        } else
                            this._colors.push(this._grayColor)
                } else if ((c = i.NormalPattern.exec(u)) !== null)
                    this._normals.push(new Vector3(parseFloat(c[1]),parseFloat(c[2]),parseFloat(c[3])));
                else if ((c = i.UVPattern.exec(u)) !== null)
                    this._uvs.push(new Vector2(parseFloat(c[1]) * this._loadingOptions.UVScaling.x,parseFloat(c[2]) * this._loadingOptions.UVScaling.y));
                else if ((c = i.FacePattern3.exec(u)) !== null)
                    this._setDataForCurrentFaceWithPattern3(c[1].trim().split(" "), 1);
                else if ((c = i.FacePattern4.exec(u)) !== null)
                    this._setDataForCurrentFaceWithPattern4(c[1].trim().split(" "), 1);
                else if ((c = i.FacePattern5.exec(u)) !== null)
                    this._setDataForCurrentFaceWithPattern5(c[1].trim().split(" "), 1);
                else if ((c = i.FacePattern2.exec(u)) !== null)
                    this._setDataForCurrentFaceWithPattern2(c[1].trim().split(" "), 1);
                else if ((c = i.FacePattern1.exec(u)) !== null)
                    this._setDataForCurrentFaceWithPattern1(c[1].trim().split(" "), 1);
                else if (i.GroupDescriptor.test(u) || i.ObjectDescriptor.test(u)) {
                    var _ = {
                        name: u.substring(2).trim(),
                        indices: void 0,
                        positions: void 0,
                        normals: void 0,
                        uvs: void 0,
                        colors: void 0,
                        materialName: ""
                    };
                    this._addPreviousObjMesh(),
                    this._meshesFromObj.push(_),
                    this._hasMeshes = !0,
                    this._isFirstMaterial = !0,
                    this._increment = 1
                } else if (i.UseMtlDescriptor.test(u)) {
                    if (this._materialNameFromObj = u.substring(7).trim(),
                    !this._isFirstMaterial || !this._hasMeshes) {
                        this._addPreviousObjMesh();
                        var _ = {
                            name: (this._objMeshName || "mesh") + "_mm" + this._increment.toString(),
                            indices: void 0,
                            positions: void 0,
                            normals: void 0,
                            uvs: void 0,
                            colors: void 0,
                            materialName: this._materialNameFromObj
                        };
                        this._increment++,
                        this._meshesFromObj.push(_),
                        this._hasMeshes = !0
                    }
                    this._hasMeshes && this._isFirstMaterial && (this._meshesFromObj[this._meshesFromObj.length - 1].materialName = this._materialNameFromObj,
                    this._isFirstMaterial = !1)
                } else
                    i.MtlLibGroupDescriptor.test(u) ? o(u.substring(7).trim()) : i.SmoothDescriptor.test(u) || console.log("Unhandled expression at line : " + u)
        }
        if (this._hasMeshes && (this._handledMesh = this._meshesFromObj[this._meshesFromObj.length - 1],
        this._indicesForBabylon.reverse(),
        this._unwrapData(),
        this._handledMesh.indices = this._indicesForBabylon,
        this._handledMesh.positions = this._unwrappedPositionsForBabylon,
        this._handledMesh.normals = this._unwrappedNormalsForBabylon,
        this._handledMesh.uvs = this._unwrappedUVForBabylon,
        this._loadingOptions.importVertexColors && (this._handledMesh.colors = this._unwrappedColorsForBabylon)),
        !this._hasMeshes) {
            var g = null;
            if (this._indicesForBabylon.length)
                this._indicesForBabylon.reverse(),
                this._unwrapData();
            else {
                for (var m = 0, v = this._positions; m < v.length; m++) {
                    var y = v[m];
                    this._unwrappedPositionsForBabylon.push(y.x, y.y, y.z)
                }
                if (this._normals.length)
                    for (var b = 0, T = this._normals; b < T.length; b++) {
                        var C = T[b];
                        this._unwrappedNormalsForBabylon.push(C.x, C.y, C.z)
                    }
                if (this._uvs.length)
                    for (var A = 0, S = this._uvs; A < S.length; A++) {
                        var P = S[A];
                        this._unwrappedUVForBabylon.push(P.x, P.y)
                    }
                if (this._colors.length)
                    for (var R = 0, M = this._colors; R < M.length; R++) {
                        var x = M[R];
                        this._unwrappedColorsForBabylon.push(x.r, x.g, x.b, x.a)
                    }
                this._materialNameFromObj || (g = new StandardMaterial(Geometry.RandomId(),r),
                g.pointsCloud = !0,
                this._materialNameFromObj = g.name,
                this._normals.length || (g.disableLighting = !0,
                g.emissiveColor = Color3.White()))
            }
            this._meshesFromObj.push({
                name: Geometry.RandomId(),
                indices: this._indicesForBabylon,
                positions: this._unwrappedPositionsForBabylon,
                colors: this._unwrappedColorsForBabylon,
                normals: this._unwrappedNormalsForBabylon,
                uvs: this._unwrappedUVForBabylon,
                materialName: this._materialNameFromObj,
                directMaterial: g
            })
        }
        for (var I = 0; I < this._meshesFromObj.length; I++) {
            if (e && this._meshesFromObj[I].name) {
                if (e instanceof Array) {
                    if (e.indexOf(this._meshesFromObj[I].name) === -1)
                        continue
                } else if (this._meshesFromObj[I].name !== e)
                    continue
            }
            this._handledMesh = this._meshesFromObj[I],
            r._blockEntityCollection = !!n;
            var w = new Mesh(this._meshesFromObj[I].name,r);
            if (w._parentContainer = n,
            r._blockEntityCollection = !1,
            this._materialToUse.push(this._meshesFromObj[I].materialName),
            ((a = this._handledMesh.positions) === null || a === void 0 ? void 0 : a.length) === 0) {
                this._babylonMeshesArray.push(w);
                continue
            }
            var O = new VertexData;
            if (O.uvs = this._handledMesh.uvs,
            O.indices = this._handledMesh.indices,
            O.positions = this._handledMesh.positions,
            this._loadingOptions.computeNormals) {
                var D = new Array;
                VertexData.ComputeNormals(this._handledMesh.positions, this._handledMesh.indices, D),
                O.normals = D
            } else
                O.normals = this._handledMesh.normals;
            this._loadingOptions.importVertexColors && (O.colors = this._handledMesh.colors),
            O.applyToMesh(w),
            this._loadingOptions.invertY && (w.scaling.y *= -1),
            this._loadingOptions.optimizeNormals && this._optimizeNormals(w),
            this._babylonMeshesArray.push(w),
            this._handledMesh.directMaterial && (w.material = this._handledMesh.directMaterial)
        }
    }
    ,
    i.ObjectDescriptor = /^o/,
    i.GroupDescriptor = /^g/,
    i.MtlLibGroupDescriptor = /^mtllib /,
    i.UseMtlDescriptor = /^usemtl /,
    i.SmoothDescriptor = /^s /,
    i.VertexPattern = /v(\s+[\d|\.|\+|\-|e|E]+){3,7}/,
    i.NormalPattern = /vn(\s+[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/,
    i.UVPattern = /vt(\s+[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/,
    i.FacePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/,
    i.FacePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/,
    i.FacePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/,
    i.FacePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/,
    i.FacePattern5 = /f\s+(((-[\d]{1,}\/-[\d]{1,}\/-[\d]{1,}[\s]?){3,})+)/,
    i
}()
  , OBJFileLoader = function() {
    function i(e) {
        this.name = "obj",
        this.extensions = ".obj",
        this._assetContainer = null,
        this._loadingOptions = e || i.DefaultLoadingOptions
    }
    return Object.defineProperty(i, "INVERT_TEXTURE_Y", {
        get: function() {
            return MTLFileLoader.INVERT_TEXTURE_Y
        },
        set: function(e) {
            MTLFileLoader.INVERT_TEXTURE_Y = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i, "DefaultLoadingOptions", {
        get: function() {
            return {
                computeNormals: i.COMPUTE_NORMALS,
                optimizeNormals: i.OPTIMIZE_NORMALS,
                importVertexColors: i.IMPORT_VERTEX_COLORS,
                invertY: i.INVERT_Y,
                invertTextureY: i.INVERT_TEXTURE_Y,
                UVScaling: i.UV_SCALING,
                materialLoadingFailsSilently: i.MATERIAL_LOADING_FAILS_SILENTLY,
                optimizeWithUV: i.OPTIMIZE_WITH_UV,
                skipMaterials: i.SKIP_MATERIALS
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype._loadMTL = function(e, t, r, n) {
        var o = t + e;
        Tools.LoadFile(o, r, void 0, void 0, !1, function(a, s) {
            n(o, s)
        })
    }
    ,
    i.prototype.createPlugin = function() {
        return new i(i.DefaultLoadingOptions)
    }
    ,
    i.prototype.canDirectLoad = function(e) {
        return !1
    }
    ,
    i.prototype.importMeshAsync = function(e, t, r, n, o, a) {
        return this._parseSolid(e, t, r, n).then(function(s) {
            return {
                meshes: s,
                particleSystems: [],
                skeletons: [],
                animationGroups: [],
                transformNodes: [],
                geometries: [],
                lights: []
            }
        })
    }
    ,
    i.prototype.loadAsync = function(e, t, r, n, o) {
        return this.importMeshAsync(null, e, t, r, n).then(function() {})
    }
    ,
    i.prototype.loadAssetContainerAsync = function(e, t, r, n, o) {
        var a = this
          , s = new AssetContainer(e);
        return this._assetContainer = s,
        this.importMeshAsync(null, e, t, r).then(function(l) {
            return l.meshes.forEach(function(u) {
                return s.meshes.push(u)
            }),
            l.meshes.forEach(function(u) {
                var c = u.material;
                if (c && s.materials.indexOf(c) == -1) {
                    s.materials.push(c);
                    var h = c.getActiveTextures();
                    h.forEach(function(f) {
                        s.textures.indexOf(f) == -1 && s.textures.push(f)
                    })
                }
            }),
            a._assetContainer = null,
            s
        }).catch(function(l) {
            throw a._assetContainer = null,
            l
        })
    }
    ,
    i.prototype._parseSolid = function(e, t, r, n) {
        var o = this
          , a = ""
          , s = new MTLFileLoader
          , l = new Array
          , u = []
          , c = new SolidParser(l,u,this._loadingOptions);
        c.parse(e, r, t, this._assetContainer, function(f) {
            a = f
        });
        var h = [];
        return a !== "" && !this._loadingOptions.skipMaterials && h.push(new Promise(function(f, d) {
            o._loadMTL(a, n, function(_) {
                try {
                    s.parseMTL(t, _, n, o._assetContainer);
                    for (var g = 0; g < s.materials.length; g++) {
                        for (var m = 0, v = [], y; (y = l.indexOf(s.materials[g].name, m)) > -1; )
                            v.push(y),
                            m = y + 1;
                        if (y === -1 && v.length === 0)
                            s.materials[g].dispose();
                        else
                            for (var b = 0; b < v.length; b++) {
                                var T = u[v[b]]
                                  , C = s.materials[g];
                                T.material = C,
                                T.getTotalIndices() || (C.pointsCloud = !0)
                            }
                    }
                    f()
                } catch (A) {
                    Tools.Warn("Error processing MTL file: '" + a + "'"),
                    o._loadingOptions.materialLoadingFailsSilently ? f() : d(A)
                }
            }, function(_, g) {
                Tools.Warn("Error downloading MTL file: '" + a + "'"),
                o._loadingOptions.materialLoadingFailsSilently ? f() : d(g)
            })
        }
        )),
        Promise.all(h).then(function() {
            return u
        })
    }
    ,
    i.OPTIMIZE_WITH_UV = !0,
    i.INVERT_Y = !1,
    i.IMPORT_VERTEX_COLORS = !1,
    i.COMPUTE_NORMALS = !1,
    i.OPTIMIZE_NORMALS = !1,
    i.UV_SCALING = new Vector2(1,1),
    i.SKIP_MATERIALS = !1,
    i.MATERIAL_LOADING_FAILS_SILENTLY = !0,
    i
}();
SceneLoader && SceneLoader.RegisterPlugin(new OBJFileLoader);
var STLFileLoader = function() {
    function i() {
        this.solidPattern = /solid (\S*)([\S\s]*?)endsolid[ ]*(\S*)/g,
        this.facetsPattern = /facet([\s\S]*?)endfacet/g,
        this.normalPattern = /normal[\s]+([\-+]?[0-9]+\.?[0-9]*([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+/g,
        this.vertexPattern = /vertex[\s]+([\-+]?[0-9]+\.?[0-9]*([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+/g,
        this.name = "stl",
        this.extensions = {
            ".stl": {
                isBinary: !0
            }
        }
    }
    return i.prototype.importMesh = function(e, t, r, n, o, a, s) {
        var l;
        if (typeof r != "string") {
            if (this._isBinary(r)) {
                var u = new Mesh("stlmesh",t);
                return this._parseBinary(u, r),
                o && o.push(u),
                !0
            }
            for (var c = new Uint8Array(r), h = "", f = 0; f < r.byteLength; f++)
                h += String.fromCharCode(c[f]);
            r = h
        }
        for (; l = this.solidPattern.exec(r); ) {
            var d = l[1]
              , _ = l[3];
            if (d != _)
                return Tools.Error("Error in STL, solid name != endsolid name"),
                !1;
            if (e && d) {
                if (e instanceof Array) {
                    if (!e.indexOf(d))
                        continue
                } else if (d !== e)
                    continue
            }
            d = d || "stlmesh";
            var u = new Mesh(d,t);
            this._parseASCII(u, l[2]),
            o && o.push(u)
        }
        return !0
    }
    ,
    i.prototype.load = function(e, t, r) {
        var n = this.importMesh(null, e, t, r, null, null, null);
        return n
    }
    ,
    i.prototype.loadAssetContainer = function(e, t, r, n) {
        var o = new AssetContainer(e);
        return e._blockEntityCollection = !0,
        this.importMesh(null, e, t, r, o.meshes, null, null),
        e._blockEntityCollection = !1,
        o
    }
    ,
    i.prototype._isBinary = function(e) {
        var t, r, n;
        if (n = new DataView(e),
        n.byteLength <= 80)
            return !1;
        if (t = 32 / 8 * 3 + 32 / 8 * 3 * 3 + 16 / 8,
        r = n.getUint32(80, !0),
        80 + 32 / 8 + r * t === n.byteLength)
            return !0;
        for (var o = n.byteLength, a = 0; a < o; a++)
            if (n.getUint8(a) > 127)
                return !0;
        return !1
    }
    ,
    i.prototype._parseBinary = function(e, t) {
        for (var r = new DataView(t), n = r.getUint32(80, !0), o = 84, a = 12 * 4 + 2, s = 0, l = new Float32Array(n * 3 * 3), u = new Float32Array(n * 3 * 3), c = new Uint32Array(n * 3), h = 0, f = 0; f < n; f++) {
            for (var d = o + f * a, _ = r.getFloat32(d, !0), g = r.getFloat32(d + 4, !0), m = r.getFloat32(d + 8, !0), v = 1; v <= 3; v++) {
                var y = d + v * 12;
                l[s] = r.getFloat32(y, !0),
                u[s] = _,
                i.DO_NOT_ALTER_FILE_COORDINATES ? (l[s + 1] = r.getFloat32(y + 4, !0),
                l[s + 2] = r.getFloat32(y + 8, !0),
                u[s + 1] = g,
                u[s + 2] = m) : (l[s + 2] = r.getFloat32(y + 4, !0),
                l[s + 1] = r.getFloat32(y + 8, !0),
                u[s + 2] = g,
                u[s + 1] = m),
                s += 3
            }
            c[h] = h++,
            c[h] = h++,
            c[h] = h++
        }
        e.setVerticesData(VertexBuffer.PositionKind, l),
        e.setVerticesData(VertexBuffer.NormalKind, u),
        e.setIndices(c),
        e.computeWorldMatrix(!0)
    }
    ,
    i.prototype._parseASCII = function(e, t) {
        for (var r = [], n = [], o = [], a = 0, s; s = this.facetsPattern.exec(t); ) {
            var l = s[1]
              , u = this.normalPattern.exec(l);
            if (this.normalPattern.lastIndex = 0,
            !!u) {
                for (var c = [Number(u[1]), Number(u[5]), Number(u[3])], h; h = this.vertexPattern.exec(l); )
                    i.DO_NOT_ALTER_FILE_COORDINATES ? (r.push(Number(h[1]), Number(h[3]), Number(h[5])),
                    n.push(c[0], c[2], c[1])) : (r.push(Number(h[1]), Number(h[5]), Number(h[3])),
                    n.push(c[0], c[1], c[2]));
                o.push(a++, a++, a++),
                this.vertexPattern.lastIndex = 0
            }
        }
        this.facetsPattern.lastIndex = 0,
        e.setVerticesData(VertexBuffer.PositionKind, r),
        e.setVerticesData(VertexBuffer.NormalKind, n),
        e.setIndices(o),
        e.computeWorldMatrix(!0)
    }
    ,
    i.DO_NOT_ALTER_FILE_COORDINATES = !1,
    i
}();
SceneLoader && SceneLoader.RegisterPlugin(new STLFileLoader);
var SoundTrack = function() {
    function i(e, t) {
        t === void 0 && (t = {}),
        this.id = -1,
        this._isInitialized = !1,
        this._scene = e,
        this.soundCollection = new Array,
        this._options = t,
        !this._options.mainTrack && this._scene.soundTracks && (this._scene.soundTracks.push(this),
        this.id = this._scene.soundTracks.length - 1)
    }
    return i.prototype._initializeSoundTrackAudioGraph = function() {
        var e;
        ((e = Engine.audioEngine) === null || e === void 0 ? void 0 : e.canUseWebAudio) && Engine.audioEngine.audioContext && (this._outputAudioNode = Engine.audioEngine.audioContext.createGain(),
        this._outputAudioNode.connect(Engine.audioEngine.masterGain),
        this._options && this._options.volume && (this._outputAudioNode.gain.value = this._options.volume),
        this._isInitialized = !0)
    }
    ,
    i.prototype.dispose = function() {
        if (Engine.audioEngine && Engine.audioEngine.canUseWebAudio) {
            for (this._connectedAnalyser && this._connectedAnalyser.stopDebugCanvas(); this.soundCollection.length; )
                this.soundCollection[0].dispose();
            this._outputAudioNode && this._outputAudioNode.disconnect(),
            this._outputAudioNode = null
        }
    }
    ,
    i.prototype.addSound = function(e) {
        var t;
        this._isInitialized || this._initializeSoundTrackAudioGraph(),
        ((t = Engine.audioEngine) === null || t === void 0 ? void 0 : t.canUseWebAudio) && this._outputAudioNode && e.connectToSoundTrackAudioNode(this._outputAudioNode),
        e.soundTrackId && (e.soundTrackId === -1 ? this._scene.mainSoundTrack.removeSound(e) : this._scene.soundTracks && this._scene.soundTracks[e.soundTrackId].removeSound(e)),
        this.soundCollection.push(e),
        e.soundTrackId = this.id
    }
    ,
    i.prototype.removeSound = function(e) {
        var t = this.soundCollection.indexOf(e);
        t !== -1 && this.soundCollection.splice(t, 1)
    }
    ,
    i.prototype.setVolume = function(e) {
        var t;
        ((t = Engine.audioEngine) === null || t === void 0 ? void 0 : t.canUseWebAudio) && this._outputAudioNode && (this._outputAudioNode.gain.value = e)
    }
    ,
    i.prototype.switchPanningModelToHRTF = function() {
        var e;
        if (!((e = Engine.audioEngine) === null || e === void 0) && e.canUseWebAudio)
            for (var t = 0; t < this.soundCollection.length; t++)
                this.soundCollection[t].switchPanningModelToHRTF()
    }
    ,
    i.prototype.switchPanningModelToEqualPower = function() {
        var e;
        if (!((e = Engine.audioEngine) === null || e === void 0) && e.canUseWebAudio)
            for (var t = 0; t < this.soundCollection.length; t++)
                this.soundCollection[t].switchPanningModelToEqualPower()
    }
    ,
    i.prototype.connectToAnalyser = function(e) {
        var t;
        this._connectedAnalyser && this._connectedAnalyser.stopDebugCanvas(),
        this._connectedAnalyser = e,
        ((t = Engine.audioEngine) === null || t === void 0 ? void 0 : t.canUseWebAudio) && this._outputAudioNode && (this._outputAudioNode.disconnect(),
        this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, Engine.audioEngine.masterGain))
    }
    ,
    i
}();
Engine.AudioEngineFactory = function(i, e, t) {
    return new AudioEngine(i,e,t)
}
;
var AudioEngine = function() {
    function i(e, t, r) {
        var n = this;
        if (e === void 0 && (e = null),
        t === void 0 && (t = null),
        r === void 0 && (r = null),
        this._audioContext = null,
        this._audioContextInitialized = !1,
        this._muteButton = null,
        this._audioDestination = null,
        this.canUseWebAudio = !1,
        this.WarnedWebAudioUnsupported = !1,
        this.isMP3supported = !1,
        this.isOGGsupported = !1,
        this.unlocked = !0,
        this.useCustomUnlockedButton = !1,
        this.onAudioUnlockedObservable = new Observable,
        this.onAudioLockedObservable = new Observable,
        this._tryToRun = !1,
        this._onResize = function() {
            n._moveButtonToTopLeft()
        }
        ,
        !!IsWindowObjectExist()) {
            (typeof window.AudioContext != "undefined" || typeof window.webkitAudioContext != "undefined") && (window.AudioContext = window.AudioContext || window.webkitAudioContext,
            this.canUseWebAudio = !0);
            var o = document.createElement("audio");
            this._hostElement = e,
            this._audioContext = t,
            this._audioDestination = r;
            try {
                o && !!o.canPlayType && (o.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, "") || o.canPlayType("audio/mp3").replace(/^no$/, "")) && (this.isMP3supported = !0)
            } catch {}
            try {
                o && !!o.canPlayType && o.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, "") && (this.isOGGsupported = !0)
            } catch {}
        }
    }
    return Object.defineProperty(i.prototype, "audioContext", {
        get: function() {
            return this._audioContextInitialized ? !this.unlocked && !this._muteButton && this._displayMuteButton() : this._initializeAudioContext(),
            this._audioContext
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.lock = function() {
        this._triggerSuspendedState()
    }
    ,
    i.prototype.unlock = function() {
        this._triggerRunningState()
    }
    ,
    i.prototype._resumeAudioContext = function() {
        var e;
        return this._audioContext.resume !== void 0 && (e = this._audioContext.resume()),
        e || Promise.resolve()
    }
    ,
    i.prototype._initializeAudioContext = function() {
        try {
            this.canUseWebAudio && (this._audioContext || (this._audioContext = new AudioContext),
            this.masterGain = this._audioContext.createGain(),
            this.masterGain.gain.value = 1,
            this._audioDestination || (this._audioDestination = this._audioContext.destination),
            this.masterGain.connect(this._audioDestination),
            this._audioContextInitialized = !0,
            this._audioContext.state === "running" && this._triggerRunningState())
        } catch (e) {
            this.canUseWebAudio = !1,
            Logger$2.Error("Web Audio: " + e.message)
        }
    }
    ,
    i.prototype._triggerRunningState = function() {
        var e = this;
        this._tryToRun || (this._tryToRun = !0,
        this._resumeAudioContext().then(function() {
            e._tryToRun = !1,
            e._muteButton && e._hideMuteButton(),
            e.unlocked = !0,
            e.onAudioUnlockedObservable.notifyObservers(e)
        }).catch(function() {
            e._tryToRun = !1,
            e.unlocked = !1
        }))
    }
    ,
    i.prototype._triggerSuspendedState = function() {
        this.unlocked = !1,
        this.onAudioLockedObservable.notifyObservers(this),
        this._displayMuteButton()
    }
    ,
    i.prototype._displayMuteButton = function() {
        var e = this;
        if (!(this.useCustomUnlockedButton || this._muteButton)) {
            this._muteButton = document.createElement("BUTTON"),
            this._muteButton.className = "babylonUnmuteIcon",
            this._muteButton.id = "babylonUnmuteIconBtn",
            this._muteButton.title = "Unmute";
            var t = window.SVGSVGElement ? "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" : "https://cdn.babylonjs.com/Assets/audio.png"
              , r = ".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url(" + t + ");  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) }"
              , n = document.createElement("style");
            n.appendChild(document.createTextNode(r)),
            document.getElementsByTagName("head")[0].appendChild(n),
            document.body.appendChild(this._muteButton),
            this._moveButtonToTopLeft(),
            this._muteButton.addEventListener("touchend", function() {
                e._triggerRunningState()
            }, !0),
            this._muteButton.addEventListener("click", function() {
                e._triggerRunningState()
            }, !0),
            window.addEventListener("resize", this._onResize)
        }
    }
    ,
    i.prototype._moveButtonToTopLeft = function() {
        this._hostElement && this._muteButton && (this._muteButton.style.top = this._hostElement.offsetTop + 20 + "px",
        this._muteButton.style.left = this._hostElement.offsetLeft + 20 + "px")
    }
    ,
    i.prototype._hideMuteButton = function() {
        this._muteButton && (document.body.removeChild(this._muteButton),
        this._muteButton = null)
    }
    ,
    i.prototype.dispose = function() {
        this.canUseWebAudio && this._audioContextInitialized && (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 = !1,
        this._hideMuteButton(),
        window.removeEventListener("resize", this._onResize),
        this.onAudioUnlockedObservable.clear(),
        this.onAudioLockedObservable.clear()
    }
    ,
    i.prototype.getGlobalVolume = function() {
        return this.canUseWebAudio && this._audioContextInitialized ? this.masterGain.gain.value : -1
    }
    ,
    i.prototype.setGlobalVolume = function(e) {
        this.canUseWebAudio && this._audioContextInitialized && (this.masterGain.gain.value = e)
    }
    ,
    i.prototype.connectToAnalyser = function(e) {
        this._connectedAnalyser && this._connectedAnalyser.stopDebugCanvas(),
        this.canUseWebAudio && this._audioContextInitialized && this._audioContext && (this._connectedAnalyser = e,
        this.masterGain.disconnect(),
        this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination))
    }
    ,
    i
}();
AbstractScene.AddParser(SceneComponentConstants.NAME_AUDIO, function(i, e, t, r) {
    var n, o = [], a;
    if (t.sounds = t.sounds || [],
    i.sounds !== void 0 && i.sounds !== null)
        for (var s = 0, l = i.sounds.length; s < l; s++) {
            var u = i.sounds[s];
            !((n = Engine.audioEngine) === null || n === void 0) && n.canUseWebAudio ? (u.url || (u.url = u.name),
            o[u.url] ? t.sounds.push(Sound.Parse(u, e, r, o[u.url])) : (a = Sound.Parse(u, e, r),
            o[u.url] = a,
            t.sounds.push(a))) : t.sounds.push(new Sound(u.name,null,e))
        }
    o = []
});
Object.defineProperty(Scene.prototype, "mainSoundTrack", {
    get: function() {
        var i = this._getComponent(SceneComponentConstants.NAME_AUDIO);
        return i || (i = new AudioSceneComponent(this),
        this._addComponent(i)),
        this._mainSoundTrack || (this._mainSoundTrack = new SoundTrack(this,{
            mainTrack: !0
        })),
        this._mainSoundTrack
    },
    enumerable: !0,
    configurable: !0
});
Scene.prototype.getSoundByName = function(i) {
    var e;
    for (e = 0; e < this.mainSoundTrack.soundCollection.length; e++)
        if (this.mainSoundTrack.soundCollection[e].name === i)
            return this.mainSoundTrack.soundCollection[e];
    if (this.soundTracks) {
        for (var t = 0; t < this.soundTracks.length; t++)
            for (e = 0; e < this.soundTracks[t].soundCollection.length; e++)
                if (this.soundTracks[t].soundCollection[e].name === i)
                    return this.soundTracks[t].soundCollection[e]
    }
    return null
}
;
Object.defineProperty(Scene.prototype, "audioEnabled", {
    get: function() {
        var i = this._getComponent(SceneComponentConstants.NAME_AUDIO);
        return i || (i = new AudioSceneComponent(this),
        this._addComponent(i)),
        i.audioEnabled
    },
    set: function(i) {
        var e = this._getComponent(SceneComponentConstants.NAME_AUDIO);
        e || (e = new AudioSceneComponent(this),
        this._addComponent(e)),
        i ? e.enableAudio() : e.disableAudio()
    },
    enumerable: !0,
    configurable: !0
});
Object.defineProperty(Scene.prototype, "headphone", {
    get: function() {
        var i = this._getComponent(SceneComponentConstants.NAME_AUDIO);
        return i || (i = new AudioSceneComponent(this),
        this._addComponent(i)),
        i.headphone
    },
    set: function(i) {
        var e = this._getComponent(SceneComponentConstants.NAME_AUDIO);
        e || (e = new AudioSceneComponent(this),
        this._addComponent(e)),
        i ? e.switchAudioModeForHeadphones() : e.switchAudioModeForNormalSpeakers()
    },
    enumerable: !0,
    configurable: !0
});
Object.defineProperty(Scene.prototype, "audioListenerPositionProvider", {
    get: function() {
        var i = this._getComponent(SceneComponentConstants.NAME_AUDIO);
        return i || (i = new AudioSceneComponent(this),
        this._addComponent(i)),
        i.audioListenerPositionProvider
    },
    set: function(i) {
        var e = this._getComponent(SceneComponentConstants.NAME_AUDIO);
        if (e || (e = new AudioSceneComponent(this),
        this._addComponent(e)),
        typeof i != "function")
            throw new Error("The value passed to [Scene.audioListenerPositionProvider] must be a function that returns a Vector3");
        e.audioListenerPositionProvider = i
    },
    enumerable: !0,
    configurable: !0
});
Object.defineProperty(Scene.prototype, "audioPositioningRefreshRate", {
    get: function() {
        var i = this._getComponent(SceneComponentConstants.NAME_AUDIO);
        return i || (i = new AudioSceneComponent(this),
        this._addComponent(i)),
        i.audioPositioningRefreshRate
    },
    set: function(i) {
        var e = this._getComponent(SceneComponentConstants.NAME_AUDIO);
        e || (e = new AudioSceneComponent(this),
        this._addComponent(e)),
        e.audioPositioningRefreshRate = i
    },
    enumerable: !0,
    configurable: !0
});
var AudioSceneComponent = function() {
    function i(e) {
        this.name = SceneComponentConstants.NAME_AUDIO,
        this._audioEnabled = !0,
        this._headphone = !1,
        this.audioPositioningRefreshRate = 500,
        this._audioListenerPositionProvider = null,
        this._cachedCameraDirection = new Vector3,
        this._cachedCameraPosition = new Vector3,
        this._lastCheck = 0,
        this.scene = e,
        e.soundTracks = new Array,
        e.sounds = new Array
    }
    return Object.defineProperty(i.prototype, "audioEnabled", {
        get: function() {
            return this._audioEnabled
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "headphone", {
        get: function() {
            return this._headphone
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "audioListenerPositionProvider", {
        get: function() {
            return this._audioListenerPositionProvider
        },
        set: function(e) {
            this._audioListenerPositionProvider = e
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.register = function() {
        this.scene._afterRenderStage.registerStep(SceneComponentConstants.STEP_AFTERRENDER_AUDIO, this, this._afterRender)
    }
    ,
    i.prototype.rebuild = function() {}
    ,
    i.prototype.serialize = function(e) {
        if (e.sounds = [],
        this.scene.soundTracks)
            for (var t = 0; t < this.scene.soundTracks.length; t++)
                for (var r = this.scene.soundTracks[t], n = 0; n < r.soundCollection.length; n++)
                    e.sounds.push(r.soundCollection[n].serialize())
    }
    ,
    i.prototype.addFromContainer = function(e) {
        var t = this;
        !e.sounds || e.sounds.forEach(function(r) {
            r.play(),
            r.autoplay = !0,
            t.scene.mainSoundTrack.addSound(r)
        })
    }
    ,
    i.prototype.removeFromContainer = function(e, t) {
        var r = this;
        t === void 0 && (t = !1),
        e.sounds && e.sounds.forEach(function(n) {
            n.stop(),
            n.autoplay = !1,
            r.scene.mainSoundTrack.removeSound(n),
            t && n.dispose()
        })
    }
    ,
    i.prototype.dispose = function() {
        var e = this.scene;
        if (e._mainSoundTrack && e.mainSoundTrack.dispose(),
        e.soundTracks)
            for (var t = 0; t < e.soundTracks.length; t++)
                e.soundTracks[t].dispose()
    }
    ,
    i.prototype.disableAudio = function() {
        var e = this.scene;
        this._audioEnabled = !1,
        Engine.audioEngine && Engine.audioEngine.audioContext && Engine.audioEngine.audioContext.suspend();
        var t;
        for (t = 0; t < e.mainSoundTrack.soundCollection.length; t++)
            e.mainSoundTrack.soundCollection[t].pause();
        if (e.soundTracks)
            for (t = 0; t < e.soundTracks.length; t++)
                for (var r = 0; r < e.soundTracks[t].soundCollection.length; r++)
                    e.soundTracks[t].soundCollection[r].pause()
    }
    ,
    i.prototype.enableAudio = function() {
        var e = this.scene;
        this._audioEnabled = !0,
        Engine.audioEngine && Engine.audioEngine.audioContext && Engine.audioEngine.audioContext.resume();
        var t;
        for (t = 0; t < e.mainSoundTrack.soundCollection.length; t++)
            e.mainSoundTrack.soundCollection[t].isPaused && e.mainSoundTrack.soundCollection[t].play();
        if (e.soundTracks)
            for (t = 0; t < e.soundTracks.length; t++)
                for (var r = 0; r < e.soundTracks[t].soundCollection.length; r++)
                    e.soundTracks[t].soundCollection[r].isPaused && e.soundTracks[t].soundCollection[r].play()
    }
    ,
    i.prototype.switchAudioModeForHeadphones = function() {
        var e = this.scene;
        if (this._headphone = !0,
        e.mainSoundTrack.switchPanningModelToHRTF(),
        e.soundTracks)
            for (var t = 0; t < e.soundTracks.length; t++)
                e.soundTracks[t].switchPanningModelToHRTF()
    }
    ,
    i.prototype.switchAudioModeForNormalSpeakers = function() {
        var e = this.scene;
        if (this._headphone = !1,
        e.mainSoundTrack.switchPanningModelToEqualPower(),
        e.soundTracks)
            for (var t = 0; t < e.soundTracks.length; t++)
                e.soundTracks[t].switchPanningModelToEqualPower()
    }
    ,
    i.prototype._afterRender = function() {
        var e = PrecisionDate.Now;
        if (!(this._lastCheck && e - this._lastCheck < this.audioPositioningRefreshRate)) {
            this._lastCheck = e;
            var t = this.scene;
            if (!(!this._audioEnabled || !t._mainSoundTrack || !t.soundTracks || t._mainSoundTrack.soundCollection.length === 0 && t.soundTracks.length === 1)) {
                var r = Engine.audioEngine;
                if (!!r && r.audioContext) {
                    if (this._audioListenerPositionProvider) {
                        var n = this._audioListenerPositionProvider();
                        n.x = n.x || 0,
                        n.y = n.y || 0,
                        n.z = n.z || 0,
                        r.audioContext.listener.setPosition(n.x, n.y, n.z)
                    } else {
                        var o;
                        if (t.activeCameras && t.activeCameras.length > 0 ? o = t.activeCameras[0] : o = t.activeCamera,
                        o) {
                            this._cachedCameraPosition.equals(o.globalPosition) || (this._cachedCameraPosition.copyFrom(o.globalPosition),
                            r.audioContext.listener.setPosition(o.globalPosition.x, o.globalPosition.y, o.globalPosition.z)),
                            o.rigCameras && o.rigCameras.length > 0 && (o = o.rigCameras[0]);
                            var a = Matrix.Invert(o.getViewMatrix())
                              , s = Vector3.TransformNormal(i._CameraDirection, a);
                            s.normalize(),
                            !isNaN(s.x) && !isNaN(s.y) && !isNaN(s.z) && (this._cachedCameraDirection.equals(s) || (this._cachedCameraDirection.copyFrom(s),
                            r.audioContext.listener.setOrientation(s.x, s.y, s.z, 0, 1, 0)))
                        } else
                            r.audioContext.listener.setPosition(0, 0, 0)
                    }
                    var l;
                    for (l = 0; l < t.mainSoundTrack.soundCollection.length; l++) {
                        var u = t.mainSoundTrack.soundCollection[l];
                        u.useCustomAttenuation && u.updateDistanceFromListener()
                    }
                    if (t.soundTracks)
                        for (l = 0; l < t.soundTracks.length; l++)
                            for (var c = 0; c < t.soundTracks[l].soundCollection.length; c++)
                                u = t.soundTracks[l].soundCollection[c],
                                u.useCustomAttenuation && u.updateDistanceFromListener()
                }
            }
        }
    }
    ,
    i._CameraDirection = new Vector3(0,0,-1),
    i
}();
Sound._SceneComponentInitialization = function(i) {
    var e = i._getComponent(SceneComponentConstants.NAME_AUDIO);
    e || (e = new AudioSceneComponent(i),
    i._addComponent(e))
}
;
var DefaultLoadingScreen = function() {
    function i(e, t, r) {
        var n = this;
        t === void 0 && (t = ""),
        r === void 0 && (r = "black"),
        this._renderingCanvas = e,
        this._loadingText = t,
        this._loadingDivBackgroundColor = r,
        this._resizeLoadingUI = function() {
            var o = n._renderingCanvas.getBoundingClientRect()
              , a = window.getComputedStyle(n._renderingCanvas).position;
            !n._loadingDiv || (n._loadingDiv.style.position = a === "fixed" ? "fixed" : "absolute",
            n._loadingDiv.style.left = o.left + "px",
            n._loadingDiv.style.top = o.top + "px",
            n._loadingDiv.style.width = o.width + "px",
            n._loadingDiv.style.height = o.height + "px")
        }
    }
    return i.prototype.displayLoadingUI = function() {
        if (!this._loadingDiv) {
            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",
            this._loadingDiv.style.display = "grid",
            this._loadingDiv.style.gridTemplateRows = "100%",
            this._loadingDiv.style.gridTemplateColumns = "100%",
            this._loadingDiv.style.justifyItems = "center",
            this._loadingDiv.style.alignItems = "center",
            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.style.zIndex = "1",
            this._loadingTextDiv.innerHTML = "Loading",
            this._loadingDiv.appendChild(this._loadingTextDiv),
            this._loadingTextDiv.innerHTML = this._loadingText,
            this._style = document.createElement("style"),
            this._style.type = "text/css";
            var e = `@-webkit-keyframes spin1 {                    0% { -webkit-transform: rotate(0deg);}
                    100% { -webkit-transform: rotate(360deg);}
                }                @keyframes spin1 {                    0% { transform: rotate(0deg);}
                    100% { transform: rotate(360deg);}
                }`;
            this._style.innerHTML = e,
            document.getElementsByTagName("head")[0].appendChild(this._style);
            var t = !!window.SVGSVGElement
              , r = new Image;
            i.DefaultLogoUrl ? r.src = i.DefaultLogoUrl : r.src = t ? "data:image/svg+xml;base64, " : "https://cdn.babylonjs.com/Assets/babylonLogo.png",
            r.style.width = "150px",
            r.style.gridColumn = "1",
            r.style.gridRow = "1",
            r.style.top = "50%",
            r.style.left = "50%",
            r.style.transform = "translate(-50%, -50%)",
            r.style.position = "absolute";
            var n = document.createElement("div");
            n.style.width = "300px",
            n.style.gridColumn = "1",
            n.style.gridRow = "1",
            n.style.top = "50%",
            n.style.left = "50%",
            n.style.transform = "translate(-50%, -50%)",
            n.style.position = "absolute";
            var o = new Image;
            if (i.DefaultSpinnerUrl ? o.src = i.DefaultSpinnerUrl : o.src = t ? "data:image/svg+xml;base64, " : "https://cdn.babylonjs.com/Assets/loadingIcon.png",
            o.style.animation = "spin1 0.75s infinite linear",
            o.style.webkitAnimation = "spin1 0.75s infinite linear",
            o.style.transformOrigin = "50% 50%",
            o.style.webkitTransformOrigin = "50% 50%",
            !t) {
                var a = {
                    w: 16,
                    h: 18.5
                }
                  , s = {
                    w: 30,
                    h: 30
                };
                r.style.width = a.w + "vh",
                r.style.height = a.h + "vh",
                r.style.left = "calc(50% - " + a.w / 2 + "vh)",
                r.style.top = "calc(50% - " + a.h / 2 + "vh)",
                o.style.width = s.w + "vh",
                o.style.height = s.h + "vh",
                o.style.left = "calc(50% - " + s.w / 2 + "vh)",
                o.style.top = "calc(50% - " + s.h / 2 + "vh)"
            }
            n.appendChild(o),
            this._loadingDiv.appendChild(r),
            this._loadingDiv.appendChild(n),
            this._resizeLoadingUI(),
            window.addEventListener("resize", this._resizeLoadingUI),
            this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor,
            document.body.appendChild(this._loadingDiv),
            this._loadingDiv.style.opacity = "1"
        }
    }
    ,
    i.prototype.hideLoadingUI = function() {
        var e = this;
        if (!!this._loadingDiv) {
            var t = function() {
                e._loadingDiv && (e._loadingDiv.parentElement && e._loadingDiv.parentElement.removeChild(e._loadingDiv),
                e._loadingDiv = null),
                e._style && (e._style.parentElement && e._style.parentElement.removeChild(e._style),
                e._style = null),
                window.removeEventListener("resize", e._resizeLoadingUI)
            };
            this._loadingDiv.style.opacity = "0",
            this._loadingDiv.addEventListener("transitionend", t)
        }
    }
    ,
    Object.defineProperty(i.prototype, "loadingUIText", {
        get: function() {
            return this._loadingText
        },
        set: function(e) {
            this._loadingText = e,
            this._loadingTextDiv && (this._loadingTextDiv.innerHTML = this._loadingText)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "loadingUIBackgroundColor", {
        get: function() {
            return this._loadingDivBackgroundColor
        },
        set: function(e) {
            this._loadingDivBackgroundColor = e,
            this._loadingDiv && (this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor)
        },
        enumerable: !1,
        configurable: !0
    }),
    i.DefaultLogoUrl = "",
    i.DefaultSpinnerUrl = "",
    i
}();
Engine.DefaultLoadingScreenFactory = function(i) {
    return new DefaultLoadingScreen(i)
}
;
var PanoramaToCubeMapTools = function() {
    function i() {}
    return i.ConvertPanoramaToCubemap = function(e, t, r, n) {
        if (!e)
            throw "ConvertPanoramaToCubemap: input cannot be null";
        if (e.length != t * r * 3)
            throw "ConvertPanoramaToCubemap: input size is wrong";
        var o = this.CreateCubemapTexture(n, this.FACE_FRONT, e, t, r)
          , a = this.CreateCubemapTexture(n, this.FACE_BACK, e, t, r)
          , s = this.CreateCubemapTexture(n, this.FACE_LEFT, e, t, r)
          , l = this.CreateCubemapTexture(n, this.FACE_RIGHT, e, t, r)
          , u = this.CreateCubemapTexture(n, this.FACE_UP, e, t, r)
          , c = this.CreateCubemapTexture(n, this.FACE_DOWN, e, t, r);
        return {
            front: o,
            back: a,
            left: s,
            right: l,
            up: u,
            down: c,
            size: n,
            type: 1,
            format: 4,
            gammaSpace: !1
        }
    }
    ,
    i.CreateCubemapTexture = function(e, t, r, n, o) {
        for (var a = new ArrayBuffer(e * e * 4 * 3), s = new Float32Array(a), l = t[1].subtract(t[0]).scale(1 / e), u = t[3].subtract(t[2]).scale(1 / e), c = 1 / e, h = 0, f = 0; f < e; f++) {
            for (var d = t[0], _ = t[2], g = 0; g < e; g++) {
                var m = _.subtract(d).scale(h).add(d);
                m.normalize();
                var v = this.CalcProjectionSpherical(m, r, n, o);
                s[f * e * 3 + g * 3 + 0] = v.r,
                s[f * e * 3 + g * 3 + 1] = v.g,
                s[f * e * 3 + g * 3 + 2] = v.b,
                d = d.add(l),
                _ = _.add(u)
            }
            h += c
        }
        return s
    }
    ,
    i.CalcProjectionSpherical = function(e, t, r, n) {
        for (var o = Math.atan2(e.z, e.x), a = Math.acos(e.y); o < -Math.PI; )
            o += 2 * Math.PI;
        for (; o > Math.PI; )
            o -= 2 * Math.PI;
        var s = o / Math.PI
          , l = a / Math.PI;
        s = s * .5 + .5;
        var u = Math.round(s * r);
        u < 0 ? u = 0 : u >= r && (u = r - 1);
        var c = Math.round(l * n);
        c < 0 ? c = 0 : c >= n && (c = n - 1);
        var h = n - c - 1
          , f = t[h * r * 3 + u * 3 + 0]
          , d = t[h * r * 3 + u * 3 + 1]
          , _ = t[h * r * 3 + u * 3 + 2];
        return {
            r: f,
            g: d,
            b: _
        }
    }
    ,
    i.FACE_LEFT = [new Vector3(-1,-1,-1), new Vector3(1,-1,-1), new Vector3(-1,1,-1), new Vector3(1,1,-1)],
    i.FACE_RIGHT = [new Vector3(1,-1,1), new Vector3(-1,-1,1), new Vector3(1,1,1), new Vector3(-1,1,1)],
    i.FACE_FRONT = [new Vector3(1,-1,-1), new Vector3(1,-1,1), new Vector3(1,1,-1), new Vector3(1,1,1)],
    i.FACE_BACK = [new Vector3(-1,-1,1), new Vector3(-1,-1,-1), new Vector3(-1,1,1), new Vector3(-1,1,-1)],
    i.FACE_DOWN = [new Vector3(1,1,-1), new Vector3(1,1,1), new Vector3(-1,1,-1), new Vector3(-1,1,1)],
    i.FACE_UP = [new Vector3(-1,-1,-1), new Vector3(-1,-1,1), new Vector3(1,-1,-1), new Vector3(1,-1,1)],
    i
}()
  , HDRTools = function() {
    function i() {}
    return i.Ldexp = function(e, t) {
        return t > 1023 ? e * Math.pow(2, 1023) * Math.pow(2, t - 1023) : t < -1074 ? e * Math.pow(2, -1074) * Math.pow(2, t + 1074) : e * Math.pow(2, t)
    }
    ,
    i.Rgbe2float = function(e, t, r, n, o, a) {
        o > 0 ? (o = this.Ldexp(1, o - (128 + 8)),
        e[a + 0] = t * o,
        e[a + 1] = r * o,
        e[a + 2] = n * o) : (e[a + 0] = 0,
        e[a + 1] = 0,
        e[a + 2] = 0)
    }
    ,
    i.readStringLine = function(e, t) {
        for (var r = "", n = "", o = t; o < e.length - t && (n = String.fromCharCode(e[o]),
        n != `
`); o++)
            r += n;
        return r
    }
    ,
    i.RGBE_ReadHeader = function(e) {
        var t = 0
          , r = 0
          , n = this.readStringLine(e, 0);
        if (n[0] != "#" || n[1] != "?")
            throw "Bad HDR Format.";
        var o = !1
          , a = !1
          , s = 0;
        do
            s += n.length + 1,
            n = this.readStringLine(e, s),
            n == "FORMAT=32-bit_rle_rgbe" ? a = !0 : n.length == 0 && (o = !0);
        while (!o);
        if (!a)
            throw "HDR Bad header format, unsupported FORMAT";
        s += n.length + 1,
        n = this.readStringLine(e, s);
        var l = /^\-Y (.*) \+X (.*)$/g
          , u = l.exec(n);
        if (!u || u.length < 3)
            throw "HDR Bad header format, no size";
        if (r = parseInt(u[2]),
        t = parseInt(u[1]),
        r < 8 || r > 32767)
            throw "HDR Bad header format, unsupported size";
        return s += n.length + 1,
        {
            height: t,
            width: r,
            dataPosition: s
        }
    }
    ,
    i.GetCubeMapTextureData = function(e, t) {
        var r = new Uint8Array(e)
          , n = this.RGBE_ReadHeader(r)
          , o = this.RGBE_ReadPixels(r, n)
          , a = PanoramaToCubeMapTools.ConvertPanoramaToCubemap(o, n.width, n.height, t);
        return a
    }
    ,
    i.RGBE_ReadPixels = function(e, t) {
        return this.RGBE_ReadPixels_RLE(e, t)
    }
    ,
    i.RGBE_ReadPixels_RLE = function(e, t) {
        for (var r = t.height, n = t.width, o, a, s, l, u, c = t.dataPosition, h = 0, f = 0, d = 0, _ = new ArrayBuffer(n * 4), g = new Uint8Array(_), m = new ArrayBuffer(t.width * t.height * 4 * 3), v = new Float32Array(m); r > 0; ) {
            if (o = e[c++],
            a = e[c++],
            s = e[c++],
            l = e[c++],
            o != 2 || a != 2 || s & 128 || t.width < 8 || t.width > 32767)
                return this.RGBE_ReadPixels_NOT_RLE(e, t);
            if ((s << 8 | l) != n)
                throw "HDR Bad header format, wrong scan line width";
            for (h = 0,
            d = 0; d < 4; d++)
                for (f = (d + 1) * n; h < f; )
                    if (o = e[c++],
                    a = e[c++],
                    o > 128) {
                        if (u = o - 128,
                        u == 0 || u > f - h)
                            throw "HDR Bad Format, bad scanline data (run)";
                        for (; u-- > 0; )
                            g[h++] = a
                    } else {
                        if (u = o,
                        u == 0 || u > f - h)
                            throw "HDR Bad Format, bad scanline data (non-run)";
                        if (g[h++] = a,
                        --u > 0)
                            for (var y = 0; y < u; y++)
                                g[h++] = e[c++]
                    }
            for (d = 0; d < n; d++)
                o = g[d],
                a = g[d + n],
                s = g[d + 2 * n],
                l = g[d + 3 * n],
                this.Rgbe2float(v, o, a, s, l, (t.height - r) * n * 3 + d * 3);
            r--
        }
        return v
    }
    ,
    i.RGBE_ReadPixels_NOT_RLE = function(e, t) {
        for (var r = t.height, n = t.width, o, a, s, l, u, c = t.dataPosition, h = new ArrayBuffer(t.width * t.height * 4 * 3), f = new Float32Array(h); r > 0; ) {
            for (u = 0; u < t.width; u++)
                o = e[c++],
                a = e[c++],
                s = e[c++],
                l = e[c++],
                this.Rgbe2float(f, o, a, s, l, (t.height - r) * n * 3 + u * 3);
            r--
        }
        return f
    }
    ,
    i
}()
  , EffectRenderer = function() {
    function i(e, t) {
        var r, n = this;
        t === void 0 && (t = i._DefaultOptions),
        this.engine = e,
        this._fullscreenViewport = new Viewport(0,0,1,1),
        t = __assign(__assign({}, i._DefaultOptions), t),
        this._vertexBuffers = (r = {},
        r[VertexBuffer.PositionKind] = new VertexBuffer(e,t.positions,VertexBuffer.PositionKind,!1,!1,2),
        r),
        this._indexBuffer = e.createIndexBuffer(t.indices),
        this._onContextRestoredObserver = e.onContextRestoredObservable.add(function() {
            n._indexBuffer = e.createIndexBuffer(t.indices);
            for (var o in n._vertexBuffers) {
                var a = n._vertexBuffers[o];
                a._rebuild()
            }
        })
    }
    return i.prototype.setViewport = function(e) {
        e === void 0 && (e = this._fullscreenViewport),
        this.engine.setViewport(e)
    }
    ,
    i.prototype.bindBuffers = function(e) {
        this.engine.bindBuffers(this._vertexBuffers, this._indexBuffer, e)
    }
    ,
    i.prototype.applyEffectWrapper = function(e) {
        this.engine.depthCullingState.depthTest = !1,
        this.engine.stencilState.stencilTest = !1,
        this.engine.enableEffect(e._drawWrapper),
        this.bindBuffers(e.effect),
        e.onApplyObservable.notifyObservers({})
    }
    ,
    i.prototype.restoreStates = function() {
        this.engine.depthCullingState.depthTest = !0,
        this.engine.stencilState.stencilTest = !0
    }
    ,
    i.prototype.draw = function() {
        this.engine.drawElementsType(0, 0, 6)
    }
    ,
    i.prototype.isRenderTargetTexture = function(e) {
        return e.renderTarget !== void 0
    }
    ,
    i.prototype.render = function(e, t) {
        if (t === void 0 && (t = null),
        !!e.effect.isReady()) {
            this.setViewport();
            var r = t === null ? null : this.isRenderTargetTexture(t) ? t.renderTarget : t;
            r && this.engine.bindFramebuffer(r),
            this.applyEffectWrapper(e),
            this.draw(),
            r && this.engine.unBindFramebuffer(r),
            this.restoreStates()
        }
    }
    ,
    i.prototype.dispose = function() {
        var e = this._vertexBuffers[VertexBuffer.PositionKind];
        e && (e.dispose(),
        delete this._vertexBuffers[VertexBuffer.PositionKind]),
        this._indexBuffer && this.engine._releaseBuffer(this._indexBuffer),
        this._onContextRestoredObserver && (this.engine.onContextRestoredObservable.remove(this._onContextRestoredObserver),
        this._onContextRestoredObserver = null)
    }
    ,
    i._DefaultOptions = {
        positions: [1, 1, -1, 1, -1, -1, 1, -1],
        indices: [0, 1, 2, 0, 2, 3]
    },
    i
}()
  , EffectWrapper = function() {
    function i(e) {
        var t = this;
        this.onApplyObservable = new Observable;
        var r, n = e.uniformNames || [];
        e.vertexShader ? r = {
            fragmentSource: e.fragmentShader,
            vertexSource: e.vertexShader,
            spectorName: e.name || "effectWrapper"
        } : (n.push("scale"),
        r = {
            fragmentSource: e.fragmentShader,
            vertex: "postprocess",
            spectorName: e.name || "effectWrapper"
        },
        this.onApplyObservable.add(function() {
            t.effect.setFloat2("scale", 1, 1)
        }));
        var o = e.defines ? e.defines.join(`
`) : "";
        this._drawWrapper = new DrawWrapper(e.engine),
        e.useShaderStore ? (r.fragment = r.fragmentSource,
        r.vertex || (r.vertex = r.vertexSource),
        delete r.fragmentSource,
        delete r.vertexSource,
        this.effect = e.engine.createEffect(r, e.attributeNames || ["position"], n, e.samplerNames, o, void 0, e.onCompiled, void 0, void 0, e.shaderLanguage)) : (this.effect = new Effect(r,e.attributeNames || ["position"],n,e.samplerNames,e.engine,o,void 0,e.onCompiled,void 0,void 0,void 0,e.shaderLanguage),
        this._onContextRestoredObserver = e.engine.onContextRestoredObservable.add(function() {
            t.effect._pipelineContext = null,
            t.effect._wasPreviouslyReady = !1,
            t.effect._prepareEffect()
        }))
    }
    return Object.defineProperty(i.prototype, "effect", {
        get: function() {
            return this._drawWrapper.effect
        },
        set: function(e) {
            this._drawWrapper.effect = e
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.dispose = function() {
        this._onContextRestoredObserver && (this.effect.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),
        this._onContextRestoredObserver = null),
        this.effect.dispose()
    }
    ,
    i
}()
  , name$t = "hdrFilteringVertexShader"
  , shader$t = `
attribute vec2 position;

varying vec3 direction;

uniform vec3 up;
uniform vec3 right;
uniform vec3 front;
void main(void) {
mat3 view=mat3(up,right,front);
direction=view*vec3(position,1.0);
gl_Position=vec4(position,0.0,1.0);
}`;
ShaderStore.ShadersStore[name$t] = shader$t;
var name$s = "hdrFilteringPixelShader"
  , shader$s = `#include<helperFunctions>
#include<importanceSampling>
#include<pbrBRDFFunctions>
#include<hdrFilteringFunctions>
uniform float alphaG;
uniform samplerCube inputTexture;
uniform vec2 vFilteringInfo;
uniform float hdrScale;
varying vec3 direction;
void main() {
vec3 color=radiance(alphaG,inputTexture,direction,vFilteringInfo);
gl_FragColor=vec4(color*hdrScale,1.0);
}`;
ShaderStore.ShadersStore[name$s] = shader$s;
var HDRFiltering = function() {
    function i(e, t) {
        t === void 0 && (t = {}),
        this._lodGenerationOffset = 0,
        this._lodGenerationScale = .8,
        this.quality = 4096,
        this.hdrScale = 1,
        this._engine = e,
        this.hdrScale = t.hdrScale || this.hdrScale,
        this.quality = t.hdrScale || this.quality
    }
    return i.prototype._createRenderTarget = function(e) {
        var t = 0;
        this._engine.getCaps().textureHalfFloatRender ? t = 2 : this._engine.getCaps().textureFloatRender && (t = 1);
        var r = this._engine.createRenderTargetCubeTexture(e, {
            format: 5,
            type: t,
            createMipMaps: !0,
            generateMipMaps: !1,
            generateDepthBuffer: !1,
            generateStencilBuffer: !1,
            samplingMode: 1
        });
        return this._engine.updateTextureWrappingMode(r.texture, 0, 0, 0),
        this._engine.updateTextureSamplingMode(3, r.texture, !0),
        r
    }
    ,
    i.prototype._prefilterInternal = function(e) {
        var t = e.getSize().width
          , r = Scalar.ILog2(t) + 1
          , n = this._effectWrapper.effect
          , o = this._createRenderTarget(t);
        this._effectRenderer.setViewport();
        var a = e.getInternalTexture();
        a && this._engine.updateTextureSamplingMode(3, a, !0),
        this._effectRenderer.applyEffectWrapper(this._effectWrapper);
        var s = [[new Vector3(0,0,-1), new Vector3(0,-1,0), new Vector3(1,0,0)], [new Vector3(0,0,1), new Vector3(0,-1,0), new Vector3(-1,0,0)], [new Vector3(1,0,0), new Vector3(0,0,1), new Vector3(0,1,0)], [new Vector3(1,0,0), new Vector3(0,0,-1), new Vector3(0,-1,0)], [new Vector3(1,0,0), new Vector3(0,-1,0), new Vector3(0,0,1)], [new Vector3(-1,0,0), new Vector3(0,-1,0), new Vector3(0,0,-1)]];
        n.setFloat("hdrScale", this.hdrScale),
        n.setFloat2("vFilteringInfo", e.getSize().width, r),
        n.setTexture("inputTexture", e);
        for (var l = 0; l < 6; l++) {
            n.setVector3("up", s[l][0]),
            n.setVector3("right", s[l][1]),
            n.setVector3("front", s[l][2]);
            for (var u = 0; u < r; u++) {
                this._engine.bindFramebuffer(o, l, void 0, void 0, !0, u),
                this._effectRenderer.applyEffectWrapper(this._effectWrapper);
                var c = Math.pow(2, (u - this._lodGenerationOffset) / this._lodGenerationScale) / t;
                u === 0 && (c = 0),
                n.setFloat("alphaG", c),
                this._effectRenderer.draw()
            }
        }
        return this._effectRenderer.restoreStates(),
        this._engine.restoreDefaultFramebuffer(),
        this._engine._releaseTexture(e._texture),
        o._swapAndDie(e._texture),
        e._prefiltered = !0,
        e
    }
    ,
    i.prototype._createEffect = function(e, t) {
        var r = [];
        e.gammaSpace && r.push("#define GAMMA_INPUT"),
        r.push("#define NUM_SAMPLES " + this.quality + "u");
        var n = new EffectWrapper({
            engine: this._engine,
            name: "hdrFiltering",
            vertexShader: "hdrFiltering",
            fragmentShader: "hdrFiltering",
            samplerNames: ["inputTexture"],
            uniformNames: ["vSampleDirections", "vWeights", "up", "right", "front", "vFilteringInfo", "hdrScale", "alphaG"],
            useShaderStore: !0,
            defines: r,
            onCompiled: t
        });
        return n
    }
    ,
    i.prototype.isReady = function(e) {
        return e.isReady() && this._effectWrapper.effect.isReady()
    }
    ,
    i.prototype.prefilter = function(e, t) {
        var r = this;
        return t === void 0 && (t = null),
        this._engine._features.allowTexturePrefiltering ? new Promise(function(n) {
            r._effectRenderer = new EffectRenderer(r._engine),
            r._effectWrapper = r._createEffect(e),
            r._effectWrapper.effect.executeWhenCompiled(function() {
                r._prefilterInternal(e),
                r._effectRenderer.dispose(),
                r._effectWrapper.dispose(),
                n(),
                t && t()
            })
        }
        ) : (Logger$2.Warn("HDR prefiltering is not available in WebGL 1., you can use real time filtering instead."),
        Promise.reject("HDR prefiltering is not available in WebGL 1., you can use real time filtering instead."))
    }
    ,
    i
}()
  , HDRCubeTexture = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a, s, l, u, c) {
        o === void 0 && (o = !1),
        a === void 0 && (a = !0),
        s === void 0 && (s = !1),
        l === void 0 && (l = !1),
        u === void 0 && (u = null),
        c === void 0 && (c = null);
        var h, f = i.call(this, r) || this;
        return f._generateHarmonics = !0,
        f._onError = null,
        f._isBlocking = !0,
        f._rotationY = 0,
        f.boundingBoxPosition = Vector3.Zero(),
        f.onLoadObservable = new Observable,
        t && (f._coordinatesMode = Texture.CUBIC_MODE,
        f.name = t,
        f.url = t,
        f.hasAlpha = !1,
        f.isCube = !0,
        f._textureMatrix = Matrix.Identity(),
        f._prefilterOnLoad = l,
        f._onLoad = function() {
            f.onLoadObservable.notifyObservers(f),
            u && u()
        }
        ,
        f._onError = c,
        f.gammaSpace = s,
        f._noMipmap = o,
        f._size = n,
        f._generateHarmonics = a,
        f._texture = f._getFromCache(t, f._noMipmap),
        f._texture ? f._texture.isReady ? Tools.SetImmediate(function() {
            return f._onLoad()
        }) : f._texture.onLoadedObservable.add(f._onLoad) : !((h = f.getScene()) === null || h === void 0) && h.useDelayedTextureLoading ? f.delayLoadState = 4 : f.loadTexture()),
        f
    }
    return Object.defineProperty(e.prototype, "isBlocking", {
        get: function() {
            return this._isBlocking
        },
        set: function(t) {
            this._isBlocking = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "rotationY", {
        get: function() {
            return this._rotationY
        },
        set: function(t) {
            this._rotationY = t,
            this.setReflectionTextureMatrix(Matrix.RotationY(this._rotationY))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "boundingBoxSize", {
        get: function() {
            return this._boundingBoxSize
        },
        set: function(t) {
            if (!(this._boundingBoxSize && this._boundingBoxSize.equals(t))) {
                this._boundingBoxSize = t;
                var r = this.getScene();
                r && r.markAllMaterialsAsDirty(1)
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getClassName = function() {
        return "HDRCubeTexture"
    }
    ,
    e.prototype.loadTexture = function() {
        var t = this
          , r = this._getEngine()
          , n = r.getCaps()
          , o = 0;
        n.textureFloat && n.textureFloatLinearFiltering ? o = 1 : n.textureHalfFloat && n.textureHalfFloatLinearFiltering && (o = 2);
        var a = function(u) {
            t.lodGenerationOffset = 0,
            t.lodGenerationScale = .8;
            var c = HDRTools.GetCubeMapTextureData(u, t._size);
            if (t._generateHarmonics) {
                var h = CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(c);
                t.sphericalPolynomial = h
            }
            for (var f = [], d = null, _ = null, g = 0; g < 6; g++) {
                o === 2 ? _ = new Uint16Array(t._size * t._size * 3) : o === 0 && (d = new Uint8Array(t._size * t._size * 3));
                var m = c[e._facesMapping[g]];
                if (t.gammaSpace || _ || d) {
                    for (var v = 0; v < t._size * t._size; v++)
                        if (t.gammaSpace && (m[v * 3 + 0] = Math.pow(m[v * 3 + 0], ToGammaSpace),
                        m[v * 3 + 1] = Math.pow(m[v * 3 + 1], ToGammaSpace),
                        m[v * 3 + 2] = Math.pow(m[v * 3 + 2], ToGammaSpace)),
                        _ && (_[v * 3 + 0] = ToHalfFloat(m[v * 3 + 0]),
                        _[v * 3 + 1] = ToHalfFloat(m[v * 3 + 1]),
                        _[v * 3 + 2] = ToHalfFloat(m[v * 3 + 2])),
                        d) {
                            var y = Math.max(m[v * 3 + 0] * 255, 0)
                              , b = Math.max(m[v * 3 + 1] * 255, 0)
                              , T = Math.max(m[v * 3 + 2] * 255, 0)
                              , C = Math.max(Math.max(y, b), T);
                            if (C > 255) {
                                var A = 255 / C;
                                y *= A,
                                b *= A,
                                T *= A
                            }
                            d[v * 3 + 0] = y,
                            d[v * 3 + 1] = b,
                            d[v * 3 + 2] = T
                        }
                }
                _ ? f.push(_) : d ? f.push(d) : f.push(m)
            }
            return f
        };
        if (r._features.allowTexturePrefiltering && this._prefilterOnLoad) {
            var s = this._onLoad
              , l = new HDRFiltering(r);
            this._onLoad = function() {
                l.prefilter(t, s)
            }
        }
        this._texture = r.createRawCubeTextureFromUrl(this.url, this.getScene(), this._size, 4, o, this._noMipmap, a, null, this._onLoad, this._onError)
    }
    ,
    e.prototype.clone = function() {
        var t = new e(this.url,this.getScene() || this._getEngine(),this._size,this._noMipmap,this._generateHarmonics,this.gammaSpace);
        return t.level = this.level,
        t.wrapU = this.wrapU,
        t.wrapV = this.wrapV,
        t.coordinatesIndex = this.coordinatesIndex,
        t.coordinatesMode = this.coordinatesMode,
        t
    }
    ,
    e.prototype.delayLoad = function() {
        this.delayLoadState === 4 && (this.delayLoadState = 1,
        this._texture = this._getFromCache(this.url, this._noMipmap),
        this._texture || this.loadTexture())
    }
    ,
    e.prototype.getReflectionTextureMatrix = function() {
        return this._textureMatrix
    }
    ,
    e.prototype.setReflectionTextureMatrix = function(t) {
        var r = this, n;
        this._textureMatrix = t,
        t.updateFlag !== this._textureMatrix.updateFlag && t.isIdentity() !== this._textureMatrix.isIdentity() && ((n = this.getScene()) === null || n === void 0 || n.markAllMaterialsAsDirty(1, function(o) {
            return o.getActiveTextures().indexOf(r) !== -1
        }))
    }
    ,
    e.prototype.dispose = function() {
        this.onLoadObservable.clear(),
        i.prototype.dispose.call(this)
    }
    ,
    e.Parse = function(t, r, n) {
        var o = null;
        return t.name && !t.isRenderTarget && (o = new e(n + t.name,r,t.size,t.noMipmap,t.generateHarmonics,t.useInGammaSpace),
        o.name = t.name,
        o.hasAlpha = t.hasAlpha,
        o.level = t.level,
        o.coordinatesMode = t.coordinatesMode,
        o.isBlocking = t.isBlocking),
        o && (t.boundingBoxPosition && (o.boundingBoxPosition = Vector3.FromArray(t.boundingBoxPosition)),
        t.boundingBoxSize && (o.boundingBoxSize = Vector3.FromArray(t.boundingBoxSize)),
        t.rotationY && (o.rotationY = t.rotationY)),
        o
    }
    ,
    e.prototype.serialize = function() {
        if (!this.name)
            return null;
        var t = {};
        return t.name = this.name,
        t.hasAlpha = this.hasAlpha,
        t.isCube = !0,
        t.level = this.level,
        t.size = this._size,
        t.coordinatesMode = this.coordinatesMode,
        t.useInGammaSpace = this.gammaSpace,
        t.generateHarmonics = this._generateHarmonics,
        t.customType = "BABYLON.HDRCubeTexture",
        t.noMipmap = this._noMipmap,
        t.isBlocking = this._isBlocking,
        t.rotationY = this._rotationY,
        t
    }
    ,
    e._facesMapping = ["right", "left", "up", "down", "front", "back"],
    e
}(BaseTexture);
RegisterClass("BABYLON.HDRCubeTexture", HDRCubeTexture);
var PhysicsJoint = function() {
    function i(e, t) {
        this.type = e,
        this.jointData = t,
        t.nativeParams = t.nativeParams || {}
    }
    return Object.defineProperty(i.prototype, "physicsJoint", {
        get: function() {
            return this._physicsJoint
        },
        set: function(e) {
            this._physicsJoint,
            this._physicsJoint = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "physicsPlugin", {
        set: function(e) {
            this._physicsPlugin = e
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.executeNativeFunction = function(e) {
        e(this._physicsPlugin.world, this._physicsJoint)
    }
    ,
    i.DistanceJoint = 0,
    i.HingeJoint = 1,
    i.BallAndSocketJoint = 2,
    i.WheelJoint = 3,
    i.SliderJoint = 4,
    i.PrismaticJoint = 5,
    i.UniversalJoint = 6,
    i.Hinge2Joint = i.WheelJoint,
    i.PointToPointJoint = 8,
    i.SpringJoint = 9,
    i.LockJoint = 10,
    i
}();
(function(i) {
    __extends(e, i);
    function e(t) {
        return i.call(this, PhysicsJoint.DistanceJoint, t) || this
    }
    return e.prototype.updateDistance = function(t, r) {
        this._physicsPlugin.updateDistanceJoint(this, t, r)
    }
    ,
    e
}
)(PhysicsJoint);
var MotorEnabledJoint = function(i) {
    __extends(e, i);
    function e(t, r) {
        return i.call(this, t, r) || this
    }
    return e.prototype.setMotor = function(t, r) {
        this._physicsPlugin.setMotor(this, t || 0, r)
    }
    ,
    e.prototype.setLimit = function(t, r) {
        this._physicsPlugin.setLimit(this, t, r)
    }
    ,
    e
}(PhysicsJoint);
(function(i) {
    __extends(e, i);
    function e(t) {
        return i.call(this, PhysicsJoint.HingeJoint, t) || this
    }
    return e.prototype.setMotor = function(t, r) {
        this._physicsPlugin.setMotor(this, t || 0, r)
    }
    ,
    e.prototype.setLimit = function(t, r) {
        this._physicsPlugin.setLimit(this, t, r)
    }
    ,
    e
}
)(MotorEnabledJoint);
(function(i) {
    __extends(e, i);
    function e(t) {
        return i.call(this, PhysicsJoint.Hinge2Joint, t) || this
    }
    return e.prototype.setMotor = function(t, r, n) {
        n === void 0 && (n = 0),
        this._physicsPlugin.setMotor(this, t || 0, r, n)
    }
    ,
    e.prototype.setLimit = function(t, r, n) {
        n === void 0 && (n = 0),
        this._physicsPlugin.setLimit(this, t, r, n)
    }
    ,
    e
}
)(MotorEnabledJoint);
Mesh._PhysicsImpostorParser = function(i, e, t) {
    return new PhysicsImpostor(e,t.physicsImpostor,{
        mass: t.physicsMass,
        friction: t.physicsFriction,
        restitution: t.physicsRestitution
    },i)
}
;
var PhysicsImpostor = function() {
    function i(e, t, r, n) {
        var o = this;
        if (r === void 0 && (r = {
            mass: 0
        }),
        this.object = e,
        this.type = t,
        this._options = r,
        this._scene = n,
        this._pluginData = {},
        this._bodyUpdateRequired = !1,
        this._onBeforePhysicsStepCallbacks = new Array,
        this._onAfterPhysicsStepCallbacks = new Array,
        this._onPhysicsCollideCallbacks = [],
        this._deltaPosition = Vector3.Zero(),
        this._isDisposed = !1,
        this.soft = !1,
        this.segments = 0,
        this._tmpQuat = new Quaternion,
        this._tmpQuat2 = new Quaternion,
        this.beforeStep = function() {
            !o._physicsEngine || (o.object.translate(o._deltaPosition, -1),
            o._deltaRotationConjugated && o.object.rotationQuaternion && o.object.rotationQuaternion.multiplyToRef(o._deltaRotationConjugated, o.object.rotationQuaternion),
            o.object.computeWorldMatrix(!1),
            o.object.parent && o.object.rotationQuaternion ? (o.getParentsRotation(),
            o._tmpQuat.multiplyToRef(o.object.rotationQuaternion, o._tmpQuat)) : o._tmpQuat.copyFrom(o.object.rotationQuaternion || new Quaternion),
            o._options.disableBidirectionalTransformation || o.object.rotationQuaternion && o._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(o, o.object.getAbsolutePosition(), o._tmpQuat),
            o._onBeforePhysicsStepCallbacks.forEach(function(a) {
                a(o)
            }))
        }
        ,
        this.afterStep = function() {
            !o._physicsEngine || (o._onAfterPhysicsStepCallbacks.forEach(function(a) {
                a(o)
            }),
            o._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(o),
            o.object.parent && o.object.rotationQuaternion && (o.getParentsRotation(),
            o._tmpQuat.conjugateInPlace(),
            o._tmpQuat.multiplyToRef(o.object.rotationQuaternion, o.object.rotationQuaternion)),
            o.object.setAbsolutePosition(o.object.position),
            o._deltaRotation && o.object.rotationQuaternion && o.object.rotationQuaternion.multiplyToRef(o._deltaRotation, o.object.rotationQuaternion),
            o.object.translate(o._deltaPosition, 1))
        }
        ,
        this.onCollideEvent = null,
        this.onCollide = function(a) {
            if (!(!o._onPhysicsCollideCallbacks.length && !o.onCollideEvent) && !!o._physicsEngine) {
                var s = o._physicsEngine.getImpostorWithPhysicsBody(a.body);
                s && (o.onCollideEvent && o.onCollideEvent(o, s),
                o._onPhysicsCollideCallbacks.filter(function(l) {
                    return l.otherImpostors.indexOf(s) !== -1
                }).forEach(function(l) {
                    l.callback(o, s, a.point)
                }))
            }
        }
        ,
        !this.object) {
            Logger$2.Error("No object was provided. A physics object is obligatory");
            return
        }
        this.object.parent && r.mass !== 0 && Logger$2.Warn("A physics impostor has been created for an object which has a parent. Babylon physics currently works in local space so unexpected issues may occur."),
        !this._scene && e.getScene && (this._scene = e.getScene()),
        this._scene && (this.type > 100 && (this.soft = !0),
        this._physicsEngine = this._scene.getPhysicsEngine(),
        this._physicsEngine ? (this.object.rotationQuaternion || (this.object.rotation ? this.object.rotationQuaternion = Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z) : this.object.rotationQuaternion = new Quaternion),
        this._options.mass = r.mass === void 0 ? 0 : r.mass,
        this._options.friction = r.friction === void 0 ? .2 : r.friction,
        this._options.restitution = r.restitution === void 0 ? .2 : r.restitution,
        this.soft && (this._options.mass = this._options.mass > 0 ? this._options.mass : 1,
        this._options.pressure = r.pressure === void 0 ? 200 : r.pressure,
        this._options.stiffness = r.stiffness === void 0 ? 1 : r.stiffness,
        this._options.velocityIterations = r.velocityIterations === void 0 ? 20 : r.velocityIterations,
        this._options.positionIterations = r.positionIterations === void 0 ? 20 : r.positionIterations,
        this._options.fixedPoints = r.fixedPoints === void 0 ? 0 : r.fixedPoints,
        this._options.margin = r.margin === void 0 ? 0 : r.margin,
        this._options.damping = r.damping === void 0 ? 0 : r.damping,
        this._options.path = r.path === void 0 ? null : r.path,
        this._options.shape = r.shape === void 0 ? null : r.shape),
        this._joints = [],
        !this.object.parent || this._options.ignoreParent ? this._init() : this.object.parent.physicsImpostor && Logger$2.Warn("You must affect impostors to children before affecting impostor to parent.")) : Logger$2.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors."))
    }
    return Object.defineProperty(i.prototype, "isDisposed", {
        get: function() {
            return this._isDisposed
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "mass", {
        get: function() {
            return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0
        },
        set: function(e) {
            this.setMass(e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "friction", {
        get: function() {
            return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0
        },
        set: function(e) {
            !this._physicsEngine || this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "restitution", {
        get: function() {
            return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0
        },
        set: function(e) {
            !this._physicsEngine || this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "pressure", {
        get: function() {
            if (!this._physicsEngine)
                return 0;
            var e = this._physicsEngine.getPhysicsPlugin();
            return e.setBodyPressure ? e.getBodyPressure(this) : 0
        },
        set: function(e) {
            if (!!this._physicsEngine) {
                var t = this._physicsEngine.getPhysicsPlugin();
                !t.setBodyPressure || t.setBodyPressure(this, e)
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "stiffness", {
        get: function() {
            if (!this._physicsEngine)
                return 0;
            var e = this._physicsEngine.getPhysicsPlugin();
            return e.getBodyStiffness ? e.getBodyStiffness(this) : 0
        },
        set: function(e) {
            if (!!this._physicsEngine) {
                var t = this._physicsEngine.getPhysicsPlugin();
                !t.setBodyStiffness || t.setBodyStiffness(this, e)
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "velocityIterations", {
        get: function() {
            if (!this._physicsEngine)
                return 0;
            var e = this._physicsEngine.getPhysicsPlugin();
            return e.getBodyVelocityIterations ? e.getBodyVelocityIterations(this) : 0
        },
        set: function(e) {
            if (!!this._physicsEngine) {
                var t = this._physicsEngine.getPhysicsPlugin();
                !t.setBodyVelocityIterations || t.setBodyVelocityIterations(this, e)
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "positionIterations", {
        get: function() {
            if (!this._physicsEngine)
                return 0;
            var e = this._physicsEngine.getPhysicsPlugin();
            return e.getBodyPositionIterations ? e.getBodyPositionIterations(this) : 0
        },
        set: function(e) {
            if (!!this._physicsEngine) {
                var t = this._physicsEngine.getPhysicsPlugin();
                !t.setBodyPositionIterations || t.setBodyPositionIterations(this, e)
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype._init = function() {
        !this._physicsEngine || (this._physicsEngine.removeImpostor(this),
        this.physicsBody = null,
        this._parent = this._parent || this._getPhysicsParent(),
        !this._isDisposed && (!this.parent || this._options.ignoreParent) && this._physicsEngine.addImpostor(this))
    }
    ,
    i.prototype._getPhysicsParent = function() {
        if (this.object.parent instanceof AbstractMesh) {
            var e = this.object.parent;
            return e.physicsImpostor
        }
        return null
    }
    ,
    i.prototype.isBodyInitRequired = function() {
        return this._bodyUpdateRequired || !this._physicsBody && !this._parent
    }
    ,
    i.prototype.setScalingUpdated = function() {
        this.forceUpdate()
    }
    ,
    i.prototype.forceUpdate = function() {
        this._init(),
        this.parent && !this._options.ignoreParent && this.parent.forceUpdate()
    }
    ,
    Object.defineProperty(i.prototype, "physicsBody", {
        get: function() {
            return this._parent && !this._options.ignoreParent ? this._parent.physicsBody : this._physicsBody
        },
        set: function(e) {
            this._physicsBody && this._physicsEngine && this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this),
            this._physicsBody = e,
            this.resetUpdateFlags()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "parent", {
        get: function() {
            return !this._options.ignoreParent && this._parent ? this._parent : null
        },
        set: function(e) {
            this._parent = e
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.resetUpdateFlags = function() {
        this._bodyUpdateRequired = !1
    }
    ,
    i.prototype.getObjectExtendSize = function() {
        if (this.object.getBoundingInfo) {
            var e = this.object.rotationQuaternion
              , t = this.object.scaling.clone();
            this.object.rotationQuaternion = i.IDENTITY_QUATERNION;
            var r = this.object.computeWorldMatrix && this.object.computeWorldMatrix(!0);
            r && r.decompose(t, void 0, void 0);
            var n = this.object.getBoundingInfo()
              , o = n.boundingBox.extendSize.scale(2).multiplyInPlace(t);
            return o.x = Math.abs(o.x),
            o.y = Math.abs(o.y),
            o.z = Math.abs(o.z),
            this.object.rotationQuaternion = e,
            this.object.computeWorldMatrix && this.object.computeWorldMatrix(!0),
            o
        } else
            return i.DEFAULT_OBJECT_SIZE
    }
    ,
    i.prototype.getObjectCenter = function() {
        if (this.object.getBoundingInfo) {
            var e = this.object.getBoundingInfo();
            return e.boundingBox.centerWorld
        } else
            return this.object.position
    }
    ,
    i.prototype.getParam = function(e) {
        return this._options[e]
    }
    ,
    i.prototype.setParam = function(e, t) {
        this._options[e] = t,
        this._bodyUpdateRequired = !0
    }
    ,
    i.prototype.setMass = function(e) {
        this.getParam("mass") !== e && this.setParam("mass", e),
        this._physicsEngine && this._physicsEngine.getPhysicsPlugin().setBodyMass(this, e)
    }
    ,
    i.prototype.getLinearVelocity = function() {
        return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : Vector3.Zero()
    }
    ,
    i.prototype.setLinearVelocity = function(e) {
        this._physicsEngine && this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, e)
    }
    ,
    i.prototype.getAngularVelocity = function() {
        return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : Vector3.Zero()
    }
    ,
    i.prototype.setAngularVelocity = function(e) {
        this._physicsEngine && this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, e)
    }
    ,
    i.prototype.executeNativeFunction = function(e) {
        this._physicsEngine && e(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody)
    }
    ,
    i.prototype.registerBeforePhysicsStep = function(e) {
        this._onBeforePhysicsStepCallbacks.push(e)
    }
    ,
    i.prototype.unregisterBeforePhysicsStep = function(e) {
        var t = this._onBeforePhysicsStepCallbacks.indexOf(e);
        t > -1 ? this._onBeforePhysicsStepCallbacks.splice(t, 1) : Logger$2.Warn("Function to remove was not found")
    }
    ,
    i.prototype.registerAfterPhysicsStep = function(e) {
        this._onAfterPhysicsStepCallbacks.push(e)
    }
    ,
    i.prototype.unregisterAfterPhysicsStep = function(e) {
        var t = this._onAfterPhysicsStepCallbacks.indexOf(e);
        t > -1 ? this._onAfterPhysicsStepCallbacks.splice(t, 1) : Logger$2.Warn("Function to remove was not found")
    }
    ,
    i.prototype.registerOnPhysicsCollide = function(e, t) {
        var r = e instanceof Array ? e : [e];
        this._onPhysicsCollideCallbacks.push({
            callback: t,
            otherImpostors: r
        })
    }
    ,
    i.prototype.unregisterOnPhysicsCollide = function(e, t) {
        var r = e instanceof Array ? e : [e]
          , n = -1
          , o = this._onPhysicsCollideCallbacks.some(function(a, s) {
            if (a.callback === t && a.otherImpostors.length === r.length) {
                var l = a.otherImpostors.every(function(u) {
                    return r.indexOf(u) > -1
                });
                return l && (n = s),
                l
            }
            return !1
        });
        o ? this._onPhysicsCollideCallbacks.splice(n, 1) : Logger$2.Warn("Function to remove was not found")
    }
    ,
    i.prototype.getParentsRotation = function() {
        var e = this.object.parent;
        for (this._tmpQuat.copyFromFloats(0, 0, 0, 1); e; )
            e.rotationQuaternion ? this._tmpQuat2.copyFrom(e.rotationQuaternion) : Quaternion.RotationYawPitchRollToRef(e.rotation.y, e.rotation.x, e.rotation.z, this._tmpQuat2),
            this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat),
            e = e.parent;
        return this._tmpQuat
    }
    ,
    i.prototype.applyForce = function(e, t) {
        return this._physicsEngine && this._physicsEngine.getPhysicsPlugin().applyForce(this, e, t),
        this
    }
    ,
    i.prototype.applyImpulse = function(e, t) {
        return this._physicsEngine && this._physicsEngine.getPhysicsPlugin().applyImpulse(this, e, t),
        this
    }
    ,
    i.prototype.createJoint = function(e, t, r) {
        var n = new PhysicsJoint(t,r);
        return this.addJoint(e, n),
        this
    }
    ,
    i.prototype.addJoint = function(e, t) {
        return this._joints.push({
            otherImpostor: e,
            joint: t
        }),
        this._physicsEngine && this._physicsEngine.addJoint(this, e, t),
        this
    }
    ,
    i.prototype.addAnchor = function(e, t, r, n, o) {
        if (!this._physicsEngine)
            return this;
        var a = this._physicsEngine.getPhysicsPlugin();
        return a.appendAnchor ? (this._physicsEngine && a.appendAnchor(this, e, t, r, n, o),
        this) : this
    }
    ,
    i.prototype.addHook = function(e, t, r, n) {
        if (!this._physicsEngine)
            return this;
        var o = this._physicsEngine.getPhysicsPlugin();
        return o.appendAnchor ? (this._physicsEngine && o.appendHook(this, e, t, r, n),
        this) : this
    }
    ,
    i.prototype.sleep = function() {
        return this._physicsEngine && this._physicsEngine.getPhysicsPlugin().sleepBody(this),
        this
    }
    ,
    i.prototype.wakeUp = function() {
        return this._physicsEngine && this._physicsEngine.getPhysicsPlugin().wakeUpBody(this),
        this
    }
    ,
    i.prototype.clone = function(e) {
        return e ? new i(e,this.type,this._options,this._scene) : null
    }
    ,
    i.prototype.dispose = function() {
        var e = this;
        !this._physicsEngine || (this._joints.forEach(function(t) {
            e._physicsEngine && e._physicsEngine.removeJoint(e, t.otherImpostor, t.joint)
        }),
        this._physicsEngine.removeImpostor(this),
        this.parent && this.parent.forceUpdate(),
        this._isDisposed = !0)
    }
    ,
    i.prototype.setDeltaPosition = function(e) {
        this._deltaPosition.copyFrom(e)
    }
    ,
    i.prototype.setDeltaRotation = function(e) {
        this._deltaRotation || (this._deltaRotation = new Quaternion),
        this._deltaRotation.copyFrom(e),
        this._deltaRotationConjugated = this._deltaRotation.conjugate()
    }
    ,
    i.prototype.getBoxSizeToRef = function(e) {
        return this._physicsEngine && this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, e),
        this
    }
    ,
    i.prototype.getRadius = function() {
        return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0
    }
    ,
    i.prototype.syncBoneWithImpostor = function(e, t, r, n, o) {
        var a = i._tmpVecs[0]
          , s = this.object;
        if (s.rotationQuaternion)
            if (o) {
                var l = i._tmpQuat;
                s.rotationQuaternion.multiplyToRef(o, l),
                e.setRotationQuaternion(l, Space.WORLD, t)
            } else
                e.setRotationQuaternion(s.rotationQuaternion, Space.WORLD, t);
        a.x = 0,
        a.y = 0,
        a.z = 0,
        r && (a.x = r.x,
        a.y = r.y,
        a.z = r.z,
        e.getDirectionToRef(a, t, a),
        n == null && (n = r.length()),
        a.x *= n,
        a.y *= n,
        a.z *= n),
        e.getParent() ? (a.addInPlace(s.getAbsolutePosition()),
        e.setAbsolutePosition(a, t)) : (t.setAbsolutePosition(s.getAbsolutePosition()),
        t.position.x -= a.x,
        t.position.y -= a.y,
        t.position.z -= a.z)
    }
    ,
    i.prototype.syncImpostorWithBone = function(e, t, r, n, o, a) {
        var s = this.object;
        if (s.rotationQuaternion)
            if (o) {
                var l = i._tmpQuat;
                e.getRotationQuaternionToRef(Space.WORLD, t, l),
                l.multiplyToRef(o, s.rotationQuaternion)
            } else
                e.getRotationQuaternionToRef(Space.WORLD, t, s.rotationQuaternion);
        var u = i._tmpVecs[0]
          , c = i._tmpVecs[1];
        a || (a = i._tmpVecs[2],
        a.x = 0,
        a.y = 1,
        a.z = 0),
        e.getDirectionToRef(a, t, c),
        e.getAbsolutePositionToRef(t, u),
        n == null && r && (n = r.length()),
        n != null && (u.x += c.x * n,
        u.y += c.y * n,
        u.z += c.z * n),
        s.setAbsolutePosition(u)
    }
    ,
    i.DEFAULT_OBJECT_SIZE = new Vector3(1,1,1),
    i.IDENTITY_QUATERNION = Quaternion.Identity(),
    i._tmpVecs = ArrayTools.BuildArray(3, Vector3.Zero),
    i._tmpQuat = Quaternion.Identity(),
    i.NoImpostor = 0,
    i.SphereImpostor = 1,
    i.BoxImpostor = 2,
    i.PlaneImpostor = 3,
    i.MeshImpostor = 4,
    i.CapsuleImpostor = 6,
    i.CylinderImpostor = 7,
    i.ParticleImpostor = 8,
    i.HeightmapImpostor = 9,
    i.ConvexHullImpostor = 10,
    i.CustomImpostor = 100,
    i.RopeImpostor = 101,
    i.ClothImpostor = 102,
    i.SoftbodyImpostor = 103,
    i
}()
  , PhysicsEngine = function() {
    function i(e, t) {
        if (t === void 0 && (t = i.DefaultPluginFactory()),
        this._physicsPlugin = t,
        this._impostors = [],
        this._joints = [],
        this._subTimeStep = 0,
        !this._physicsPlugin.isSupported())
            throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. Please make sure it is included.");
        e = e || new Vector3(0,-9.807,0),
        this.setGravity(e),
        this.setTimeStep()
    }
    return i.DefaultPluginFactory = function() {
        throw _WarnImport("CannonJSPlugin")
    }
    ,
    i.prototype.setGravity = function(e) {
        this.gravity = e,
        this._physicsPlugin.setGravity(this.gravity)
    }
    ,
    i.prototype.setTimeStep = function(e) {
        e === void 0 && (e = 1 / 60),
        this._physicsPlugin.setTimeStep(e)
    }
    ,
    i.prototype.getTimeStep = function() {
        return this._physicsPlugin.getTimeStep()
    }
    ,
    i.prototype.setSubTimeStep = function(e) {
        e === void 0 && (e = 0),
        this._subTimeStep = e
    }
    ,
    i.prototype.getSubTimeStep = function() {
        return this._subTimeStep
    }
    ,
    i.prototype.dispose = function() {
        this._impostors.forEach(function(e) {
            e.dispose()
        }),
        this._physicsPlugin.dispose()
    }
    ,
    i.prototype.getPhysicsPluginName = function() {
        return this._physicsPlugin.name
    }
    ,
    i.prototype.addImpostor = function(e) {
        e.uniqueId = this._impostors.push(e),
        e.parent || this._physicsPlugin.generatePhysicsBody(e)
    }
    ,
    i.prototype.removeImpostor = function(e) {
        var t = this._impostors.indexOf(e);
        if (t > -1) {
            var r = this._impostors.splice(t, 1);
            r.length && this.getPhysicsPlugin().removePhysicsBody(e)
        }
    }
    ,
    i.prototype.addJoint = function(e, t, r) {
        var n = {
            mainImpostor: e,
            connectedImpostor: t,
            joint: r
        };
        r.physicsPlugin = this._physicsPlugin,
        this._joints.push(n),
        this._physicsPlugin.generateJoint(n)
    }
    ,
    i.prototype.removeJoint = function(e, t, r) {
        var n = this._joints.filter(function(o) {
            return o.connectedImpostor === t && o.joint === r && o.mainImpostor === e
        });
        n.length && this._physicsPlugin.removeJoint(n[0])
    }
    ,
    i.prototype._step = function(e) {
        var t = this;
        this._impostors.forEach(function(r) {
            r.isBodyInitRequired() && t._physicsPlugin.generatePhysicsBody(r)
        }),
        e > .1 ? e = .1 : e <= 0 && (e = 1 / 60),
        this._physicsPlugin.executeStep(e, this._impostors)
    }
    ,
    i.prototype.getPhysicsPlugin = function() {
        return this._physicsPlugin
    }
    ,
    i.prototype.getImpostors = function() {
        return this._impostors
    }
    ,
    i.prototype.getImpostorForPhysicsObject = function(e) {
        for (var t = 0; t < this._impostors.length; ++t)
            if (this._impostors[t].object === e)
                return this._impostors[t];
        return null
    }
    ,
    i.prototype.getImpostorWithPhysicsBody = function(e) {
        for (var t = 0; t < this._impostors.length; ++t)
            if (this._impostors[t].physicsBody === e)
                return this._impostors[t];
        return null
    }
    ,
    i.prototype.raycast = function(e, t) {
        return this._physicsPlugin.raycast(e, t)
    }
    ,
    i.Epsilon = .001,
    i
}()
  , PhysicsRaycastResult = function() {
    function i() {
        this._hasHit = !1,
        this._hitDistance = 0,
        this._hitNormalWorld = Vector3.Zero(),
        this._hitPointWorld = Vector3.Zero(),
        this._rayFromWorld = Vector3.Zero(),
        this._rayToWorld = Vector3.Zero()
    }
    return Object.defineProperty(i.prototype, "hasHit", {
        get: function() {
            return this._hasHit
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "hitDistance", {
        get: function() {
            return this._hitDistance
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "hitNormalWorld", {
        get: function() {
            return this._hitNormalWorld
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "hitPointWorld", {
        get: function() {
            return this._hitPointWorld
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "rayFromWorld", {
        get: function() {
            return this._rayFromWorld
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "rayToWorld", {
        get: function() {
            return this._rayToWorld
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.setHitData = function(e, t) {
        this._hasHit = !0,
        this._hitNormalWorld = new Vector3(e.x,e.y,e.z),
        this._hitPointWorld = new Vector3(t.x,t.y,t.z)
    }
    ,
    i.prototype.setHitDistance = function(e) {
        this._hitDistance = e
    }
    ,
    i.prototype.calculateHitDistance = function() {
        this._hitDistance = Vector3.Distance(this._rayFromWorld, this._hitPointWorld)
    }
    ,
    i.prototype.reset = function(e, t) {
        e === void 0 && (e = Vector3.Zero()),
        t === void 0 && (t = Vector3.Zero()),
        this._rayFromWorld = e,
        this._rayToWorld = t,
        this._hasHit = !1,
        this._hitDistance = 0,
        this._hitNormalWorld = Vector3.Zero(),
        this._hitPointWorld = Vector3.Zero()
    }
    ,
    i
}()
  , CannonJSPlugin = function() {
    function i(e, t, r) {
        if (e === void 0 && (e = !0),
        t === void 0 && (t = 10),
        r === void 0 && (r = CANNON),
        this._useDeltaForWorldStep = e,
        this.name = "CannonJSPlugin",
        this._physicsMaterials = new Array,
        this._fixedTimeStep = 1 / 60,
        this._physicsBodysToRemoveAfterStep = new Array,
        this._firstFrame = !0,
        this._tmpQuaternion = new Quaternion,
        this._minus90X = new Quaternion(-.7071067811865475,0,0,.7071067811865475),
        this._plus90X = new Quaternion(.7071067811865475,0,0,.7071067811865475),
        this._tmpPosition = Vector3.Zero(),
        this._tmpDeltaPosition = Vector3.Zero(),
        this._tmpUnityRotation = new Quaternion,
        this.BJSCANNON = r,
        !this.isSupported()) {
            Logger$2.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 = t,
        this._cannonRaycastResult = new this.BJSCANNON.RaycastResult,
        this._raycastResult = new PhysicsRaycastResult
    }
    return i.prototype.setGravity = function(e) {
        var t = e;
        this.world.gravity.set(t.x, t.y, t.z)
    }
    ,
    i.prototype.setTimeStep = function(e) {
        this._fixedTimeStep = e
    }
    ,
    i.prototype.getTimeStep = function() {
        return this._fixedTimeStep
    }
    ,
    i.prototype.executeStep = function(e, t) {
        if (this._firstFrame) {
            this._firstFrame = !1;
            for (var r = 0, n = t; r < n.length; r++) {
                var o = n[r];
                o.type == PhysicsImpostor.HeightmapImpostor || o.type === PhysicsImpostor.PlaneImpostor || o.beforeStep()
            }
        }
        this.world.step(this._useDeltaForWorldStep ? e : this._fixedTimeStep),
        this._removeMarkedPhysicsBodiesFromWorld()
    }
    ,
    i.prototype._removeMarkedPhysicsBodiesFromWorld = function() {
        var e = this;
        this._physicsBodysToRemoveAfterStep.length > 0 && (this._physicsBodysToRemoveAfterStep.forEach(function(t) {
            typeof e.world.removeBody == "function" ? e.world.removeBody(t) : e.world.remove(t)
        }),
        this._physicsBodysToRemoveAfterStep = [])
    }
    ,
    i.prototype.applyImpulse = function(e, t, r) {
        var n = new this.BJSCANNON.Vec3(r.x,r.y,r.z)
          , o = new this.BJSCANNON.Vec3(t.x,t.y,t.z);
        e.physicsBody.applyImpulse(o, n)
    }
    ,
    i.prototype.applyForce = function(e, t, r) {
        var n = new this.BJSCANNON.Vec3(r.x,r.y,r.z)
          , o = new this.BJSCANNON.Vec3(t.x,t.y,t.z);
        e.physicsBody.applyForce(o, n)
    }
    ,
    i.prototype.generatePhysicsBody = function(e) {
        if (this._removeMarkedPhysicsBodiesFromWorld(),
        e.parent) {
            e.physicsBody && (this.removePhysicsBody(e),
            e.forceUpdate());
            return
        }
        if (e.isBodyInitRequired()) {
            var t = this._createShape(e)
              , r = e.physicsBody;
            r && this.removePhysicsBody(e);
            var n = this._addMaterial("mat-" + e.uniqueId, e.getParam("friction"), e.getParam("restitution"))
              , o = {
                mass: e.getParam("mass"),
                material: n
            }
              , a = e.getParam("nativeOptions");
            for (var s in a)
                a.hasOwnProperty(s) && (o[s] = a[s]);
            e.physicsBody = new this.BJSCANNON.Body(o),
            e.physicsBody.addEventListener("collide", e.onCollide),
            this.world.addEventListener("preStep", e.beforeStep),
            this.world.addEventListener("postStep", e.afterStep),
            e.physicsBody.addShape(t),
            typeof this.world.addBody == "function" ? this.world.addBody(e.physicsBody) : this.world.add(e.physicsBody),
            r && ["force", "torque", "velocity", "angularVelocity"].forEach(function(l) {
                var u = r[l];
                e.physicsBody[l].set(u.x, u.y, u.z)
            }),
            this._processChildMeshes(e)
        }
        this._updatePhysicsBodyTransformation(e)
    }
    ,
    i.prototype._processChildMeshes = function(e) {
        var t = this
          , r = e.object.getChildMeshes ? e.object.getChildMeshes(!0) : []
          , n = e.object.rotationQuaternion;
        if (n ? n.conjugateToRef(this._tmpQuaternion) : this._tmpQuaternion.set(0, 0, 0, 1),
        r.length) {
            var o = function(a) {
                if (!!a.rotationQuaternion) {
                    var s = a.getPhysicsImpostor();
                    if (s) {
                        var l = s.parent;
                        if (l !== e && a.parent) {
                            var u = a.getAbsolutePosition().subtract(a.parent.getAbsolutePosition())
                              , c = a.rotationQuaternion.multiply(t._tmpQuaternion);
                            s.physicsBody && (t.removePhysicsBody(s),
                            s.physicsBody = null),
                            s.parent = e,
                            s.resetUpdateFlags(),
                            e.physicsBody.addShape(t._createShape(s), new t.BJSCANNON.Vec3(u.x,u.y,u.z), new t.BJSCANNON.Quaternion(c.x,c.y,c.z,c.w)),
                            e.physicsBody.mass += s.getParam("mass")
                        }
                    }
                    a.getChildMeshes(!0).filter(function(h) {
                        return !!h.physicsImpostor
                    }).forEach(o)
                }
            };
            r.filter(function(a) {
                return !!a.physicsImpostor
            }).forEach(o)
        }
    }
    ,
    i.prototype.removePhysicsBody = function(e) {
        e.physicsBody.removeEventListener("collide", e.onCollide),
        this.world.removeEventListener("preStep", e.beforeStep),
        this.world.removeEventListener("postStep", e.afterStep),
        this._physicsBodysToRemoveAfterStep.indexOf(e.physicsBody) === -1 && this._physicsBodysToRemoveAfterStep.push(e.physicsBody)
    }
    ,
    i.prototype.generateJoint = function(e) {
        var t = e.mainImpostor.physicsBody
          , r = e.connectedImpostor.physicsBody;
        if (!(!t || !r)) {
            var n, o = e.joint.jointData, a = {
                pivotA: o.mainPivot ? new this.BJSCANNON.Vec3().set(o.mainPivot.x, o.mainPivot.y, o.mainPivot.z) : null,
                pivotB: o.connectedPivot ? new this.BJSCANNON.Vec3().set(o.connectedPivot.x, o.connectedPivot.y, o.connectedPivot.z) : null,
                axisA: o.mainAxis ? new this.BJSCANNON.Vec3().set(o.mainAxis.x, o.mainAxis.y, o.mainAxis.z) : null,
                axisB: o.connectedAxis ? new this.BJSCANNON.Vec3().set(o.connectedAxis.x, o.connectedAxis.y, o.connectedAxis.z) : null,
                maxForce: o.nativeParams.maxForce,
                collideConnected: !!o.collision
            };
            switch (e.joint.type) {
            case PhysicsJoint.HingeJoint:
            case PhysicsJoint.Hinge2Joint:
                n = new this.BJSCANNON.HingeConstraint(t,r,a);
                break;
            case PhysicsJoint.DistanceJoint:
                n = new this.BJSCANNON.DistanceConstraint(t,r,o.maxDistance || 2);
                break;
            case PhysicsJoint.SpringJoint:
                var s = o;
                n = new this.BJSCANNON.Spring(t,r,{
                    restLength: s.length,
                    stiffness: s.stiffness,
                    damping: s.damping,
                    localAnchorA: a.pivotA,
                    localAnchorB: a.pivotB
                });
                break;
            case PhysicsJoint.LockJoint:
                n = new this.BJSCANNON.LockConstraint(t,r,a);
                break;
            case PhysicsJoint.PointToPointJoint:
            case PhysicsJoint.BallAndSocketJoint:
            default:
                n = new this.BJSCANNON.PointToPointConstraint(t,a.pivotA,r,a.pivotB,a.maxForce);
                break
            }
            n.collideConnected = !!o.collision,
            e.joint.physicsJoint = n,
            e.joint.type !== PhysicsJoint.SpringJoint ? this.world.addConstraint(n) : (e.joint.jointData.forceApplicationCallback = e.joint.jointData.forceApplicationCallback || function() {
                n.applyForce()
            }
            ,
            e.mainImpostor.registerAfterPhysicsStep(e.joint.jointData.forceApplicationCallback))
        }
    }
    ,
    i.prototype.removeJoint = function(e) {
        e.joint.type !== PhysicsJoint.SpringJoint ? this.world.removeConstraint(e.joint.physicsJoint) : e.mainImpostor.unregisterAfterPhysicsStep(e.joint.jointData.forceApplicationCallback)
    }
    ,
    i.prototype._addMaterial = function(e, t, r) {
        var n, o;
        for (n = 0; n < this._physicsMaterials.length; n++)
            if (o = this._physicsMaterials[n],
            o.friction === t && o.restitution === r)
                return o;
        var a = new this.BJSCANNON.Material(e);
        return a.friction = t,
        a.restitution = r,
        this._physicsMaterials.push(a),
        a
    }
    ,
    i.prototype._checkWithEpsilon = function(e) {
        return e < PhysicsEngine.Epsilon ? PhysicsEngine.Epsilon : e
    }
    ,
    i.prototype._createShape = function(e) {
        var t = e.object, r, n = e.getObjectExtendSize();
        switch (e.type) {
        case PhysicsImpostor.SphereImpostor:
            var o = n.x
              , a = n.y
              , s = n.z;
            r = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(o), this._checkWithEpsilon(a), this._checkWithEpsilon(s)) / 2);
            break;
        case PhysicsImpostor.CylinderImpostor:
            var l = e.getParam("nativeOptions");
            l || (l = {});
            var u = l.radiusTop !== void 0 ? l.radiusTop : this._checkWithEpsilon(n.x) / 2
              , c = l.radiusBottom !== void 0 ? l.radiusBottom : this._checkWithEpsilon(n.x) / 2
              , h = l.height !== void 0 ? l.height : this._checkWithEpsilon(n.y)
              , f = l.numSegments !== void 0 ? l.numSegments : 16;
            r = new this.BJSCANNON.Cylinder(u,c,h,f);
            var d = new this.BJSCANNON.Quaternion;
            d.setFromAxisAngle(new this.BJSCANNON.Vec3(1,0,0), -Math.PI / 2);
            var _ = new this.BJSCANNON.Vec3(0,0,0);
            r.transformAllPoints(_, d);
            break;
        case PhysicsImpostor.BoxImpostor:
            var g = n.scale(.5);
            r = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(g.x),this._checkWithEpsilon(g.y),this._checkWithEpsilon(g.z)));
            break;
        case PhysicsImpostor.PlaneImpostor:
            Logger$2.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead"),
            r = new this.BJSCANNON.Plane;
            break;
        case PhysicsImpostor.MeshImpostor:
            var m = t.getVerticesData ? t.getVerticesData(VertexBuffer.PositionKind) : []
              , v = t.getIndices ? t.getIndices() : [];
            if (!m)
                return;
            var y = t.position.clone()
              , b = t.rotation && t.rotation.clone()
              , T = t.rotationQuaternion && t.rotationQuaternion.clone();
            t.position.copyFromFloats(0, 0, 0),
            t.rotation && t.rotation.copyFromFloats(0, 0, 0),
            t.rotationQuaternion && t.rotationQuaternion.copyFrom(e.getParentsRotation()),
            t.rotationQuaternion && t.parent && t.rotationQuaternion.conjugateInPlace();
            var C = t.computeWorldMatrix(!0), A = new Array, S;
            for (S = 0; S < m.length; S += 3)
                Vector3.TransformCoordinates(Vector3.FromArray(m, S), C).toArray(A, S);
            Logger$2.Warn("MeshImpostor only collides against spheres."),
            r = new this.BJSCANNON.Trimesh(A,v),
            t.position.copyFrom(y),
            b && t.rotation && t.rotation.copyFrom(b),
            T && t.rotationQuaternion && t.rotationQuaternion.copyFrom(T);
            break;
        case PhysicsImpostor.HeightmapImpostor:
            var P = t.position.clone()
              , R = t.rotation && t.rotation.clone()
              , M = t.rotationQuaternion && t.rotationQuaternion.clone();
            t.position.copyFromFloats(0, 0, 0),
            t.rotation && t.rotation.copyFromFloats(0, 0, 0),
            t.rotationQuaternion && t.rotationQuaternion.copyFrom(e.getParentsRotation()),
            t.rotationQuaternion && t.parent && t.rotationQuaternion.conjugateInPlace(),
            t.rotationQuaternion && t.rotationQuaternion.multiplyInPlace(this._minus90X),
            r = this._createHeightmap(t),
            t.position.copyFrom(P),
            R && t.rotation && t.rotation.copyFrom(R),
            M && t.rotationQuaternion && t.rotationQuaternion.copyFrom(M),
            t.computeWorldMatrix(!0);
            break;
        case PhysicsImpostor.ParticleImpostor:
            r = new this.BJSCANNON.Particle;
            break;
        case PhysicsImpostor.NoImpostor:
            r = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(0,0,0));
            break
        }
        return r
    }
    ,
    i.prototype._createHeightmap = function(e, t) {
        var r = e.getVerticesData(VertexBuffer.PositionKind), n = e.computeWorldMatrix(!0), o = new Array, a;
        for (a = 0; a < r.length; a += 3)
            Vector3.TransformCoordinates(Vector3.FromArray(r, a), n).toArray(o, a);
        r = o;
        for (var s = new Array, l = t || ~~(Math.sqrt(r.length / 3) - 1), u = e.getBoundingInfo(), c = Math.min(u.boundingBox.extendSizeWorld.x, u.boundingBox.extendSizeWorld.y), h = u.boundingBox.extendSizeWorld.z, f = c * 2 / l, d = 0; d < r.length; d = d + 3) {
            var _ = Math.round(r[d + 0] / f + l / 2)
              , g = Math.round((r[d + 1] / f - l / 2) * -1)
              , m = -r[d + 2] + h;
            s[_] || (s[_] = []),
            s[_][g] || (s[_][g] = m),
            s[_][g] = Math.max(m, s[_][g])
        }
        for (var _ = 0; _ <= l; ++_) {
            if (!s[_]) {
                for (var v = 1; !s[(_ + v) % l]; )
                    v++;
                s[_] = s[(_ + v) % l].slice()
            }
            for (var g = 0; g <= l; ++g)
                if (!s[_][g]) {
                    for (var v = 1, y; y === void 0; )
                        y = s[_][(g + v++) % l];
                    s[_][g] = y
                }
        }
        var b = new this.BJSCANNON.Heightfield(s,{
            elementSize: f
        });
        return b.minY = h,
        b
    }
    ,
    i.prototype._updatePhysicsBodyTransformation = function(e) {
        var t = e.object;
        if (t.computeWorldMatrix && t.computeWorldMatrix(!0),
        !!t.getBoundingInfo()) {
            var r = e.getObjectCenter();
            this._tmpDeltaPosition.copyFrom(t.getAbsolutePivotPoint().subtract(r)),
            this._tmpDeltaPosition.divideInPlace(e.object.scaling),
            this._tmpPosition.copyFrom(r);
            var n = t.rotationQuaternion;
            if (!!n) {
                if ((e.type === PhysicsImpostor.PlaneImpostor || e.type === PhysicsImpostor.HeightmapImpostor) && (n = n.multiply(this._minus90X),
                e.setDeltaRotation(this._plus90X)),
                e.type === PhysicsImpostor.HeightmapImpostor) {
                    var o = t
                      , a = o.getBoundingInfo()
                      , s = o.rotationQuaternion;
                    o.rotationQuaternion = this._tmpUnityRotation,
                    o.computeWorldMatrix(!0);
                    var l = r.clone()
                      , u = o.getPivotMatrix();
                    u ? u = u.clone() : u = Matrix.Identity();
                    var c = Matrix.Translation(a.boundingBox.extendSizeWorld.x, 0, -a.boundingBox.extendSizeWorld.z);
                    o.setPreTransformMatrix(c),
                    o.computeWorldMatrix(!0),
                    a = o.getBoundingInfo();
                    var h = a.boundingBox.centerWorld.subtract(r).subtract(o.position).negate();
                    this._tmpPosition.copyFromFloats(h.x, h.y - a.boundingBox.extendSizeWorld.y, h.z),
                    this._tmpDeltaPosition.copyFrom(a.boundingBox.centerWorld.subtract(l)),
                    this._tmpDeltaPosition.y += a.boundingBox.extendSizeWorld.y,
                    o.rotationQuaternion = s,
                    o.setPreTransformMatrix(u),
                    o.computeWorldMatrix(!0)
                } else
                    e.type === PhysicsImpostor.MeshImpostor && this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
                e.setDeltaPosition(this._tmpDeltaPosition),
                e.physicsBody.position.set(this._tmpPosition.x, this._tmpPosition.y, this._tmpPosition.z),
                e.physicsBody.quaternion.set(n.x, n.y, n.z, n.w)
            }
        }
    }
    ,
    i.prototype.setTransformationFromPhysicsBody = function(e) {
        if (e.object.position.set(e.physicsBody.position.x, e.physicsBody.position.y, e.physicsBody.position.z),
        e.object.rotationQuaternion) {
            var t = e.physicsBody.quaternion;
            e.object.rotationQuaternion.set(t.x, t.y, t.z, t.w)
        }
    }
    ,
    i.prototype.setPhysicsBodyTransformation = function(e, t, r) {
        e.physicsBody.position.set(t.x, t.y, t.z),
        e.physicsBody.quaternion.set(r.x, r.y, r.z, r.w)
    }
    ,
    i.prototype.isSupported = function() {
        return this.BJSCANNON !== void 0
    }
    ,
    i.prototype.setLinearVelocity = function(e, t) {
        e.physicsBody.velocity.set(t.x, t.y, t.z)
    }
    ,
    i.prototype.setAngularVelocity = function(e, t) {
        e.physicsBody.angularVelocity.set(t.x, t.y, t.z)
    }
    ,
    i.prototype.getLinearVelocity = function(e) {
        var t = e.physicsBody.velocity;
        return t ? new Vector3(t.x,t.y,t.z) : null
    }
    ,
    i.prototype.getAngularVelocity = function(e) {
        var t = e.physicsBody.angularVelocity;
        return t ? new Vector3(t.x,t.y,t.z) : null
    }
    ,
    i.prototype.setBodyMass = function(e, t) {
        e.physicsBody.mass = t,
        e.physicsBody.updateMassProperties()
    }
    ,
    i.prototype.getBodyMass = function(e) {
        return e.physicsBody.mass
    }
    ,
    i.prototype.getBodyFriction = function(e) {
        return e.physicsBody.material.friction
    }
    ,
    i.prototype.setBodyFriction = function(e, t) {
        e.physicsBody.material.friction = t
    }
    ,
    i.prototype.getBodyRestitution = function(e) {
        return e.physicsBody.material.restitution
    }
    ,
    i.prototype.setBodyRestitution = function(e, t) {
        e.physicsBody.material.restitution = t
    }
    ,
    i.prototype.sleepBody = function(e) {
        e.physicsBody.sleep()
    }
    ,
    i.prototype.wakeUpBody = function(e) {
        e.physicsBody.wakeUp()
    }
    ,
    i.prototype.updateDistanceJoint = function(e, t) {
        e.physicsJoint.distance = t
    }
    ,
    i.prototype.setMotor = function(e, t, r, n) {
        n || (e.physicsJoint.enableMotor(),
        e.physicsJoint.setMotorSpeed(t),
        r && this.setLimit(e, r))
    }
    ,
    i.prototype.setLimit = function(e, t, r) {
        e.physicsJoint.motorEquation.maxForce = t,
        e.physicsJoint.motorEquation.minForce = r === void 0 ? -t : r
    }
    ,
    i.prototype.syncMeshWithImpostor = function(e, t) {
        var r = t.physicsBody;
        e.position.x = r.position.x,
        e.position.y = r.position.y,
        e.position.z = r.position.z,
        e.rotationQuaternion && (e.rotationQuaternion.x = r.quaternion.x,
        e.rotationQuaternion.y = r.quaternion.y,
        e.rotationQuaternion.z = r.quaternion.z,
        e.rotationQuaternion.w = r.quaternion.w)
    }
    ,
    i.prototype.getRadius = function(e) {
        var t = e.physicsBody.shapes[0];
        return t.boundingSphereRadius
    }
    ,
    i.prototype.getBoxSizeToRef = function(e, t) {
        var r = e.physicsBody.shapes[0];
        t.x = r.halfExtents.x * 2,
        t.y = r.halfExtents.y * 2,
        t.z = r.halfExtents.z * 2
    }
    ,
    i.prototype.dispose = function() {}
    ,
    i.prototype._extendNamespace = function() {
        var e = new this.BJSCANNON.Vec3
          , t = this.BJSCANNON;
        this.BJSCANNON.World.prototype.step = function(r, n, o) {
            if (o = o || 10,
            n = n || 0,
            n === 0)
                this.internalStep(r),
                this.time += r;
            else {
                var a = Math.floor((this.time + n) / r) - Math.floor(this.time / r);
                a = Math.min(a, o) || 1;
                for (var s = performance.now(), l = 0; l !== a && (this.internalStep(r),
                !(performance.now() - s > r * 1e3)); l++)
                    ;
                this.time += n;
                for (var u = this.time % r, c = u / r, h = e, f = this.bodies, d = 0; d !== f.length; d++) {
                    var _ = f[d];
                    _.type !== t.Body.STATIC && _.sleepState !== t.Body.SLEEPING ? (_.position.vsub(_.previousPosition, h),
                    h.scale(c, h),
                    _.position.vadd(h, _.interpolatedPosition)) : (_.interpolatedPosition.set(_.position.x, _.position.y, _.position.z),
                    _.interpolatedQuaternion.set(_.quaternion.x, _.quaternion.y, _.quaternion.z, _.quaternion.w))
                }
            }
        }
    }
    ,
    i.prototype.raycast = function(e, t) {
        return this._cannonRaycastResult.reset(),
        this.world.raycastClosest(e, t, {}, this._cannonRaycastResult),
        this._raycastResult.reset(e, t),
        this._cannonRaycastResult.hasHit && (this._raycastResult.setHitData({
            x: this._cannonRaycastResult.hitNormalWorld.x,
            y: this._cannonRaycastResult.hitNormalWorld.y,
            z: this._cannonRaycastResult.hitNormalWorld.z
        }, {
            x: this._cannonRaycastResult.hitPointWorld.x,
            y: this._cannonRaycastResult.hitPointWorld.y,
            z: this._cannonRaycastResult.hitPointWorld.z
        }),
        this._raycastResult.setHitDistance(this._cannonRaycastResult.distance)),
        this._raycastResult
    }
    ,
    i
}();
PhysicsEngine.DefaultPluginFactory = function() {
    return new CannonJSPlugin
}
;
var OimoJSPlugin = function() {
    function i(e, t, r) {
        e === void 0 && (e = !0),
        r === void 0 && (r = OIMO),
        this._useDeltaForWorldStep = e,
        this.name = "OimoJSPlugin",
        this._fixedTimeStep = 1 / 60,
        this._tmpImpostorsArray = [],
        this._tmpPositionVector = Vector3.Zero(),
        this.BJSOIMO = r,
        this.world = new this.BJSOIMO.World({
            iterations: t
        }),
        this.world.clear(),
        this._raycastResult = new PhysicsRaycastResult
    }
    return i.prototype.setGravity = function(e) {
        this.world.gravity.set(e.x, e.y, e.z)
    }
    ,
    i.prototype.setTimeStep = function(e) {
        this.world.timeStep = e
    }
    ,
    i.prototype.getTimeStep = function() {
        return this.world.timeStep
    }
    ,
    i.prototype.executeStep = function(e, t) {
        var r = this;
        t.forEach(function(s) {
            s.beforeStep()
        }),
        this.world.timeStep = this._useDeltaForWorldStep ? e : this._fixedTimeStep,
        this.world.step(),
        t.forEach(function(s) {
            s.afterStep(),
            r._tmpImpostorsArray[s.uniqueId] = s
        });
        for (var n = this.world.contacts; n !== null; ) {
            if (n.touching && !n.body1.sleeping && !n.body2.sleeping) {
                n = n.next;
                continue
            }
            var o = this._tmpImpostorsArray[+n.body1.name]
              , a = this._tmpImpostorsArray[+n.body2.name];
            if (!o || !a) {
                n = n.next;
                continue
            }
            o.onCollide({
                body: a.physicsBody,
                point: null
            }),
            a.onCollide({
                body: o.physicsBody,
                point: null
            }),
            n = n.next
        }
    }
    ,
    i.prototype.applyImpulse = function(e, t, r) {
        var n = e.physicsBody.mass;
        e.physicsBody.applyImpulse(r.scale(this.world.invScale), t.scale(this.world.invScale * n))
    }
    ,
    i.prototype.applyForce = function(e, t, r) {
        Logger$2.Warn("Oimo doesn't support applying force. Using impule instead."),
        this.applyImpulse(e, t, r)
    }
    ,
    i.prototype.generatePhysicsBody = function(e) {
        var t = this;
        if (e.parent) {
            e.physicsBody && (this.removePhysicsBody(e),
            e.forceUpdate());
            return
        }
        if (e.isBodyInitRequired()) {
            var r = {
                name: e.uniqueId,
                config: [e.getParam("mass") || .001, e.getParam("friction"), e.getParam("restitution")],
                size: [],
                type: [],
                pos: [],
                posShape: [],
                rot: [],
                rotShape: [],
                move: e.getParam("mass") !== 0,
                density: e.getParam("mass"),
                friction: e.getParam("friction"),
                restitution: e.getParam("restitution"),
                world: this.world
            }
              , n = [e]
              , o = function(l) {
                !l.getChildMeshes || l.getChildMeshes().forEach(function(u) {
                    u.physicsImpostor && n.push(u.physicsImpostor)
                })
            };
            o(e.object);
            var a = function(l) {
                return Math.max(l, PhysicsEngine.Epsilon)
            }
              , s = new Quaternion;
            n.forEach(function(l) {
                if (!!l.object.rotationQuaternion) {
                    var u = l.object.rotationQuaternion;
                    s.copyFrom(u),
                    l.object.rotationQuaternion.set(0, 0, 0, 1),
                    l.object.computeWorldMatrix(!0);
                    var c = s.toEulerAngles()
                      , h = l.getObjectExtendSize()
                      , f = 57.29577951308232;
                    if (l === e) {
                        var d = e.getObjectCenter();
                        e.object.getAbsolutePivotPoint().subtractToRef(d, t._tmpPositionVector),
                        t._tmpPositionVector.divideInPlace(e.object.scaling),
                        r.pos.push(d.x),
                        r.pos.push(d.y),
                        r.pos.push(d.z),
                        r.posShape.push(0, 0, 0),
                        r.rotShape.push(0, 0, 0)
                    } else {
                        var _ = l.object.position.clone();
                        r.posShape.push(_.x),
                        r.posShape.push(_.y),
                        r.posShape.push(_.z),
                        r.rotShape.push(c.x * f, c.y * f, c.z * f)
                    }
                    switch (l.object.rotationQuaternion.copyFrom(s),
                    l.type) {
                    case PhysicsImpostor.ParticleImpostor:
                        Logger$2.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
                    case PhysicsImpostor.SphereImpostor:
                        var g = h.x
                          , m = h.y
                          , v = h.z
                          , y = Math.max(a(g), a(m), a(v)) / 2;
                        r.type.push("sphere"),
                        r.size.push(y),
                        r.size.push(y),
                        r.size.push(y);
                        break;
                    case PhysicsImpostor.CylinderImpostor:
                        var b = a(h.x) / 2
                          , T = a(h.y);
                        r.type.push("cylinder"),
                        r.size.push(b),
                        r.size.push(T),
                        r.size.push(T);
                        break;
                    case PhysicsImpostor.PlaneImpostor:
                    case PhysicsImpostor.BoxImpostor:
                    default:
                        var b = a(h.x)
                          , T = a(h.y)
                          , C = a(h.z);
                        r.type.push("box"),
                        r.size.push(b),
                        r.size.push(T),
                        r.size.push(C);
                        break
                    }
                    l.object.rotationQuaternion = u
                }
            }),
            e.physicsBody = this.world.add(r),
            e.physicsBody.resetQuaternion(s),
            e.physicsBody.updatePosition(0)
        } else
            this._tmpPositionVector.copyFromFloats(0, 0, 0);
        e.setDeltaPosition(this._tmpPositionVector)
    }
    ,
    i.prototype.removePhysicsBody = function(e) {
        this.world.removeRigidBody(e.physicsBody)
    }
    ,
    i.prototype.generateJoint = function(e) {
        var t = e.mainImpostor.physicsBody
          , r = e.connectedImpostor.physicsBody;
        if (!(!t || !r)) {
            var n = e.joint.jointData, o = n.nativeParams || {}, a, s = {
                body1: t,
                body2: r,
                axe1: o.axe1 || (n.mainAxis ? n.mainAxis.asArray() : null),
                axe2: o.axe2 || (n.connectedAxis ? n.connectedAxis.asArray() : null),
                pos1: o.pos1 || (n.mainPivot ? n.mainPivot.asArray() : null),
                pos2: o.pos2 || (n.connectedPivot ? n.connectedPivot.asArray() : null),
                min: o.min,
                max: o.max,
                collision: o.collision || n.collision,
                spring: o.spring,
                world: this.world
            };
            switch (e.joint.type) {
            case PhysicsJoint.BallAndSocketJoint:
                a = "jointBall";
                break;
            case PhysicsJoint.SpringJoint:
                Logger$2.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
                var l = n;
                s.min = l.length || s.min,
                s.max = Math.max(s.min, s.max);
            case PhysicsJoint.DistanceJoint:
                a = "jointDistance",
                s.max = n.maxDistance;
                break;
            case PhysicsJoint.PrismaticJoint:
                a = "jointPrisme";
                break;
            case PhysicsJoint.SliderJoint:
                a = "jointSlide";
                break;
            case PhysicsJoint.WheelJoint:
                a = "jointWheel";
                break;
            case PhysicsJoint.HingeJoint:
            default:
                a = "jointHinge";
                break
            }
            s.type = a,
            e.joint.physicsJoint = this.world.add(s)
        }
    }
    ,
    i.prototype.removeJoint = function(e) {
        try {
            this.world.removeJoint(e.joint.physicsJoint)
        } catch (t) {
            Logger$2.Warn(t)
        }
    }
    ,
    i.prototype.isSupported = function() {
        return this.BJSOIMO !== void 0
    }
    ,
    i.prototype.setTransformationFromPhysicsBody = function(e) {
        if (!e.physicsBody.sleeping) {
            if (e.physicsBody.shapes.next) {
                for (var t = e.physicsBody.shapes; t.next; )
                    t = t.next;
                e.object.position.set(t.position.x, t.position.y, t.position.z)
            } else {
                var r = e.physicsBody.getPosition();
                e.object.position.set(r.x, r.y, r.z)
            }
            if (e.object.rotationQuaternion) {
                var n = e.physicsBody.getQuaternion();
                e.object.rotationQuaternion.set(n.x, n.y, n.z, n.w)
            }
        }
    }
    ,
    i.prototype.setPhysicsBodyTransformation = function(e, t, r) {
        var n = e.physicsBody;
        e.physicsBody.shapes.next || (n.position.set(t.x, t.y, t.z),
        n.orientation.set(r.x, r.y, r.z, r.w),
        n.syncShapes(),
        n.awake())
    }
    ,
    i.prototype.setLinearVelocity = function(e, t) {
        e.physicsBody.linearVelocity.set(t.x, t.y, t.z)
    }
    ,
    i.prototype.setAngularVelocity = function(e, t) {
        e.physicsBody.angularVelocity.set(t.x, t.y, t.z)
    }
    ,
    i.prototype.getLinearVelocity = function(e) {
        var t = e.physicsBody.linearVelocity;
        return t ? new Vector3(t.x,t.y,t.z) : null
    }
    ,
    i.prototype.getAngularVelocity = function(e) {
        var t = e.physicsBody.angularVelocity;
        return t ? new Vector3(t.x,t.y,t.z) : null
    }
    ,
    i.prototype.setBodyMass = function(e, t) {
        var r = t === 0;
        e.physicsBody.shapes.density = r ? 1 : t,
        e.physicsBody.setupMass(r ? 2 : 1)
    }
    ,
    i.prototype.getBodyMass = function(e) {
        return e.physicsBody.shapes.density
    }
    ,
    i.prototype.getBodyFriction = function(e) {
        return e.physicsBody.shapes.friction
    }
    ,
    i.prototype.setBodyFriction = function(e, t) {
        e.physicsBody.shapes.friction = t
    }
    ,
    i.prototype.getBodyRestitution = function(e) {
        return e.physicsBody.shapes.restitution
    }
    ,
    i.prototype.setBodyRestitution = function(e, t) {
        e.physicsBody.shapes.restitution = t
    }
    ,
    i.prototype.sleepBody = function(e) {
        e.physicsBody.sleep()
    }
    ,
    i.prototype.wakeUpBody = function(e) {
        e.physicsBody.awake()
    }
    ,
    i.prototype.updateDistanceJoint = function(e, t, r) {
        e.physicsJoint.limitMotor.upperLimit = t,
        r !== void 0 && (e.physicsJoint.limitMotor.lowerLimit = r)
    }
    ,
    i.prototype.setMotor = function(e, t, r, n) {
        r !== void 0 ? Logger$2.Warn("OimoJS plugin currently has unexpected behavior when using setMotor with force parameter") : r = 1e6,
        t *= -1;
        var o = n ? e.physicsJoint.rotationalLimitMotor2 : e.physicsJoint.rotationalLimitMotor1 || e.physicsJoint.rotationalLimitMotor || e.physicsJoint.limitMotor;
        o && o.setMotor(t, r)
    }
    ,
    i.prototype.setLimit = function(e, t, r, n) {
        var o = n ? e.physicsJoint.rotationalLimitMotor2 : e.physicsJoint.rotationalLimitMotor1 || e.physicsJoint.rotationalLimitMotor || e.physicsJoint.limitMotor;
        o && o.setLimit(t, r === void 0 ? -t : r)
    }
    ,
    i.prototype.syncMeshWithImpostor = function(e, t) {
        var r = t.physicsBody;
        e.position.x = r.position.x,
        e.position.y = r.position.y,
        e.position.z = r.position.z,
        e.rotationQuaternion && (e.rotationQuaternion.x = r.orientation.x,
        e.rotationQuaternion.y = r.orientation.y,
        e.rotationQuaternion.z = r.orientation.z,
        e.rotationQuaternion.w = r.orientation.s)
    }
    ,
    i.prototype.getRadius = function(e) {
        return e.physicsBody.shapes.radius
    }
    ,
    i.prototype.getBoxSizeToRef = function(e, t) {
        var r = e.physicsBody.shapes;
        t.x = r.halfWidth * 2,
        t.y = r.halfHeight * 2,
        t.z = r.halfDepth * 2
    }
    ,
    i.prototype.dispose = function() {
        this.world.clear()
    }
    ,
    i.prototype.raycast = function(e, t) {
        return Logger$2.Warn("raycast is not currently supported by the Oimo physics plugin"),
        this._raycastResult.reset(e, t),
        this._raycastResult
    }
    ,
    i
}()
  , AmmoJSPlugin = function() {
    function i(e, t, r) {
        var n = this;
        if (e === void 0 && (e = !0),
        t === void 0 && (t = Ammo),
        r === void 0 && (r = null),
        this._useDeltaForWorldStep = e,
        this.bjsAMMO = {},
        this.name = "AmmoJSPlugin",
        this._timeStep = 1 / 60,
        this._fixedTimeStep = 1 / 60,
        this._maxSteps = 5,
        this._tmpQuaternion = new Quaternion,
        this._tmpContactCallbackResult = !1,
        this._tmpContactPoint = new Vector3,
        this._tmpVec3 = new Vector3,
        this._tmpMatrix = new Matrix,
        typeof t == "function") {
            Logger$2.Error("AmmoJS is not ready. Please make sure you await Ammo() before using the plugin.");
            return
        } else
            this.bjsAMMO = t;
        if (!this.isSupported()) {
            Logger$2.Error("AmmoJS is not available. Please make sure you included the js file.");
            return
        }
        this._collisionConfiguration = new this.bjsAMMO.btSoftBodyRigidBodyCollisionConfiguration,
        this._dispatcher = new this.bjsAMMO.btCollisionDispatcher(this._collisionConfiguration),
        this._overlappingPairCache = r || new this.bjsAMMO.btDbvtBroadphase,
        this._solver = new this.bjsAMMO.btSequentialImpulseConstraintSolver,
        this._softBodySolver = new this.bjsAMMO.btDefaultSoftBodySolver,
        this.world = new this.bjsAMMO.btSoftRigidDynamicsWorld(this._dispatcher,this._overlappingPairCache,this._solver,this._collisionConfiguration,this._softBodySolver),
        this._tmpAmmoConcreteContactResultCallback = new this.bjsAMMO.ConcreteContactResultCallback,
        this._tmpAmmoConcreteContactResultCallback.addSingleResult = function(o, a, s, l) {
            o = n.bjsAMMO.wrapPointer(o, n.bjsAMMO.btManifoldPoint);
            var u = o.getPositionWorldOnA();
            n._tmpContactPoint.x = u.x(),
            n._tmpContactPoint.y = u.y(),
            n._tmpContactPoint.z = u.z(),
            n._tmpContactCallbackResult = !0
        }
        ,
        this._raycastResult = new PhysicsRaycastResult,
        this._tmpAmmoTransform = new this.bjsAMMO.btTransform,
        this._tmpAmmoTransform.setIdentity(),
        this._tmpAmmoQuaternion = new this.bjsAMMO.btQuaternion(0,0,0,1),
        this._tmpAmmoVectorA = new this.bjsAMMO.btVector3(0,0,0),
        this._tmpAmmoVectorB = new this.bjsAMMO.btVector3(0,0,0),
        this._tmpAmmoVectorC = new this.bjsAMMO.btVector3(0,0,0),
        this._tmpAmmoVectorD = new this.bjsAMMO.btVector3(0,0,0)
    }
    return i.prototype.setGravity = function(e) {
        this._tmpAmmoVectorA.setValue(e.x, e.y, e.z),
        this.world.setGravity(this._tmpAmmoVectorA),
        this.world.getWorldInfo().set_m_gravity(this._tmpAmmoVectorA)
    }
    ,
    i.prototype.setTimeStep = function(e) {
        this._timeStep = e
    }
    ,
    i.prototype.setFixedTimeStep = function(e) {
        this._fixedTimeStep = e
    }
    ,
    i.prototype.setMaxSteps = function(e) {
        this._maxSteps = e
    }
    ,
    i.prototype.getTimeStep = function() {
        return this._timeStep
    }
    ,
    i.prototype._isImpostorInContact = function(e) {
        return this._tmpContactCallbackResult = !1,
        this.world.contactTest(e.physicsBody, this._tmpAmmoConcreteContactResultCallback),
        this._tmpContactCallbackResult
    }
    ,
    i.prototype._isImpostorPairInContact = function(e, t) {
        return this._tmpContactCallbackResult = !1,
        this.world.contactPairTest(e.physicsBody, t.physicsBody, this._tmpAmmoConcreteContactResultCallback),
        this._tmpContactCallbackResult
    }
    ,
    i.prototype._stepSimulation = function(e, t, r) {
        if (e === void 0 && (e = 1 / 60),
        t === void 0 && (t = 10),
        r === void 0 && (r = 1 / 60),
        t == 0)
            this.world.stepSimulation(e, 0);
        else
            for (; t > 0 && e > 0; )
                e - r < r ? (this.world.stepSimulation(e, 0),
                e = 0) : (e -= r,
                this.world.stepSimulation(r, 0)),
                t--
    }
    ,
    i.prototype.executeStep = function(e, t) {
        for (var r = 0, n = t; r < n.length; r++) {
            var o = n[r];
            o.soft || o.beforeStep()
        }
        this._stepSimulation(this._useDeltaForWorldStep ? e : this._timeStep, this._maxSteps, this._fixedTimeStep);
        for (var a = 0, s = t; a < s.length; a++) {
            var l = s[a];
            if (l.soft ? this._afterSoftStep(l) : l.afterStep(),
            l._onPhysicsCollideCallbacks.length > 0 && this._isImpostorInContact(l))
                for (var u = 0, c = l._onPhysicsCollideCallbacks; u < c.length; u++)
                    for (var h = c[u], f = 0, d = h.otherImpostors; f < d.length; f++) {
                        var _ = d[f];
                        (l.physicsBody.isActive() || _.physicsBody.isActive()) && this._isImpostorPairInContact(l, _) && (l.onCollide({
                            body: _.physicsBody,
                            point: this._tmpContactPoint
                        }),
                        _.onCollide({
                            body: l.physicsBody,
                            point: this._tmpContactPoint
                        }))
                    }
        }
    }
    ,
    i.prototype._afterSoftStep = function(e) {
        e.type === PhysicsImpostor.RopeImpostor ? this._ropeStep(e) : this._softbodyOrClothStep(e)
    }
    ,
    i.prototype._ropeStep = function(e) {
        for (var t = e.physicsBody.get_m_nodes(), r = t.size(), n, o, a, s, l, u = new Array, c = 0; c < r; c++)
            n = t.at(c),
            o = n.get_m_x(),
            a = o.x(),
            s = o.y(),
            l = o.z(),
            u.push(new Vector3(a,s,l));
        var h = e.object
          , f = e.getParam("shape");
        e._isFromLine ? e.object = CreateLines("lines", {
            points: u,
            instance: h
        }) : e.object = ExtrudeShape("ext", {
            shape: f,
            path: u,
            instance: h
        })
    }
    ,
    i.prototype._softbodyOrClothStep = function(e) {
        var t = e.type === PhysicsImpostor.ClothImpostor ? 1 : -1
          , r = e.object
          , n = r.getVerticesData(VertexBuffer.PositionKind);
        n || (n = []);
        var o = r.getVerticesData(VertexBuffer.NormalKind);
        o || (o = []);
        for (var a = n.length / 3, s = e.physicsBody.get_m_nodes(), l, u, c, h, f, d, _, g, m, v = 0; v < a; v++) {
            l = s.at(v),
            u = l.get_m_x(),
            h = u.x(),
            f = u.y(),
            d = u.z() * t;
            var c = l.get_m_n();
            _ = c.x(),
            g = c.y(),
            m = c.z() * t,
            n[3 * v] = h,
            n[3 * v + 1] = f,
            n[3 * v + 2] = d,
            o[3 * v] = _,
            o[3 * v + 1] = g,
            o[3 * v + 2] = m
        }
        var y = new VertexData;
        y.positions = n,
        y.normals = o,
        y.uvs = r.getVerticesData(VertexBuffer.UVKind),
        y.colors = r.getVerticesData(VertexBuffer.ColorKind),
        r && r.getIndices && (y.indices = r.getIndices()),
        y.applyToMesh(r)
    }
    ,
    i.prototype.applyImpulse = function(e, t, r) {
        if (e.soft)
            Logger$2.Warn("Cannot be applied to a soft body");
        else {
            e.physicsBody.activate();
            var n = this._tmpAmmoVectorA
              , o = this._tmpAmmoVectorB;
            e.object && e.object.getWorldMatrix && r.subtractInPlace(e.object.getWorldMatrix().getTranslation()),
            n.setValue(r.x, r.y, r.z),
            o.setValue(t.x, t.y, t.z),
            e.physicsBody.applyImpulse(o, n)
        }
    }
    ,
    i.prototype.applyForce = function(e, t, r) {
        if (e.soft)
            Logger$2.Warn("Cannot be applied to a soft body");
        else {
            e.physicsBody.activate();
            var n = this._tmpAmmoVectorA
              , o = this._tmpAmmoVectorB;
            if (n.setValue(r.x, r.y, r.z),
            e.object && e.object.getWorldMatrix) {
                var a = e.object.getWorldMatrix().getTranslation();
                n.x -= a.x,
                n.y -= a.y,
                n.z -= a.z
            }
            o.setValue(t.x, t.y, t.z),
            e.physicsBody.applyForce(o, n)
        }
    }
    ,
    i.prototype.generatePhysicsBody = function(e) {
        if (e._pluginData.toDispose = [],
        e.parent) {
            e.physicsBody && (this.removePhysicsBody(e),
            e.forceUpdate());
            return
        }
        if (e.isBodyInitRequired()) {
            var t = this._createShape(e)
              , r = e.getParam("mass");
            if (e._pluginData.mass = r,
            e.soft)
                t.get_m_cfg().set_collisions(17),
                t.get_m_cfg().set_kDP(e.getParam("damping")),
                this.bjsAMMO.castObject(t, this.bjsAMMO.btCollisionObject).getCollisionShape().setMargin(e.getParam("margin")),
                t.setActivationState(i.DISABLE_DEACTIVATION_FLAG),
                this.world.addSoftBody(t, 1, -1),
                e.physicsBody = t,
                e._pluginData.toDispose.push(t),
                this.setBodyPressure(e, 0),
                e.type === PhysicsImpostor.SoftbodyImpostor && this.setBodyPressure(e, e.getParam("pressure")),
                this.setBodyStiffness(e, e.getParam("stiffness")),
                this.setBodyVelocityIterations(e, e.getParam("velocityIterations")),
                this.setBodyPositionIterations(e, e.getParam("positionIterations"));
            else {
                var n = new this.bjsAMMO.btVector3(0,0,0)
                  , o = new this.bjsAMMO.btTransform;
                e.object.computeWorldMatrix(!0),
                o.setIdentity(),
                r !== 0 && t.calculateLocalInertia(r, n),
                this._tmpAmmoVectorA.setValue(e.object.position.x, e.object.position.y, e.object.position.z),
                this._tmpAmmoQuaternion.setValue(e.object.rotationQuaternion.x, e.object.rotationQuaternion.y, e.object.rotationQuaternion.z, e.object.rotationQuaternion.w),
                o.setOrigin(this._tmpAmmoVectorA),
                o.setRotation(this._tmpAmmoQuaternion);
                var a = new this.bjsAMMO.btDefaultMotionState(o)
                  , s = new this.bjsAMMO.btRigidBodyConstructionInfo(r,a,t,n)
                  , l = new this.bjsAMMO.btRigidBody(s);
                if (r === 0 && (l.setCollisionFlags(l.getCollisionFlags() | i.KINEMATIC_FLAG),
                l.setActivationState(i.DISABLE_DEACTIVATION_FLAG)),
                e.type == PhysicsImpostor.NoImpostor && !t.getChildShape && l.setCollisionFlags(l.getCollisionFlags() | i.DISABLE_COLLISION_FLAG),
                e.type !== PhysicsImpostor.MeshImpostor && e.type !== PhysicsImpostor.NoImpostor) {
                    var u = e.object.getBoundingInfo();
                    this._tmpVec3.copyFrom(e.object.getAbsolutePosition()),
                    this._tmpVec3.subtractInPlace(u.boundingBox.centerWorld),
                    this._tmpVec3.x /= e.object.scaling.x,
                    this._tmpVec3.y /= e.object.scaling.y,
                    this._tmpVec3.z /= e.object.scaling.z,
                    e.setDeltaPosition(this._tmpVec3)
                }
                var c = e.getParam("group")
                  , h = e.getParam("mask");
                c && h ? this.world.addRigidBody(l, c, h) : this.world.addRigidBody(l),
                e.physicsBody = l,
                e._pluginData.toDispose = e._pluginData.toDispose.concat([l, s, a, o, n, t])
            }
            this.setBodyRestitution(e, e.getParam("restitution")),
            this.setBodyFriction(e, e.getParam("friction"))
        }
    }
    ,
    i.prototype.removePhysicsBody = function(e) {
        var t = this;
        this.world && (e.soft ? this.world.removeSoftBody(e.physicsBody) : this.world.removeRigidBody(e.physicsBody),
        e._pluginData && (e._pluginData.toDispose.forEach(function(r) {
            t.bjsAMMO.destroy(r)
        }),
        e._pluginData.toDispose = []))
    }
    ,
    i.prototype.generateJoint = function(e) {
        var t = e.mainImpostor.physicsBody
          , r = e.connectedImpostor.physicsBody;
        if (!(!t || !r)) {
            var n = e.joint.jointData;
            n.mainPivot || (n.mainPivot = new Vector3(0,0,0)),
            n.connectedPivot || (n.connectedPivot = new Vector3(0,0,0));
            var o;
            switch (e.joint.type) {
            case PhysicsJoint.DistanceJoint:
                var a = n.maxDistance;
                a && (n.mainPivot = new Vector3(0,-a / 2,0),
                n.connectedPivot = new Vector3(0,a / 2,0)),
                o = new this.bjsAMMO.btPoint2PointConstraint(t,r,new this.bjsAMMO.btVector3(n.mainPivot.x,n.mainPivot.y,n.mainPivot.z),new this.bjsAMMO.btVector3(n.connectedPivot.x,n.connectedPivot.y,n.connectedPivot.z));
                break;
            case PhysicsJoint.HingeJoint:
                n.mainAxis || (n.mainAxis = new Vector3(0,0,0)),
                n.connectedAxis || (n.connectedAxis = new Vector3(0,0,0));
                var s = new this.bjsAMMO.btVector3(n.mainAxis.x,n.mainAxis.y,n.mainAxis.z)
                  , l = new this.bjsAMMO.btVector3(n.connectedAxis.x,n.connectedAxis.y,n.connectedAxis.z);
                o = new this.bjsAMMO.btHingeConstraint(t,r,new this.bjsAMMO.btVector3(n.mainPivot.x,n.mainPivot.y,n.mainPivot.z),new this.bjsAMMO.btVector3(n.connectedPivot.x,n.connectedPivot.y,n.connectedPivot.z),s,l);
                break;
            case PhysicsJoint.BallAndSocketJoint:
                o = new this.bjsAMMO.btPoint2PointConstraint(t,r,new this.bjsAMMO.btVector3(n.mainPivot.x,n.mainPivot.y,n.mainPivot.z),new this.bjsAMMO.btVector3(n.connectedPivot.x,n.connectedPivot.y,n.connectedPivot.z));
                break;
            default:
                Logger$2.Warn("JointType not currently supported by the Ammo plugin, falling back to PhysicsJoint.BallAndSocketJoint"),
                o = new this.bjsAMMO.btPoint2PointConstraint(t,r,new this.bjsAMMO.btVector3(n.mainPivot.x,n.mainPivot.y,n.mainPivot.z),new this.bjsAMMO.btVector3(n.connectedPivot.x,n.connectedPivot.y,n.connectedPivot.z));
                break
            }
            this.world.addConstraint(o, !e.joint.jointData.collision),
            e.joint.physicsJoint = o
        }
    }
    ,
    i.prototype.removeJoint = function(e) {
        this.world && this.world.removeConstraint(e.joint.physicsJoint)
    }
    ,
    i.prototype._addMeshVerts = function(e, t, r) {
        var n = this
          , o = 0;
        if (r && r.getIndices && r.getWorldMatrix && r.getChildMeshes) {
            var a = r.getIndices();
            a || (a = []);
            var s = r.getVerticesData(VertexBuffer.PositionKind);
            s || (s = []);
            var l = void 0;
            if (t && t !== r) {
                var u = void 0;
                t.rotationQuaternion ? u = t.rotationQuaternion : t.rotation ? u = Quaternion.FromEulerAngles(t.rotation.x, t.rotation.y, t.rotation.z) : u = Quaternion.Identity();
                var c = Matrix.Compose(Vector3.One(), u, t.position);
                c.invertToRef(this._tmpMatrix);
                var h = r.computeWorldMatrix(!1);
                l = h.multiply(this._tmpMatrix)
            } else
                Matrix.ScalingToRef(r.scaling.x, r.scaling.y, r.scaling.z, this._tmpMatrix),
                l = this._tmpMatrix;
            for (var f = a.length / 3, d = 0; d < f; d++) {
                for (var _ = [], g = 0; g < 3; g++) {
                    var m = new Vector3(s[a[d * 3 + g] * 3 + 0],s[a[d * 3 + g] * 3 + 1],s[a[d * 3 + g] * 3 + 2]);
                    m = Vector3.TransformCoordinates(m, l);
                    var v;
                    g == 0 ? v = this._tmpAmmoVectorA : g == 1 ? v = this._tmpAmmoVectorB : v = this._tmpAmmoVectorC,
                    v.setValue(m.x, m.y, m.z),
                    _.push(v)
                }
                e.addTriangle(_[0], _[1], _[2]),
                o++
            }
            r.getChildMeshes().forEach(function(y) {
                o += n._addMeshVerts(e, t, y)
            })
        }
        return o
    }
    ,
    i.prototype._softVertexData = function(e) {
        var t = e.object;
        if (t && t.getIndices && t.getWorldMatrix && t.getChildMeshes) {
            t.getIndices();
            var r = t.getVerticesData(VertexBuffer.PositionKind);
            r || (r = []);
            var n = t.getVerticesData(VertexBuffer.NormalKind);
            n || (n = []),
            t.computeWorldMatrix(!1);
            for (var o = [], a = [], s = 0; s < r.length; s += 3) {
                var l = new Vector3(r[s],r[s + 1],r[s + 2])
                  , u = new Vector3(n[s],n[s + 1],n[s + 2]);
                l = Vector3.TransformCoordinates(l, t.getWorldMatrix()),
                u = Vector3.TransformNormal(u, t.getWorldMatrix()),
                o.push(l.x, l.y, l.z),
                a.push(u.x, u.y, u.z)
            }
            var c = new VertexData;
            return c.positions = o,
            c.normals = a,
            c.uvs = t.getVerticesData(VertexBuffer.UVKind),
            c.colors = t.getVerticesData(VertexBuffer.ColorKind),
            t && t.getIndices && (c.indices = t.getIndices()),
            c.applyToMesh(t),
            t.position = Vector3.Zero(),
            t.rotationQuaternion = null,
            t.rotation = Vector3.Zero(),
            t.computeWorldMatrix(!0),
            c
        }
        return VertexData.ExtractFromMesh(t)
    }
    ,
    i.prototype._createSoftbody = function(e) {
        var t = e.object;
        if (t && t.getIndices) {
            var r = t.getIndices();
            r || (r = []);
            var n = this._softVertexData(e)
              , o = n.positions
              , a = n.normals;
            if (o === null || a === null)
                return new this.bjsAMMO.btCompoundShape;
            for (var s = [], l = [], u = 0; u < o.length; u += 3) {
                var c = new Vector3(o[u],o[u + 1],o[u + 2])
                  , h = new Vector3(a[u],a[u + 1],a[u + 2]);
                s.push(c.x, c.y, -c.z),
                l.push(h.x, h.y, -h.z)
            }
            for (var f = new this.bjsAMMO.btSoftBodyHelpers().CreateFromTriMesh(this.world.getWorldInfo(), s, t.getIndices(), r.length / 3, !0), d = o.length / 3, _ = f.get_m_nodes(), g, m, u = 0; u < d; u++) {
                g = _.at(u);
                var m = g.get_m_n();
                m.setX(l[3 * u]),
                m.setY(l[3 * u + 1]),
                m.setZ(l[3 * u + 2])
            }
            return f
        }
    }
    ,
    i.prototype._createCloth = function(e) {
        var t = e.object;
        if (t && t.getIndices) {
            t.getIndices();
            var r = this._softVertexData(e)
              , n = r.positions
              , o = r.normals;
            if (n === null || o === null)
                return new this.bjsAMMO.btCompoundShape;
            var a = n.length
              , s = Math.sqrt(a / 3);
            e.segments = s;
            var l = s - 1;
            this._tmpAmmoVectorA.setValue(n[0], n[1], n[2]),
            this._tmpAmmoVectorB.setValue(n[3 * l], n[3 * l + 1], n[3 * l + 2]),
            this._tmpAmmoVectorD.setValue(n[a - 3], n[a - 2], n[a - 1]),
            this._tmpAmmoVectorC.setValue(n[a - 3 - 3 * l], n[a - 2 - 3 * l], n[a - 1 - 3 * l]);
            var u = new this.bjsAMMO.btSoftBodyHelpers().CreatePatch(this.world.getWorldInfo(), this._tmpAmmoVectorA, this._tmpAmmoVectorB, this._tmpAmmoVectorC, this._tmpAmmoVectorD, s, s, e.getParam("fixedPoints"), !0);
            return u
        }
    }
    ,
    i.prototype._createRope = function(e) {
        var t, r, n = this._softVertexData(e), o = n.positions, a = n.normals;
        if (o === null || a === null)
            return new this.bjsAMMO.btCompoundShape;
        n.applyToMesh(e.object, !0),
        e._isFromLine = !0;
        var s = a.map(function(_) {
            return _ * _
        })
          , l = function(_, g) {
            return _ + g
        }
          , u = s.reduce(l);
        if (u === 0)
            t = o.length,
            r = t / 3 - 1,
            this._tmpAmmoVectorA.setValue(o[0], o[1], o[2]),
            this._tmpAmmoVectorB.setValue(o[t - 3], o[t - 2], o[t - 1]);
        else {
            e._isFromLine = !1;
            var c = e.getParam("path")
              , h = e.getParam("shape");
            if (h === null)
                return Logger$2.Warn("No shape available for extruded mesh"),
                new this.bjsAMMO.btCompoundShape;
            t = c.length,
            r = t - 1,
            this._tmpAmmoVectorA.setValue(c[0].x, c[0].y, c[0].z),
            this._tmpAmmoVectorB.setValue(c[t - 1].x, c[t - 1].y, c[t - 1].z)
        }
        e.segments = r;
        var f = e.getParam("fixedPoints");
        f = f > 3 ? 3 : f;
        var d = new this.bjsAMMO.btSoftBodyHelpers().CreateRope(this.world.getWorldInfo(), this._tmpAmmoVectorA, this._tmpAmmoVectorB, r - 1, f);
        return d.get_m_cfg().set_collisions(17),
        d
    }
    ,
    i.prototype._createCustom = function(e) {
        var t = null;
        return this.onCreateCustomShape && (t = this.onCreateCustomShape(e)),
        t == null && (t = new this.bjsAMMO.btCompoundShape),
        t
    }
    ,
    i.prototype._addHullVerts = function(e, t, r) {
        var n = this
          , o = 0;
        if (r && r.getIndices && r.getWorldMatrix && r.getChildMeshes) {
            var a = r.getIndices();
            a || (a = []);
            var s = r.getVerticesData(VertexBuffer.PositionKind);
            s || (s = []),
            r.computeWorldMatrix(!1);
            for (var l = a.length / 3, u = 0; u < l; u++) {
                for (var c = [], h = 0; h < 3; h++) {
                    var f = new Vector3(s[a[u * 3 + h] * 3 + 0],s[a[u * 3 + h] * 3 + 1],s[a[u * 3 + h] * 3 + 2]);
                    Matrix.ScalingToRef(r.scaling.x, r.scaling.y, r.scaling.z, this._tmpMatrix),
                    f = Vector3.TransformCoordinates(f, this._tmpMatrix);
                    var d;
                    h == 0 ? d = this._tmpAmmoVectorA : h == 1 ? d = this._tmpAmmoVectorB : d = this._tmpAmmoVectorC,
                    d.setValue(f.x, f.y, f.z),
                    c.push(d)
                }
                e.addPoint(c[0], !0),
                e.addPoint(c[1], !0),
                e.addPoint(c[2], !0),
                o++
            }
            r.getChildMeshes().forEach(function(_) {
                o += n._addHullVerts(e, t, _)
            })
        }
        return o
    }
    ,
    i.prototype._createShape = function(e, t) {
        var r = this;
        t === void 0 && (t = !1);
        var n = e.object, o, a = e.getObjectExtendSize();
        if (!t) {
            var s = e.object.getChildMeshes ? e.object.getChildMeshes(!0) : [];
            o = new this.bjsAMMO.btCompoundShape;
            var l = 0;
            if (s.forEach(function(m) {
                var v = m.getPhysicsImpostor();
                if (v) {
                    if (v.type == PhysicsImpostor.MeshImpostor)
                        throw "A child MeshImpostor is not supported. Only primitive impostors are supported as children (eg. box or sphere)";
                    var y = r._createShape(v)
                      , b = m.parent.getWorldMatrix().clone()
                      , T = new Vector3;
                    b.decompose(T),
                    r._tmpAmmoTransform.getOrigin().setValue(m.position.x * T.x, m.position.y * T.y, m.position.z * T.z),
                    r._tmpAmmoQuaternion.setValue(m.rotationQuaternion.x, m.rotationQuaternion.y, m.rotationQuaternion.z, m.rotationQuaternion.w),
                    r._tmpAmmoTransform.setRotation(r._tmpAmmoQuaternion),
                    o.addChildShape(r._tmpAmmoTransform, y),
                    v.dispose(),
                    l++
                }
            }),
            l > 0) {
                if (e.type != PhysicsImpostor.NoImpostor) {
                    var u = this._createShape(e, !0);
                    u && (this._tmpAmmoTransform.getOrigin().setValue(0, 0, 0),
                    this._tmpAmmoQuaternion.setValue(0, 0, 0, 1),
                    this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion),
                    o.addChildShape(this._tmpAmmoTransform, u))
                }
                return o
            } else
                this.bjsAMMO.destroy(o),
                o = null
        }
        switch (e.type) {
        case PhysicsImpostor.SphereImpostor:
            if (Scalar.WithinEpsilon(a.x, a.y, 1e-4) && Scalar.WithinEpsilon(a.x, a.z, 1e-4))
                o = new this.bjsAMMO.btSphereShape(a.x / 2);
            else {
                var c = [new this.bjsAMMO.btVector3(0,0,0)]
                  , h = [1];
                o = new this.bjsAMMO.btMultiSphereShape(c,h,1),
                o.setLocalScaling(new this.bjsAMMO.btVector3(a.x / 2,a.y / 2,a.z / 2))
            }
            break;
        case PhysicsImpostor.CapsuleImpostor:
            var f = a.x / 2;
            o = new this.bjsAMMO.btCapsuleShape(f,a.y - f * 2);
            break;
        case PhysicsImpostor.CylinderImpostor:
            this._tmpAmmoVectorA.setValue(a.x / 2, a.y / 2, a.z / 2),
            o = new this.bjsAMMO.btCylinderShape(this._tmpAmmoVectorA);
            break;
        case PhysicsImpostor.PlaneImpostor:
        case PhysicsImpostor.BoxImpostor:
            this._tmpAmmoVectorA.setValue(a.x / 2, a.y / 2, a.z / 2),
            o = new this.bjsAMMO.btBoxShape(this._tmpAmmoVectorA);
            break;
        case PhysicsImpostor.MeshImpostor:
            if (e.getParam("mass") == 0) {
                var d = new this.bjsAMMO.btTriangleMesh;
                e._pluginData.toDispose.push(d);
                var g = this._addMeshVerts(d, n, n);
                g == 0 ? o = new this.bjsAMMO.btCompoundShape : o = new this.bjsAMMO.btBvhTriangleMeshShape(d);
                break
            }
        case PhysicsImpostor.ConvexHullImpostor:
            var _ = new this.bjsAMMO.btConvexHullShape
              , g = this._addHullVerts(_, n, n);
            g == 0 ? (e._pluginData.toDispose.push(_),
            o = new this.bjsAMMO.btCompoundShape) : o = _;
            break;
        case PhysicsImpostor.NoImpostor:
            o = new this.bjsAMMO.btSphereShape(a.x / 2);
            break;
        case PhysicsImpostor.CustomImpostor:
            o = this._createCustom(e);
            break;
        case PhysicsImpostor.SoftbodyImpostor:
            o = this._createSoftbody(e);
            break;
        case PhysicsImpostor.ClothImpostor:
            o = this._createCloth(e);
            break;
        case PhysicsImpostor.RopeImpostor:
            o = this._createRope(e);
            break;
        default:
            Logger$2.Warn("The impostor type is not currently supported by the ammo plugin.");
            break
        }
        return o
    }
    ,
    i.prototype.setTransformationFromPhysicsBody = function(e) {
        e.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform),
        e.object.position.set(this._tmpAmmoTransform.getOrigin().x(), this._tmpAmmoTransform.getOrigin().y(), this._tmpAmmoTransform.getOrigin().z()),
        e.object.rotationQuaternion ? e.object.rotationQuaternion.set(this._tmpAmmoTransform.getRotation().x(), this._tmpAmmoTransform.getRotation().y(), this._tmpAmmoTransform.getRotation().z(), this._tmpAmmoTransform.getRotation().w()) : e.object.rotation && (this._tmpQuaternion.set(this._tmpAmmoTransform.getRotation().x(), this._tmpAmmoTransform.getRotation().y(), this._tmpAmmoTransform.getRotation().z(), this._tmpAmmoTransform.getRotation().w()),
        this._tmpQuaternion.toEulerAnglesToRef(e.object.rotation))
    }
    ,
    i.prototype.setPhysicsBodyTransformation = function(e, t, r) {
        var n = e.physicsBody.getWorldTransform();
        if (Math.abs(n.getOrigin().x() - t.x) > Epsilon || Math.abs(n.getOrigin().y() - t.y) > Epsilon || Math.abs(n.getOrigin().z() - t.z) > Epsilon || Math.abs(n.getRotation().x() - r.x) > Epsilon || Math.abs(n.getRotation().y() - r.y) > Epsilon || Math.abs(n.getRotation().z() - r.z) > Epsilon || Math.abs(n.getRotation().w() - r.w) > Epsilon)
            if (this._tmpAmmoVectorA.setValue(t.x, t.y, t.z),
            n.setOrigin(this._tmpAmmoVectorA),
            this._tmpAmmoQuaternion.setValue(r.x, r.y, r.z, r.w),
            n.setRotation(this._tmpAmmoQuaternion),
            e.physicsBody.setWorldTransform(n),
            e.mass == 0) {
                var o = e.physicsBody.getMotionState();
                o && o.setWorldTransform(n)
            } else
                e.physicsBody.activate()
    }
    ,
    i.prototype.isSupported = function() {
        return this.bjsAMMO !== void 0
    }
    ,
    i.prototype.setLinearVelocity = function(e, t) {
        this._tmpAmmoVectorA.setValue(t.x, t.y, t.z),
        e.soft ? e.physicsBody.linearVelocity(this._tmpAmmoVectorA) : e.physicsBody.setLinearVelocity(this._tmpAmmoVectorA)
    }
    ,
    i.prototype.setAngularVelocity = function(e, t) {
        this._tmpAmmoVectorA.setValue(t.x, t.y, t.z),
        e.soft ? e.physicsBody.angularVelocity(this._tmpAmmoVectorA) : e.physicsBody.setAngularVelocity(this._tmpAmmoVectorA)
    }
    ,
    i.prototype.getLinearVelocity = function(e) {
        if (e.soft)
            var t = e.physicsBody.linearVelocity();
        else
            var t = e.physicsBody.getLinearVelocity();
        if (!t)
            return null;
        var r = new Vector3(t.x(),t.y(),t.z());
        return this.bjsAMMO.destroy(t),
        r
    }
    ,
    i.prototype.getAngularVelocity = function(e) {
        if (e.soft)
            var t = e.physicsBody.angularVelocity();
        else
            var t = e.physicsBody.getAngularVelocity();
        if (!t)
            return null;
        var r = new Vector3(t.x(),t.y(),t.z());
        return this.bjsAMMO.destroy(t),
        r
    }
    ,
    i.prototype.setBodyMass = function(e, t) {
        e.soft ? e.physicsBody.setTotalMass(t, !1) : e.physicsBody.setMassProps(t),
        e._pluginData.mass = t
    }
    ,
    i.prototype.getBodyMass = function(e) {
        return e._pluginData.mass || 0
    }
    ,
    i.prototype.getBodyFriction = function(e) {
        return e._pluginData.friction || 0
    }
    ,
    i.prototype.setBodyFriction = function(e, t) {
        e.soft ? e.physicsBody.get_m_cfg().set_kDF(t) : e.physicsBody.setFriction(t),
        e._pluginData.friction = t
    }
    ,
    i.prototype.getBodyRestitution = function(e) {
        return e._pluginData.restitution || 0
    }
    ,
    i.prototype.setBodyRestitution = function(e, t) {
        e.physicsBody.setRestitution(t),
        e._pluginData.restitution = t
    }
    ,
    i.prototype.getBodyPressure = function(e) {
        return e.soft ? e._pluginData.pressure || 0 : (Logger$2.Warn("Pressure is not a property of a rigid body"),
        0)
    }
    ,
    i.prototype.setBodyPressure = function(e, t) {
        e.soft ? e.type === PhysicsImpostor.SoftbodyImpostor ? (e.physicsBody.get_m_cfg().set_kPR(t),
        e._pluginData.pressure = t) : (e.physicsBody.get_m_cfg().set_kPR(0),
        e._pluginData.pressure = 0) : Logger$2.Warn("Pressure can only be applied to a softbody")
    }
    ,
    i.prototype.getBodyStiffness = function(e) {
        return e.soft ? e._pluginData.stiffness || 0 : (Logger$2.Warn("Stiffness is not a property of a rigid body"),
        0)
    }
    ,
    i.prototype.setBodyStiffness = function(e, t) {
        e.soft ? (t = t < 0 ? 0 : t,
        t = t > 1 ? 1 : t,
        e.physicsBody.get_m_materials().at(0).set_m_kLST(t),
        e._pluginData.stiffness = t) : Logger$2.Warn("Stiffness cannot be applied to a rigid body")
    }
    ,
    i.prototype.getBodyVelocityIterations = function(e) {
        return e.soft ? e._pluginData.velocityIterations || 0 : (Logger$2.Warn("Velocity iterations is not a property of a rigid body"),
        0)
    }
    ,
    i.prototype.setBodyVelocityIterations = function(e, t) {
        e.soft ? (t = t < 0 ? 0 : t,
        e.physicsBody.get_m_cfg().set_viterations(t),
        e._pluginData.velocityIterations = t) : Logger$2.Warn("Velocity iterations cannot be applied to a rigid body")
    }
    ,
    i.prototype.getBodyPositionIterations = function(e) {
        return e.soft ? e._pluginData.positionIterations || 0 : (Logger$2.Warn("Position iterations is not a property of a rigid body"),
        0)
    }
    ,
    i.prototype.setBodyPositionIterations = function(e, t) {
        e.soft ? (t = t < 0 ? 0 : t,
        e.physicsBody.get_m_cfg().set_piterations(t),
        e._pluginData.positionIterations = t) : Logger$2.Warn("Position iterations cannot be applied to a rigid body")
    }
    ,
    i.prototype.appendAnchor = function(e, t, r, n, o, a) {
        o === void 0 && (o = 1),
        a === void 0 && (a = !1);
        var s = e.segments
          , l = Math.round((s - 1) * r)
          , u = Math.round((s - 1) * n)
          , c = s - 1 - u
          , h = l + s * c;
        e.physicsBody.appendAnchor(h, t.physicsBody, a, o)
    }
    ,
    i.prototype.appendHook = function(e, t, r, n, o) {
        n === void 0 && (n = 1),
        o === void 0 && (o = !1);
        var a = Math.round(e.segments * r);
        e.physicsBody.appendAnchor(a, t.physicsBody, o, n)
    }
    ,
    i.prototype.sleepBody = function(e) {
        e.physicsBody.forceActivationState(0)
    }
    ,
    i.prototype.wakeUpBody = function(e) {
        e.physicsBody.activate()
    }
    ,
    i.prototype.updateDistanceJoint = function(e, t, r) {
        Logger$2.Warn("updateDistanceJoint is not currently supported by the Ammo physics plugin")
    }
    ,
    i.prototype.setMotor = function(e, t, r, n) {
        e.physicsJoint.enableAngularMotor(!0, t, r)
    }
    ,
    i.prototype.setLimit = function(e, t, r) {
        Logger$2.Warn("setLimit is not currently supported by the Ammo physics plugin")
    }
    ,
    i.prototype.syncMeshWithImpostor = function(e, t) {
        var r = t.physicsBody;
        r.getMotionState().getWorldTransform(this._tmpAmmoTransform),
        e.position.x = this._tmpAmmoTransform.getOrigin().x(),
        e.position.y = this._tmpAmmoTransform.getOrigin().y(),
        e.position.z = this._tmpAmmoTransform.getOrigin().z(),
        e.rotationQuaternion && (e.rotationQuaternion.x = this._tmpAmmoTransform.getRotation().x(),
        e.rotationQuaternion.y = this._tmpAmmoTransform.getRotation().y(),
        e.rotationQuaternion.z = this._tmpAmmoTransform.getRotation().z(),
        e.rotationQuaternion.w = this._tmpAmmoTransform.getRotation().w())
    }
    ,
    i.prototype.getRadius = function(e) {
        var t = e.getObjectExtendSize();
        return t.x / 2
    }
    ,
    i.prototype.getBoxSizeToRef = function(e, t) {
        var r = e.getObjectExtendSize();
        t.x = r.x,
        t.y = r.y,
        t.z = r.z
    }
    ,
    i.prototype.dispose = function() {
        this.bjsAMMO.destroy(this.world),
        this.bjsAMMO.destroy(this._solver),
        this.bjsAMMO.destroy(this._overlappingPairCache),
        this.bjsAMMO.destroy(this._dispatcher),
        this.bjsAMMO.destroy(this._collisionConfiguration),
        this.bjsAMMO.destroy(this._tmpAmmoVectorA),
        this.bjsAMMO.destroy(this._tmpAmmoVectorB),
        this.bjsAMMO.destroy(this._tmpAmmoVectorC),
        this.bjsAMMO.destroy(this._tmpAmmoTransform),
        this.bjsAMMO.destroy(this._tmpAmmoQuaternion),
        this.bjsAMMO.destroy(this._tmpAmmoConcreteContactResultCallback),
        this.world = null
    }
    ,
    i.prototype.raycast = function(e, t) {
        this._tmpAmmoVectorRCA = new this.bjsAMMO.btVector3(e.x,e.y,e.z),
        this._tmpAmmoVectorRCB = new this.bjsAMMO.btVector3(t.x,t.y,t.z);
        var r = new this.bjsAMMO.ClosestRayResultCallback(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB);
        return this.world.rayTest(this._tmpAmmoVectorRCA, this._tmpAmmoVectorRCB, r),
        this._raycastResult.reset(e, t),
        r.hasHit() && (this._raycastResult.setHitData({
            x: r.get_m_hitNormalWorld().x(),
            y: r.get_m_hitNormalWorld().y(),
            z: r.get_m_hitNormalWorld().z()
        }, {
            x: r.get_m_hitPointWorld().x(),
            y: r.get_m_hitPointWorld().y(),
            z: r.get_m_hitPointWorld().z()
        }),
        this._raycastResult.calculateHitDistance()),
        this.bjsAMMO.destroy(r),
        this.bjsAMMO.destroy(this._tmpAmmoVectorRCA),
        this.bjsAMMO.destroy(this._tmpAmmoVectorRCB),
        this._raycastResult
    }
    ,
    i.DISABLE_COLLISION_FLAG = 4,
    i.KINEMATIC_FLAG = 2,
    i.DISABLE_DEACTIVATION_FLAG = 4,
    i
}();
AbstractScene.prototype.removeReflectionProbe = function(i) {
    if (!this.reflectionProbes)
        return -1;
    var e = this.reflectionProbes.indexOf(i);
    return e !== -1 && this.reflectionProbes.splice(e, 1),
    e
}
;
AbstractScene.prototype.addReflectionProbe = function(i) {
    this.reflectionProbes || (this.reflectionProbes = []),
    this.reflectionProbes.push(i)
}
;
var ReflectionProbe = function() {
    function i(e, t, r, n, o, a) {
        var s = this;
        if (n === void 0 && (n = !0),
        o === void 0 && (o = !1),
        a === void 0 && (a = !1),
        this.name = e,
        this._viewMatrix = Matrix.Identity(),
        this._target = Vector3.Zero(),
        this._add = Vector3.Zero(),
        this._invertYAxis = !1,
        this.position = Vector3.Zero(),
        this._parentContainer = null,
        this._scene = r,
        r.getEngine().supportsUniformBuffers) {
            this._sceneUBOs = [];
            for (var l = 0; l < 6; ++l)
                this._sceneUBOs.push(r.createSceneUniformBuffer('Scene for Reflection Probe (name "' + e + '") face #' + l))
        }
        this._scene.reflectionProbes || (this._scene.reflectionProbes = new Array),
        this._scene.reflectionProbes.push(this);
        var u = 0;
        if (o) {
            var c = this._scene.getEngine().getCaps();
            c.textureHalfFloatRender ? u = 2 : c.textureFloatRender && (u = 1)
        }
        this._renderTargetTexture = new RenderTargetTexture(e,t,r,n,!0,u,!0),
        this._renderTargetTexture.gammaSpace = !a;
        var h = r.getEngine().useReverseDepthBuffer;
        this._renderTargetTexture.onBeforeRenderObservable.add(function(d) {
            switch (s._sceneUBOs && (r.setSceneUniformBuffer(s._sceneUBOs[d]),
            r.getSceneUniformBuffer().unbindEffect()),
            d) {
            case 0:
                s._add.copyFromFloats(1, 0, 0);
                break;
            case 1:
                s._add.copyFromFloats(-1, 0, 0);
                break;
            case 2:
                s._add.copyFromFloats(0, s._invertYAxis ? 1 : -1, 0);
                break;
            case 3:
                s._add.copyFromFloats(0, s._invertYAxis ? -1 : 1, 0);
                break;
            case 4:
                s._add.copyFromFloats(0, 0, r.useRightHandedSystem ? -1 : 1);
                break;
            case 5:
                s._add.copyFromFloats(0, 0, r.useRightHandedSystem ? 1 : -1);
                break
            }
            s._attachedMesh && s.position.copyFrom(s._attachedMesh.getAbsolutePosition()),
            s.position.addToRef(s._add, s._target);
            var _ = r.useRightHandedSystem ? Matrix.LookAtRHToRef : Matrix.LookAtLHToRef
              , g = r.useRightHandedSystem ? Matrix.PerspectiveFovRH : Matrix.PerspectiveFovLH;
            _(s.position, s._target, Vector3.Up(), s._viewMatrix),
            r.activeCamera && (s._projectionMatrix = g(Math.PI / 2, 1, h ? r.activeCamera.maxZ : r.activeCamera.minZ, h ? r.activeCamera.minZ : r.activeCamera.maxZ, s._scene.getEngine().isNDCHalfZRange),
            r.setTransformMatrix(s._viewMatrix, s._projectionMatrix),
            r.activeCamera.isRigCamera && !s._renderTargetTexture.activeCamera && (s._renderTargetTexture.activeCamera = r.activeCamera.rigParent || null)),
            r._forcedViewPosition = s.position
        });
        var f;
        this._renderTargetTexture.onBeforeBindObservable.add(function() {
            var d, _;
            s._currentSceneUBO = r.getSceneUniformBuffer(),
            (_ = (d = r.getEngine())._debugPushGroup) === null || _ === void 0 || _.call(d, "reflection probe generation for " + e, 1),
            f = s._scene.imageProcessingConfiguration.applyByPostProcess,
            a && (r.imageProcessingConfiguration.applyByPostProcess = !0)
        }),
        this._renderTargetTexture.onAfterUnbindObservable.add(function() {
            var d, _;
            r.imageProcessingConfiguration.applyByPostProcess = f,
            r._forcedViewPosition = null,
            s._sceneUBOs && r.setSceneUniformBuffer(s._currentSceneUBO),
            r.updateTransformMatrix(!0),
            (_ = (d = r.getEngine())._debugPopGroup) === null || _ === void 0 || _.call(d, 1)
        })
    }
    return Object.defineProperty(i.prototype, "samples", {
        get: function() {
            return this._renderTargetTexture.samples
        },
        set: function(e) {
            this._renderTargetTexture.samples = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "refreshRate", {
        get: function() {
            return this._renderTargetTexture.refreshRate
        },
        set: function(e) {
            this._renderTargetTexture.refreshRate = e
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.getScene = function() {
        return this._scene
    }
    ,
    Object.defineProperty(i.prototype, "cubeTexture", {
        get: function() {
            return this._renderTargetTexture
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "renderList", {
        get: function() {
            return this._renderTargetTexture.renderList
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.attachToMesh = function(e) {
        this._attachedMesh = e
    }
    ,
    i.prototype.setRenderingAutoClearDepthStencil = function(e, t) {
        this._renderTargetTexture.setRenderingAutoClearDepthStencil(e, t)
    }
    ,
    i.prototype.dispose = function() {
        var e = this._scene.reflectionProbes.indexOf(this);
        if (e !== -1 && this._scene.reflectionProbes.splice(e, 1),
        this._parentContainer) {
            var t = this._parentContainer.reflectionProbes.indexOf(this);
            t > -1 && this._parentContainer.reflectionProbes.splice(t, 1),
            this._parentContainer = null
        }
        if (this._renderTargetTexture && (this._renderTargetTexture.dispose(),
        this._renderTargetTexture = null),
        this._sceneUBOs) {
            for (var r = 0, n = this._sceneUBOs; r < n.length; r++) {
                var o = n[r];
                o.dispose()
            }
            this._sceneUBOs = []
        }
    }
    ,
    i.prototype.toString = function(e) {
        var t = "Name: " + this.name;
        return e && (t += ", position: " + this.position.toString(),
        this._attachedMesh && (t += ", attached mesh: " + this._attachedMesh.name)),
        t
    }
    ,
    i.prototype.getClassName = function() {
        return "ReflectionProbe"
    }
    ,
    i.prototype.serialize = function() {
        var e = SerializationHelper.Serialize(this, this._renderTargetTexture.serialize());
        return e.isReflectionProbe = !0,
        e
    }
    ,
    i.Parse = function(e, t, r) {
        var n = null;
        if (t.reflectionProbes)
            for (var o = 0; o < t.reflectionProbes.length; o++) {
                var a = t.reflectionProbes[o];
                if (a.name === e.name) {
                    n = a;
                    break
                }
            }
        return n = SerializationHelper.Parse(function() {
            return n || new i(e.name,e.renderTargetSize,t,e._generateMipMaps)
        }, e, t, r),
        n.cubeTexture._waitingRenderList = e.renderList,
        e._attachedMesh && n.attachToMesh(t.getMeshById(e._attachedMesh)),
        n
    }
    ,
    __decorate([serializeAsMeshReference()], i.prototype, "_attachedMesh", void 0),
    __decorate([serializeAsVector3()], i.prototype, "position", void 0),
    i
}()
  , BabylonFileLoaderConfiguration = function() {
    function i() {}
    return i.LoaderInjectedPhysicsEngine = void 0,
    i
}()
  , tempIndexContainer = {}
  , parseMaterialById = function(i, e, t, r) {
    if (!e.materials)
        return null;
    for (var n = 0, o = e.materials.length; n < o; n++) {
        var a = e.materials[n];
        if (a.id === i)
            return Material.Parse(a, t, r)
    }
    return null
}
  , isDescendantOf = function(i, e, t) {
    for (var r in e)
        if (i.name === e[r])
            return t.push(i.id),
            !0;
    return i.parentId && t.indexOf(i.parentId) !== -1 ? (t.push(i.id),
    !0) : !1
}
  , logOperation = function(i, e) {
    return i + " of " + (e ? e.file + " from " + e.name + " version: " + e.version + ", exporter version: " + e.exporter_version : "unknown")
}
  , loadDetailLevels = function(i, e) {
    var t = e;
    if (e._waitingData.lods) {
        if (e._waitingData.lods.ids && e._waitingData.lods.ids.length > 0) {
            var r = e._waitingData.lods.ids
              , n = t.isEnabled(!1);
            if (e._waitingData.lods.distances) {
                var o = e._waitingData.lods.distances;
                if (o.length >= r.length) {
                    var a = o.length > r.length ? o[o.length - 1] : 0;
                    t.setEnabled(!1);
                    for (var s = 0; s < r.length; s++) {
                        var l = r[s]
                          , u = i.getMeshById(l);
                        u != null && t.addLODLevel(o[s], u)
                    }
                    a > 0 && t.addLODLevel(a, null),
                    n === !0 && t.setEnabled(!0)
                } else
                    Tools.Warn("Invalid level of detail distances for " + e.name)
            }
        }
        e._waitingData.lods = null
    }
}
  , findParent = function(i, e) {
    if (typeof i != "number")
        return e.getLastEntryById(i);
    var t = tempIndexContainer[i];
    return t
}
  , loadAssetContainer = function(i, e, t, r, n) {
    n === void 0 && (n = !1);
    var o = new AssetContainer(i)
      , a = "importScene has failed JSON parse";
    try {
        var s = JSON.parse(e);
        a = "";
        var l = SceneLoader.loggingLevel === SceneLoader.DETAILED_LOGGING, u, c;
        if (s.environmentTexture !== void 0 && s.environmentTexture !== null) {
            var h = s.isPBR !== void 0 ? s.isPBR : !0;
            if (s.environmentTextureType && s.environmentTextureType === "BABYLON.HDRCubeTexture") {
                var f = s.environmentTextureSize ? s.environmentTextureSize : 128
                  , d = new HDRCubeTexture((s.environmentTexture.match(/https?:\/\//g) ? "" : t) + s.environmentTexture,i,f,!0,!h);
                s.environmentTextureRotationY && (d.rotationY = s.environmentTextureRotationY),
                i.environmentTexture = d
            } else if (EndsWith(s.environmentTexture, ".env")) {
                var _ = new CubeTexture((s.environmentTexture.match(/https?:\/\//g) ? "" : t) + s.environmentTexture,i);
                s.environmentTextureRotationY && (_.rotationY = s.environmentTextureRotationY),
                i.environmentTexture = _
            } else {
                var g = CubeTexture.CreateFromPrefilteredData((s.environmentTexture.match(/https?:\/\//g) ? "" : t) + s.environmentTexture, i);
                s.environmentTextureRotationY && (g.rotationY = s.environmentTextureRotationY),
                i.environmentTexture = g
            }
            if (s.createDefaultSkybox === !0) {
                var m = i.activeCamera !== void 0 && i.activeCamera !== null ? (i.activeCamera.maxZ - i.activeCamera.minZ) / 2 : 1e3
                  , v = s.skyboxBlurLevel || 0;
                i.createDefaultSkybox(i.environmentTexture, h, m, v)
            }
            o.environmentTexture = i.environmentTexture
        }
        if (s.environmentIntensity !== void 0 && s.environmentIntensity !== null && (i.environmentIntensity = s.environmentIntensity),
        s.lights !== void 0 && s.lights !== null)
            for (u = 0,
            c = s.lights.length; u < c; u++) {
                var y = s.lights[u]
                  , b = Light.Parse(y, i);
                b && (tempIndexContainer[y.uniqueId] = b,
                o.lights.push(b),
                b._parentContainer = o,
                a += u === 0 ? `
	Lights:` : "",
                a += `
		` + b.toString(l))
            }
        if (s.reflectionProbes !== void 0 && s.reflectionProbes !== null)
            for (u = 0,
            c = s.reflectionProbes.length; u < c; u++) {
                var T = s.reflectionProbes[u]
                  , C = ReflectionProbe.Parse(T, i, t);
                C && (o.reflectionProbes.push(C),
                C._parentContainer = o,
                a += u === 0 ? `
	Reflection Probes:` : "",
                a += `
		` + C.toString(l))
            }
        if (s.animations !== void 0 && s.animations !== null)
            for (u = 0,
            c = s.animations.length; u < c; u++) {
                var A = s.animations[u]
                  , S = GetClass("BABYLON.Animation");
                if (S) {
                    var P = S.Parse(A);
                    i.animations.push(P),
                    o.animations.push(P),
                    a += u === 0 ? `
	Animations:` : "",
                    a += `
		` + P.toString(l)
                }
            }
        if (s.materials !== void 0 && s.materials !== null)
            for (u = 0,
            c = s.materials.length; u < c; u++) {
                var R = s.materials[u]
                  , M = Material.Parse(R, i, t);
                if (M) {
                    o.materials.push(M),
                    M._parentContainer = o,
                    a += u === 0 ? `
	Materials:` : "",
                    a += `
		` + M.toString(l);
                    var x = M.getActiveTextures();
                    x.forEach(function(ae) {
                        o.textures.indexOf(ae) == -1 && (o.textures.push(ae),
                        ae._parentContainer = o)
                    })
                }
            }
        if (s.multiMaterials !== void 0 && s.multiMaterials !== null)
            for (u = 0,
            c = s.multiMaterials.length; u < c; u++) {
                var I = s.multiMaterials[u]
                  , w = MultiMaterial.ParseMultiMaterial(I, i);
                o.multiMaterials.push(w),
                w._parentContainer = o,
                a += u === 0 ? `
	MultiMaterials:` : "",
                a += `
		` + w.toString(l);
                var x = w.getActiveTextures();
                x.forEach(function(se) {
                    o.textures.indexOf(se) == -1 && (o.textures.push(se),
                    se._parentContainer = o)
                })
            }
        if (s.morphTargetManagers !== void 0 && s.morphTargetManagers !== null)
            for (var O = 0, D = s.morphTargetManagers; O < D.length; O++) {
                var F = D[O]
                  , V = MorphTargetManager.Parse(F, i);
                o.morphTargetManagers.push(V),
                V._parentContainer = o
            }
        if (s.skeletons !== void 0 && s.skeletons !== null)
            for (u = 0,
            c = s.skeletons.length; u < c; u++) {
                var N = s.skeletons[u]
                  , L = Skeleton.Parse(N, i);
                o.skeletons.push(L),
                L._parentContainer = o,
                a += u === 0 ? `
	Skeletons:` : "",
                a += `
		` + L.toString(l)
            }
        var k = s.geometries;
        if (k != null) {
            var U = new Array
              , z = k.vertexData;
            if (z != null)
                for (u = 0,
                c = z.length; u < c; u++) {
                    var H = z[u];
                    U.push(Geometry.Parse(H, i, t))
                }
            U.forEach(function(ae) {
                ae && (o.geometries.push(ae),
                ae._parentContainer = o)
            })
        }
        if (s.transformNodes !== void 0 && s.transformNodes !== null)
            for (u = 0,
            c = s.transformNodes.length; u < c; u++) {
                var G = s.transformNodes[u]
                  , W = TransformNode.Parse(G, i, t);
                tempIndexContainer[G.uniqueId] = W,
                o.transformNodes.push(W),
                W._parentContainer = o
            }
        if (s.meshes !== void 0 && s.meshes !== null)
            for (u = 0,
            c = s.meshes.length; u < c; u++) {
                var j = s.meshes[u]
                  , B = Mesh.Parse(j, i, t);
                if (tempIndexContainer[j.uniqueId] = B,
                o.meshes.push(B),
                B._parentContainer = o,
                B.hasInstances)
                    for (var X = 0, $ = B.instances; X < $.length; X++) {
                        var Y = $[X];
                        o.meshes.push(Y),
                        Y._parentContainer = o
                    }
                a += u === 0 ? `
	Meshes:` : "",
                a += `
		` + B.toString(l)
            }
        if (s.cameras !== void 0 && s.cameras !== null)
            for (u = 0,
            c = s.cameras.length; u < c; u++) {
                var K = s.cameras[u]
                  , Z = Camera$1.Parse(K, i);
                tempIndexContainer[K.uniqueId] = Z,
                o.cameras.push(Z),
                Z._parentContainer = o,
                a += u === 0 ? `
	Cameras:` : "",
                a += `
		` + Z.toString(l)
            }
        if (s.postProcesses !== void 0 && s.postProcesses !== null)
            for (u = 0,
            c = s.postProcesses.length; u < c; u++) {
                var q = s.postProcesses[u]
                  , J = PostProcess.Parse(q, i, t);
                J && (o.postProcesses.push(J),
                J._parentContainer = o,
                a += u === 0 ? `
Postprocesses:` : "",
                a += `
		` + J.toString())
            }
        if (s.animationGroups !== void 0 && s.animationGroups !== null)
            for (u = 0,
            c = s.animationGroups.length; u < c; u++) {
                var Q = s.animationGroups[u]
                  , te = AnimationGroup.Parse(Q, i);
                o.animationGroups.push(te),
                te._parentContainer = o,
                a += u === 0 ? `
	AnimationGroups:` : "",
                a += `
		` + te.toString(l)
            }
        for (u = 0,
        c = i.cameras.length; u < c; u++) {
            var Z = i.cameras[u];
            Z._waitingParentId && (Z.parent = findParent(Z._waitingParentId, i),
            Z._waitingParentId = null)
        }
        for (u = 0,
        c = i.lights.length; u < c; u++) {
            var re = i.lights[u];
            re && re._waitingParentId && (re.parent = findParent(re._waitingParentId, i),
            re._waitingParentId = null)
        }
        for (u = 0,
        c = i.transformNodes.length; u < c; u++) {
            var ie = i.transformNodes[u];
            ie._waitingParentId && (ie.parent = findParent(ie._waitingParentId, i),
            ie._waitingParentId = null)
        }
        for (u = 0,
        c = i.meshes.length; u < c; u++) {
            var B = i.meshes[u];
            B._waitingParentId && (B.parent = findParent(B._waitingParentId, i),
            B._waitingParentId = null),
            B._waitingData.lods && loadDetailLevels(i, B)
        }
        for (u = 0,
        c = i.skeletons.length; u < c; u++) {
            var L = i.skeletons[u];
            L._hasWaitingData && (L.bones != null && L.bones.forEach(function(se) {
                if (se._waitingTransformNodeId) {
                    var Re = i.getLastEntryById(se._waitingTransformNodeId);
                    Re && se.linkTransformNode(Re),
                    se._waitingTransformNodeId = null
                }
            }),
            L._waitingOverrideMeshId && (L.overrideMesh = i.getMeshById(L._waitingOverrideMeshId),
            L._waitingOverrideMeshId = null),
            L._hasWaitingData = null)
        }
        for (u = 0,
        c = i.meshes.length; u < c; u++) {
            var ee = i.meshes[u];
            ee._waitingData.freezeWorldMatrix ? (ee.freezeWorldMatrix(),
            ee._waitingData.freezeWorldMatrix = null) : ee.computeWorldMatrix(!0)
        }
        for (u = 0,
        c = i.lights.length; u < c; u++) {
            var ne = i.lights[u];
            if (ne._excludedMeshesIds.length > 0) {
                for (var ce = 0; ce < ne._excludedMeshesIds.length; ce++) {
                    var he = i.getMeshById(ne._excludedMeshesIds[ce]);
                    he && ne.excludedMeshes.push(he)
                }
                ne._excludedMeshesIds = []
            }
            if (ne._includedOnlyMeshesIds.length > 0) {
                for (var fe = 0; fe < ne._includedOnlyMeshesIds.length; fe++) {
                    var ue = i.getMeshById(ne._includedOnlyMeshesIds[fe]);
                    ue && ne.includedOnlyMeshes.push(ue)
                }
                ne._includedOnlyMeshesIds = []
            }
        }
        for (AbstractScene.Parse(s, i, o, t),
        u = 0,
        c = i.meshes.length; u < c; u++) {
            var B = i.meshes[u];
            B._waitingData.actions && (ActionManager.Parse(B._waitingData.actions, B, i),
            B._waitingData.actions = null)
        }
        s.actions !== void 0 && s.actions !== null && ActionManager.Parse(s.actions, null, i)
    } catch (ae) {
        var _e = logOperation("loadAssets", s ? s.producer : "Unknown") + a;
        if (r)
            r(_e, ae);
        else
            throw Logger$2.Log(_e),
            ae
    } finally {
        tempIndexContainer = {},
        n || o.removeAllFromScene(),
        a !== null && SceneLoader.loggingLevel !== SceneLoader.NO_LOGGING && Logger$2.Log(logOperation("loadAssets", s ? s.producer : "Unknown") + (SceneLoader.loggingLevel !== SceneLoader.MINIMAL_LOGGING ? a : ""))
    }
    return o
};
SceneLoader.RegisterPlugin({
    name: "babylon.js",
    extensions: ".babylon",
    canDirectLoad: function(i) {
        return i.indexOf("babylon") !== -1
    },
    importMesh: function(i, e, t, r, n, o, a, s) {
        var l = "importMesh has failed JSON parse";
        try {
            var u = JSON.parse(t);
            l = "";
            var c = SceneLoader.loggingLevel === SceneLoader.DETAILED_LOGGING;
            i ? Array.isArray(i) || (i = [i]) : i = null;
            var h = new Array;
            if (u.meshes !== void 0 && u.meshes !== null) {
                var f = [], d = [], _, g;
                for (_ = 0,
                g = u.meshes.length; _ < g; _++) {
                    var m = u.meshes[_];
                    if (i === null || isDescendantOf(m, i, h)) {
                        if (i !== null && delete i[i.indexOf(m.name)],
                        m.geometryId !== void 0 && m.geometryId !== null && u.geometries !== void 0 && u.geometries !== null) {
                            var v = !1;
                            ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function(G) {
                                v === !0 || !u.geometries[G] || !Array.isArray(u.geometries[G]) || u.geometries[G].forEach(function(W) {
                                    if (W.id === m.geometryId) {
                                        switch (G) {
                                        case "vertexData":
                                            Geometry.Parse(W, e, r);
                                            break
                                        }
                                        v = !0
                                    }
                                })
                            }),
                            v === !1 && Logger$2.Warn("Geometry not found for mesh " + m.id)
                        }
                        if (m.materialId) {
                            var y = d.indexOf(m.materialId) !== -1;
                            if (y === !1 && u.multiMaterials !== void 0 && u.multiMaterials !== null)
                                for (var b = 0, T = u.multiMaterials.length; b < T; b++) {
                                    var C = u.multiMaterials[b];
                                    if (C.id === m.materialId) {
                                        for (var A = 0, S = C.materials.length; A < S; A++) {
                                            var P = C.materials[A];
                                            d.push(P);
                                            var R = parseMaterialById(P, u, e, r);
                                            R && (l += `
	Material ` + R.toString(c))
                                        }
                                        d.push(C.id);
                                        var M = MultiMaterial.ParseMultiMaterial(C, e);
                                        M && (y = !0,
                                        l += `
	Multi-Material ` + M.toString(c));
                                        break
                                    }
                                }
                            if (y === !1) {
                                d.push(m.materialId);
                                var R = parseMaterialById(m.materialId, u, e, r);
                                R ? l += `
	Material ` + R.toString(c) : Logger$2.Warn("Material not found for mesh " + m.id)
                            }
                        }
                        if (m.skeletonId > -1 && u.skeletons !== void 0 && u.skeletons !== null) {
                            var x = f.indexOf(m.skeletonId) > -1;
                            if (x === !1)
                                for (var I = 0, w = u.skeletons.length; I < w; I++) {
                                    var O = u.skeletons[I];
                                    if (O.id === m.skeletonId) {
                                        var D = Skeleton.Parse(O, e);
                                        a.push(D),
                                        f.push(O.id),
                                        l += `
	Skeleton ` + D.toString(c)
                                    }
                                }
                        }
                        if (u.morphTargetManagers !== void 0 && u.morphTargetManagers !== null)
                            for (var F = 0, V = u.morphTargetManagers; F < V.length; F++) {
                                var N = V[F];
                                MorphTargetManager.Parse(N, e)
                            }
                        var L = Mesh.Parse(m, e, r);
                        n.push(L),
                        l += `
	Mesh ` + L.toString(c)
                    }
                }
                var k;
                for (_ = 0,
                g = e.meshes.length; _ < g; _++)
                    k = e.meshes[_],
                    k._waitingParentId && (k.parent = e.getLastEntryById(k._waitingParentId),
                    k._waitingParentId = null),
                    k._waitingData.lods && loadDetailLevels(e, k);
                for (_ = 0,
                g = e.skeletons.length; _ < g; _++) {
                    var D = e.skeletons[_];
                    D._hasWaitingData && (D.bones != null && D.bones.forEach(function(W) {
                        if (W._waitingTransformNodeId) {
                            var j = e.getLastEntryById(W._waitingTransformNodeId);
                            j && W.linkTransformNode(j),
                            W._waitingTransformNodeId = null
                        }
                    }),
                    D._waitingOverrideMeshId && (D.overrideMesh = e.getMeshById(D._waitingOverrideMeshId),
                    D._waitingOverrideMeshId = null),
                    D._hasWaitingData = null)
                }
                for (_ = 0,
                g = e.meshes.length; _ < g; _++)
                    k = e.meshes[_],
                    k._waitingData.freezeWorldMatrix ? (k.freezeWorldMatrix(),
                    k._waitingData.freezeWorldMatrix = null) : k.computeWorldMatrix(!0)
            }
            if (u.particleSystems !== void 0 && u.particleSystems !== null) {
                var U = AbstractScene.GetIndividualParser(SceneComponentConstants.NAME_PARTICLESYSTEM);
                if (U)
                    for (_ = 0,
                    g = u.particleSystems.length; _ < g; _++) {
                        var z = u.particleSystems[_];
                        h.indexOf(z.emitterId) !== -1 && o.push(U(z, e, r))
                    }
            }
            return !0
        } catch (G) {
            var H = logOperation("importMesh", u ? u.producer : "Unknown") + l;
            if (s)
                s(H, G);
            else
                throw Logger$2.Log(H),
                G
        } finally {
            l !== null && SceneLoader.loggingLevel !== SceneLoader.NO_LOGGING && Logger$2.Log(logOperation("importMesh", u ? u.producer : "Unknown") + (SceneLoader.loggingLevel !== SceneLoader.MINIMAL_LOGGING ? l : ""))
        }
        return !1
    },
    load: function(i, e, t, r) {
        var n = "importScene has failed JSON parse";
        try {
            var o = JSON.parse(e);
            if (n = "",
            o.useDelayedTextureLoading !== void 0 && o.useDelayedTextureLoading !== null && (i.useDelayedTextureLoading = o.useDelayedTextureLoading && !SceneLoader.ForceFullSceneLoadingForIncremental),
            o.autoClear !== void 0 && o.autoClear !== null && (i.autoClear = o.autoClear),
            o.clearColor !== void 0 && o.clearColor !== null && (i.clearColor = Color4.FromArray(o.clearColor)),
            o.ambientColor !== void 0 && o.ambientColor !== null && (i.ambientColor = Color3.FromArray(o.ambientColor)),
            o.gravity !== void 0 && o.gravity !== null && (i.gravity = Vector3.FromArray(o.gravity)),
            o.fogMode && o.fogMode !== 0)
                switch (i.fogMode = o.fogMode,
                i.fogColor = Color3.FromArray(o.fogColor),
                i.fogStart = o.fogStart,
                i.fogEnd = o.fogEnd,
                i.fogDensity = o.fogDensity,
                n += "	Fog mode for scene:  ",
                i.fogMode) {
                case 1:
                    n += `exp
`;
                    break;
                case 2:
                    n += `exp2
`;
                    break;
                case 3:
                    n += `linear
`;
                    break
                }
            if (o.physicsEnabled) {
                var a;
                o.physicsEngine === "cannon" ? a = new CannonJSPlugin(void 0,void 0,BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine) : o.physicsEngine === "oimo" ? a = new OimoJSPlugin(void 0,BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine) : o.physicsEngine === "ammo" && (a = new AmmoJSPlugin(void 0,BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine,void 0)),
                n = "	Physics engine " + (o.physicsEngine ? o.physicsEngine : "oimo") + ` enabled
`;
                var s = o.physicsGravity ? Vector3.FromArray(o.physicsGravity) : null;
                i.enablePhysics(s, a)
            }
            o.metadata !== void 0 && o.metadata !== null && (i.metadata = o.metadata),
            o.collisionsEnabled !== void 0 && o.collisionsEnabled !== null && (i.collisionsEnabled = o.collisionsEnabled);
            var l = loadAssetContainer(i, e, t, r, !0);
            return l ? (o.autoAnimate && i.beginAnimation(i, o.autoAnimateFrom, o.autoAnimateTo, o.autoAnimateLoop, o.autoAnimateSpeed || 1),
            o.activeCameraID !== void 0 && o.activeCameraID !== null && i.setActiveCameraById(o.activeCameraID),
            !0) : !1
        } catch (c) {
            var u = logOperation("importScene", o ? o.producer : "Unknown") + n;
            if (r)
                r(u, c);
            else
                throw Logger$2.Log(u),
                c
        } finally {
            n !== null && SceneLoader.loggingLevel !== SceneLoader.NO_LOGGING && Logger$2.Log(logOperation("importScene", o ? o.producer : "Unknown") + (SceneLoader.loggingLevel !== SceneLoader.MINIMAL_LOGGING ? n : ""))
        }
        return !1
    },
    loadAssetContainer: function(i, e, t, r) {
        var n = loadAssetContainer(i, e, t, r);
        return n
    }
});
var name$r = "depthPixelShader"
  , shader$r = `#ifdef ALPHATEST
varying vec2 vUV;
uniform sampler2D diffuseSampler;
#endif
varying float vDepthMetric;
#ifdef PACKED
#include<packingFunctions>
#endif
void main(void)
{
#ifdef ALPHATEST
if (texture2D(diffuseSampler,vUV).a<0.4)
discard;
#endif
#ifdef NONLINEARDEPTH
#ifdef PACKED
gl_FragColor=pack(gl_FragCoord.z);
#else
gl_FragColor=vec4(gl_FragCoord.z,0.0,0.0,0.0);
#endif
#else
#ifdef PACKED
gl_FragColor=pack(vDepthMetric);
#else
gl_FragColor=vec4(vDepthMetric,0.0,0.0,1.0);
#endif
#endif
}`;
ShaderStore.ShadersStore[name$r] = shader$r;
var name$q = "depthVertexShader"
  , shader$q = `
attribute vec3 position;
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]

#include<instancesDeclaration>
uniform mat4 viewProjection;
uniform vec2 depthValues;
#if defined(ALPHATEST) || defined(NEED_UV)
varying vec2 vUV;
uniform mat4 diffuseMatrix;
#ifdef UV1
attribute vec2 uv;
#endif
#ifdef UV2
attribute vec2 uv2;
#endif
#endif
varying float vDepthMetric;
void main(void)
{
vec3 positionUpdated=position;
#ifdef UV1
vec2 uvUpdated=uv;
#endif
#include<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
#include<instancesVertex>
#include<bonesVertex>
#include<bakedVertexAnimation>
gl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);
#ifdef USE_REVERSE_DEPTHBUFFER
vDepthMetric=((-gl_Position.z+depthValues.x)/(depthValues.y));
#else
vDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));
#endif
#if defined(ALPHATEST) || defined(BASIC_RENDER)
#ifdef UV1
vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));
#endif
#ifdef UV2
vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));
#endif
#endif
}
`;
ShaderStore.ShadersStore[name$q] = shader$q;
var DepthRenderer = function() {
    function i(e, t, r, n, o) {
        var a = this;
        t === void 0 && (t = 1),
        r === void 0 && (r = null),
        n === void 0 && (n = !1),
        o === void 0 && (o = Texture.TRILINEAR_SAMPLINGMODE),
        this.enabled = !0,
        this.forceDepthWriteTransparentMeshes = !1,
        this.useOnlyInActiveCamera = !1,
        this._scene = e,
        this._storeNonLinearDepth = n,
        this.isPacked = t === 0,
        this.isPacked ? this._clearColor = new Color4(1,1,1,1) : this._clearColor = new Color4(1,0,0,1),
        i._SceneComponentInitialization(this._scene);
        var s = e.getEngine();
        this._camera = r,
        o !== Texture.NEAREST_SAMPLINGMODE && (t === 1 && !s._caps.textureFloatLinearFiltering && (o = Texture.NEAREST_SAMPLINGMODE),
        t === 2 && !s._caps.textureHalfFloatLinearFiltering && (o = Texture.NEAREST_SAMPLINGMODE));
        var l = this.isPacked || !s._features.supportExtendedTextureFormats ? 5 : 6;
        this._depthMap = new RenderTargetTexture("DepthRenderer",{
            width: s.getRenderWidth(),
            height: s.getRenderHeight()
        },this._scene,!1,!0,t,!1,o,void 0,void 0,void 0,l),
        this._depthMap.wrapU = Texture.CLAMP_ADDRESSMODE,
        this._depthMap.wrapV = Texture.CLAMP_ADDRESSMODE,
        this._depthMap.refreshRate = 1,
        this._depthMap.renderParticles = !1,
        this._depthMap.renderList = null,
        this._depthMap.activeCamera = this._camera,
        this._depthMap.ignoreCameraViewport = !0,
        this._depthMap.useCameraPostProcesses = !1,
        this._depthMap.onClearObservable.add(function(c) {
            c.clear(a._clearColor, !0, !0, !0)
        }),
        this._depthMap.onBeforeBindObservable.add(function() {
            var c;
            (c = s._debugPushGroup) === null || c === void 0 || c.call(s, "depth renderer", 1)
        }),
        this._depthMap.onAfterUnbindObservable.add(function() {
            var c;
            (c = s._debugPopGroup) === null || c === void 0 || c.call(s, 1)
        });
        var u = function(c) {
            var h, f, d = c.getRenderingMesh(), _ = c.getEffectiveMesh(), g = a._scene, m = g.getEngine(), v = c.getMaterial();
            if (_._internalAbstractMeshDataInfo._isActiveIntermediate = !1,
            !(!v || _.infiniteDistance || v.disableDepthWrite || c.verticesCount === 0 || c._renderId === g.getRenderId())) {
                var y = _._getWorldMatrixDeterminant() < 0
                  , b = (h = d.overrideMaterialSideOrientation) !== null && h !== void 0 ? h : v.sideOrientation;
                (g.useRightHandedSystem && !y || !g.useRightHandedSystem && y) && (b = b === 0 ? 1 : 0);
                var T = b === 0;
                m.setState(v.backFaceCulling, 0, !1, T, v.cullBackFaces);
                var C = d._getInstancesRenderList(c._id, !!c.getReplacementMesh());
                if (!C.mustReturn) {
                    var A = m.getCaps().instancedArrays && (C.visibleInstances[c._id] !== null && C.visibleInstances[c._id] !== void 0 || d.hasThinInstances)
                      , S = a._camera || g.activeCamera;
                    if (a.isReady(c, A) && S) {
                        c._renderId = g.getRenderId();
                        var P = (f = _._internalAbstractMeshDataInfo._materialForRenderPass) === null || f === void 0 ? void 0 : f[m.currentRenderPassId]
                          , R = c._getDrawWrapper();
                        !R && P && (R = P._getDrawWrapper());
                        var M = S.mode === Camera$1.ORTHOGRAPHIC_CAMERA;
                        if (!R)
                            return;
                        var x = R.effect;
                        m.enableEffect(R),
                        A || d._bind(c, x, v.fillMode),
                        P ? P.bindForSubMesh(_.getWorldMatrix(), _, c) : (x.setMatrix("viewProjection", g.getTransformMatrix()),
                        x.setMatrix("world", _.getWorldMatrix()));
                        var I = void 0
                          , w = void 0;
                        if (M ? (I = !m.useReverseDepthBuffer && m.isNDCHalfZRange ? 0 : 1,
                        w = m.useReverseDepthBuffer && m.isNDCHalfZRange ? 0 : 1) : (I = m.useReverseDepthBuffer && m.isNDCHalfZRange ? S.minZ : m.isNDCHalfZRange ? 0 : S.minZ,
                        w = m.useReverseDepthBuffer && m.isNDCHalfZRange ? 0 : S.maxZ),
                        x.setFloat2("depthValues", I, I + w),
                        !P) {
                            if (v && v.needAlphaTesting()) {
                                var O = v.getAlphaTestTexture();
                                O && (x.setTexture("diffuseSampler", O),
                                x.setMatrix("diffuseMatrix", O.getTextureMatrix()))
                            }
                            if (d.useBones && d.computeBonesUsingShaders && d.skeleton) {
                                var D = d.skeleton;
                                if (D.isUsingTextureForMatrices) {
                                    var F = D.getTransformMatrixTexture(d);
                                    if (!F)
                                        return;
                                    x.setTexture("boneSampler", F),
                                    x.setFloat("boneTextureWidth", 4 * (D.bones.length + 1))
                                } else
                                    x.setMatrices("mBones", D.getTransformMatrices(d))
                            }
                            MaterialHelper.BindMorphTargetParameters(d, x),
                            d.morphTargetManager && d.morphTargetManager.isUsingTextureForTargets && d.morphTargetManager._bind(x)
                        }
                        d._processRendering(_, c, x, v.fillMode, C, A, function(V, N) {
                            return x.setMatrix("world", N)
                        })
                    }
                }
            }
        };
        this._depthMap.customRenderFunction = function(c, h, f, d) {
            var _;
            if (d.length)
                for (_ = 0; _ < d.length; _++)
                    u(d.data[_]);
            for (_ = 0; _ < c.length; _++)
                u(c.data[_]);
            for (_ = 0; _ < h.length; _++)
                u(h.data[_]);
            if (a.forceDepthWriteTransparentMeshes)
                for (_ = 0; _ < f.length; _++)
                    u(f.data[_]);
            else
                for (_ = 0; _ < f.length; _++)
                    f.data[_].getEffectiveMesh()._internalAbstractMeshDataInfo._isActiveIntermediate = !1
        }
    }
    return i.prototype.setMaterialForRendering = function(e, t) {
        this._depthMap.setMaterialForRendering(e, t)
    }
    ,
    i.prototype.isReady = function(e, t) {
        var r, n = this._scene.getEngine(), o = e.getMesh(), a = (r = o._internalAbstractMeshDataInfo._materialForRenderPass) === null || r === void 0 ? void 0 : r[n.currentRenderPassId];
        if (a)
            return a.isReadyForSubMesh(o, e, t);
        var s = e.getMaterial();
        if (!s || s.disableDepthWrite)
            return !1;
        var l = []
          , u = [VertexBuffer.PositionKind];
        if (s && s.needAlphaTesting() && s.getAlphaTestTexture() && (l.push("#define ALPHATEST"),
        o.isVerticesDataPresent(VertexBuffer.UVKind) && (u.push(VertexBuffer.UVKind),
        l.push("#define UV1")),
        o.isVerticesDataPresent(VertexBuffer.UV2Kind) && (u.push(VertexBuffer.UV2Kind),
        l.push("#define UV2"))),
        o.useBones && o.computeBonesUsingShaders) {
            u.push(VertexBuffer.MatricesIndicesKind),
            u.push(VertexBuffer.MatricesWeightsKind),
            o.numBoneInfluencers > 4 && (u.push(VertexBuffer.MatricesIndicesExtraKind),
            u.push(VertexBuffer.MatricesWeightsExtraKind)),
            l.push("#define NUM_BONE_INFLUENCERS " + o.numBoneInfluencers),
            l.push("#define BonesPerMesh " + (o.skeleton ? o.skeleton.bones.length + 1 : 0));
            var c = e.getRenderingMesh().skeleton;
            c != null && c.isUsingTextureForMatrices && l.push("#define BONETEXTURE")
        } else
            l.push("#define NUM_BONE_INFLUENCERS 0");
        var h = o.morphTargetManager
          , f = 0;
        h && h.numInfluencers > 0 && (f = h.numInfluencers,
        l.push("#define MORPHTARGETS"),
        l.push("#define NUM_MORPH_INFLUENCERS " + f),
        h.isUsingTextureForTargets && l.push("#define MORPHTARGETS_TEXTURE"),
        MaterialHelper.PrepareAttributesForMorphTargetsInfluencers(u, o, f)),
        t && (l.push("#define INSTANCES"),
        MaterialHelper.PushAttributesForInstances(u),
        e.getRenderingMesh().hasThinInstances && l.push("#define THIN_INSTANCES")),
        this._storeNonLinearDepth && l.push("#define NONLINEARDEPTH"),
        this.isPacked && l.push("#define PACKED");
        var d = e._getDrawWrapper(void 0, !0)
          , _ = d.defines
          , g = l.join(`
`);
        return _ !== g && d.setEffect(n.createEffect("depth", u, ["world", "mBones", "boneTextureWidth", "viewProjection", "diffuseMatrix", "depthValues", "morphTargetInfluences", "morphTargetTextureInfo", "morphTargetTextureIndices"], ["diffuseSampler", "morphTargets", "boneSampler"], g, void 0, void 0, void 0, {
            maxSimultaneousMorphTargets: f
        }), g),
        d.effect.isReady()
    }
    ,
    i.prototype.getDepthMap = function() {
        return this._depthMap
    }
    ,
    i.prototype.dispose = function() {
        var e = [];
        for (var t in this._scene._depthRenderer) {
            var r = this._scene._depthRenderer[t];
            r === this && e.push(t)
        }
        if (e.length > 0) {
            this._depthMap.dispose();
            for (var n = 0, o = e; n < o.length; n++) {
                var a = o[n];
                delete this._scene._depthRenderer[a]
            }
        }
    }
    ,
    i._SceneComponentInitialization = function(e) {
        throw _WarnImport("DepthRendererSceneComponent")
    }
    ,
    i
}()
  , name$p = "minmaxReduxPixelShader"
  , shader$p = `varying vec2 vUV;
uniform sampler2D textureSampler;
#if defined(INITIAL)
uniform sampler2D sourceTexture;
uniform vec2 texSize;
void main(void)
{
ivec2 coord=ivec2(vUV*(texSize-1.0));
float f1=texelFetch(sourceTexture,coord,0).r;
float f2=texelFetch(sourceTexture,coord+ivec2(1,0),0).r;
float f3=texelFetch(sourceTexture,coord+ivec2(1,1),0).r;
float f4=texelFetch(sourceTexture,coord+ivec2(0,1),0).r;
float minz=min(min(min(f1,f2),f3),f4);
#ifdef DEPTH_REDUX
float maxz=max(max(max(sign(1.0-f1)*f1,sign(1.0-f2)*f2),sign(1.0-f3)*f3),sign(1.0-f4)*f4);
#else
float maxz=max(max(max(f1,f2),f3),f4);
#endif
glFragColor=vec4(minz,maxz,0.,0.);
}
#elif defined(MAIN)
uniform vec2 texSize;
void main(void)
{
ivec2 coord=ivec2(vUV*(texSize-1.0));
vec2 f1=texelFetch(textureSampler,coord,0).rg;
vec2 f2=texelFetch(textureSampler,coord+ivec2(1,0),0).rg;
vec2 f3=texelFetch(textureSampler,coord+ivec2(1,1),0).rg;
vec2 f4=texelFetch(textureSampler,coord+ivec2(0,1),0).rg;
float minz=min(min(min(f1.x,f2.x),f3.x),f4.x);
float maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);
glFragColor=vec4(minz,maxz,0.,0.);
}
#elif defined(ONEBEFORELAST)
uniform ivec2 texSize;
void main(void)
{
ivec2 coord=ivec2(vUV*vec2(texSize-1));
vec2 f1=texelFetch(textureSampler,coord % texSize,0).rg;
vec2 f2=texelFetch(textureSampler,(coord+ivec2(1,0)) % texSize,0).rg;
vec2 f3=texelFetch(textureSampler,(coord+ivec2(1,1)) % texSize,0).rg;
vec2 f4=texelFetch(textureSampler,(coord+ivec2(0,1)) % texSize,0).rg;
float minz=min(f1.x,f2.x);
float maxz=max(f1.y,f2.y);
glFragColor=vec4(minz,maxz,0.,0.);
}
#elif defined(LAST)
void main(void)
{
glFragColor=vec4(0.);
discard;
}
#endif
`;
ShaderStore.ShadersStore[name$p] = shader$p;
var MinMaxReducer = function() {
    function i(e) {
        var t = this;
        this.onAfterReductionPerformed = new Observable,
        this._forceFullscreenViewport = !0,
        this._activated = !1,
        this._camera = e,
        this._postProcessManager = new PostProcessManager(e.getScene()),
        this._onContextRestoredObserver = e.getEngine().onContextRestoredObservable.add(function() {
            t._postProcessManager._rebuild()
        })
    }
    return Object.defineProperty(i.prototype, "sourceTexture", {
        get: function() {
            return this._sourceTexture
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.setSourceTexture = function(e, t, r, n) {
        var o = this;
        if (r === void 0 && (r = 2),
        n === void 0 && (n = !0),
        e !== this._sourceTexture) {
            this.dispose(!1),
            this._sourceTexture = e,
            this._reductionSteps = [],
            this._forceFullscreenViewport = n;
            var a = this._camera.getScene()
              , s = new PostProcess("Initial reduction phase","minmaxRedux",["texSize"],["sourceTexture"],1,null,1,a.getEngine(),!1,"#define INITIAL" + (t ? `
#define DEPTH_REDUX` : ""),r,void 0,void 0,void 0,7);
            s.autoClear = !1,
            s.forceFullscreenViewport = n;
            var l = this._sourceTexture.getRenderWidth()
              , u = this._sourceTexture.getRenderHeight();
            s.onApply = function(d, _) {
                return function(g) {
                    g.setTexture("sourceTexture", o._sourceTexture),
                    g.setFloat2("texSize", d, _)
                }
            }(l, u),
            this._reductionSteps.push(s);
            for (var c = 1; l > 1 || u > 1; ) {
                l = Math.max(Math.round(l / 2), 1),
                u = Math.max(Math.round(u / 2), 1);
                var h = new PostProcess("Reduction phase " + c,"minmaxRedux",["texSize"],null,{
                    width: l,
                    height: u
                },null,1,a.getEngine(),!1,"#define " + (l == 1 && u == 1 ? "LAST" : l == 1 || u == 1 ? "ONEBEFORELAST" : "MAIN"),r,void 0,void 0,void 0,7);
                if (h.autoClear = !1,
                h.forceFullscreenViewport = n,
                h.onApply = function(d, _) {
                    return function(g) {
                        d == 1 || _ == 1 ? g.setInt2("texSize", d, _) : g.setFloat2("texSize", d, _)
                    }
                }(l, u),
                this._reductionSteps.push(h),
                c++,
                l == 1 && u == 1) {
                    var f = function(d, _, g) {
                        var m = new Float32Array(4 * d * _)
                          , v = {
                            min: 0,
                            max: 0
                        };
                        return function() {
                            a.getEngine()._readTexturePixels(g.inputTexture.texture, d, _, -1, 0, m, !1),
                            v.min = m[0],
                            v.max = m[1],
                            o.onAfterReductionPerformed.notifyObservers(v)
                        }
                    };
                    h.onAfterRenderObservable.add(f(l, u, h))
                }
            }
        }
    }
    ,
    Object.defineProperty(i.prototype, "refreshRate", {
        get: function() {
            return this._sourceTexture ? this._sourceTexture.refreshRate : -1
        },
        set: function(e) {
            this._sourceTexture && (this._sourceTexture.refreshRate = e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "activated", {
        get: function() {
            return this._activated
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.activate = function() {
        var e = this;
        this._onAfterUnbindObserver || !this._sourceTexture || (this._onAfterUnbindObserver = this._sourceTexture.onAfterUnbindObservable.add(function() {
            var t, r, n = e._camera.getScene().getEngine();
            (t = n._debugPushGroup) === null || t === void 0 || t.call(n, "min max reduction", 1),
            e._reductionSteps[0].activate(e._camera),
            e._postProcessManager.directRender(e._reductionSteps, e._reductionSteps[0].inputTexture, e._forceFullscreenViewport),
            n.unBindFramebuffer(e._reductionSteps[0].inputTexture, !1),
            (r = n._debugPopGroup) === null || r === void 0 || r.call(n, 1)
        }),
        this._activated = !0)
    }
    ,
    i.prototype.deactivate = function() {
        !this._onAfterUnbindObserver || !this._sourceTexture || (this._sourceTexture.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),
        this._onAfterUnbindObserver = null,
        this._activated = !1)
    }
    ,
    i.prototype.dispose = function(e) {
        if (e === void 0 && (e = !0),
        e && (this.onAfterReductionPerformed.clear(),
        this._onContextRestoredObserver && (this._camera.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),
        this._onContextRestoredObserver = null)),
        this.deactivate(),
        this._reductionSteps) {
            for (var t = 0; t < this._reductionSteps.length; ++t)
                this._reductionSteps[t].dispose();
            this._reductionSteps = null
        }
        this._postProcessManager && e && this._postProcessManager.dispose(),
        this._sourceTexture = null
    }
    ,
    i
}()
  , DepthReducer = function(i) {
    __extends(e, i);
    function e(t) {
        return i.call(this, t) || this
    }
    return Object.defineProperty(e.prototype, "depthRenderer", {
        get: function() {
            return this._depthRenderer
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.setDepthRenderer = function(t, r, n) {
        t === void 0 && (t = null),
        r === void 0 && (r = 2),
        n === void 0 && (n = !0);
        var o = this._camera.getScene();
        this._depthRenderer && (delete o._depthRenderer[this._depthRendererId],
        this._depthRenderer.dispose(),
        this._depthRenderer = null),
        t === null && (o._depthRenderer || (o._depthRenderer = {}),
        t = this._depthRenderer = new DepthRenderer(o,r,this._camera,!1,1),
        t.enabled = !1,
        this._depthRendererId = "minmax" + this._camera.id,
        o._depthRenderer[this._depthRendererId] = t),
        i.prototype.setSourceTexture.call(this, t.getDepthMap(), !0, r, n)
    }
    ,
    e.prototype.setSourceTexture = function(t, r, n, o) {
        n === void 0 && (n = 2),
        o === void 0 && (o = !0),
        i.prototype.setSourceTexture.call(this, t, r, n, o)
    }
    ,
    e.prototype.activate = function() {
        this._depthRenderer && (this._depthRenderer.enabled = !0),
        i.prototype.activate.call(this)
    }
    ,
    e.prototype.deactivate = function() {
        i.prototype.deactivate.call(this),
        this._depthRenderer && (this._depthRenderer.enabled = !1)
    }
    ,
    e.prototype.dispose = function(t) {
        if (t === void 0 && (t = !0),
        i.prototype.dispose.call(this, t),
        this._depthRenderer && t) {
            var r = this._depthRenderer.getDepthMap().getScene();
            r && delete r._depthRenderer[this._depthRendererId],
            this._depthRenderer.dispose(),
            this._depthRenderer = null
        }
    }
    ,
    e
}(MinMaxReducer)
  , UpDir = Vector3.Up()
  , ZeroVec = Vector3.Zero()
  , tmpv1 = new Vector3
  , tmpv2 = new Vector3
  , tmpMatrix = new Matrix
  , CascadedShadowGenerator = function(i) {
    __extends(e, i);
    function e(t, r, n) {
        var o = this;
        if (!e.IsSupported) {
            Logger$2.Error("CascadedShadowMap is not supported by the current engine.");
            return
        }
        return o = i.call(this, t, r, n) || this,
        o.usePercentageCloserFiltering = !0,
        o
    }
    return e.prototype._validateFilter = function(t) {
        return t === ShadowGenerator.FILTER_NONE || t === ShadowGenerator.FILTER_PCF || t === ShadowGenerator.FILTER_PCSS ? t : (console.error('Unsupported filter "' + t + '"!'),
        ShadowGenerator.FILTER_NONE)
    }
    ,
    Object.defineProperty(e.prototype, "numCascades", {
        get: function() {
            return this._numCascades
        },
        set: function(t) {
            t = Math.min(Math.max(t, e.MIN_CASCADES_COUNT), e.MAX_CASCADES_COUNT),
            t !== this._numCascades && (this._numCascades = t,
            this.recreateShadowMap(),
            this._recreateSceneUBOs())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "freezeShadowCastersBoundingInfo", {
        get: function() {
            return this._freezeShadowCastersBoundingInfo
        },
        set: function(t) {
            this._freezeShadowCastersBoundingInfoObservable && t && (this._scene.onBeforeRenderObservable.remove(this._freezeShadowCastersBoundingInfoObservable),
            this._freezeShadowCastersBoundingInfoObservable = null),
            !this._freezeShadowCastersBoundingInfoObservable && !t && (this._freezeShadowCastersBoundingInfoObservable = this._scene.onBeforeRenderObservable.add(this._computeShadowCastersBoundingInfo.bind(this))),
            this._freezeShadowCastersBoundingInfo = t,
            t && this._computeShadowCastersBoundingInfo()
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._computeShadowCastersBoundingInfo = function() {
        if (this._scbiMin.copyFromFloats(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE),
        this._scbiMax.copyFromFloats(Number.MIN_VALUE, Number.MIN_VALUE, Number.MIN_VALUE),
        this._shadowMap && this._shadowMap.renderList) {
            for (var t = this._shadowMap.renderList, r = 0; r < t.length; r++) {
                var n = t[r];
                if (!!n) {
                    var o = n.getBoundingInfo()
                      , a = o.boundingBox;
                    this._scbiMin.minimizeInPlace(a.minimumWorld),
                    this._scbiMax.maximizeInPlace(a.maximumWorld)
                }
            }
            for (var s = this._scene.meshes, r = 0; r < s.length; r++) {
                var n = s[r];
                if (!(!n || !n.isVisible || !n.isEnabled || !n.receiveShadows)) {
                    var o = n.getBoundingInfo()
                      , a = o.boundingBox;
                    this._scbiMin.minimizeInPlace(a.minimumWorld),
                    this._scbiMax.maximizeInPlace(a.maximumWorld)
                }
            }
        }
        this._shadowCastersBoundingInfo.reConstruct(this._scbiMin, this._scbiMax)
    }
    ,
    Object.defineProperty(e.prototype, "shadowCastersBoundingInfo", {
        get: function() {
            return this._shadowCastersBoundingInfo
        },
        set: function(t) {
            this._shadowCastersBoundingInfo = t
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.setMinMaxDistance = function(t, r) {
        this._minDistance === t && this._maxDistance === r || (t > r && (t = 0,
        r = 1),
        t < 0 && (t = 0),
        r > 1 && (r = 1),
        this._minDistance = t,
        this._maxDistance = r,
        this._breaksAreDirty = !0)
    }
    ,
    Object.defineProperty(e.prototype, "minDistance", {
        get: function() {
            return this._minDistance
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "maxDistance", {
        get: function() {
            return this._maxDistance
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getClassName = function() {
        return e.CLASSNAME
    }
    ,
    e.prototype.getCascadeMinExtents = function(t) {
        return t >= 0 && t < this._numCascades ? this._cascadeMinExtents[t] : null
    }
    ,
    e.prototype.getCascadeMaxExtents = function(t) {
        return t >= 0 && t < this._numCascades ? this._cascadeMaxExtents[t] : null
    }
    ,
    Object.defineProperty(e.prototype, "shadowMaxZ", {
        get: function() {
            return !this._scene || !this._scene.activeCamera ? 0 : this._shadowMaxZ
        },
        set: function(t) {
            if (!this._scene || !this._scene.activeCamera) {
                this._shadowMaxZ = t;
                return
            }
            this._shadowMaxZ === t || t < this._scene.activeCamera.minZ || t > this._scene.activeCamera.maxZ || (this._shadowMaxZ = t,
            this._light._markMeshesAsLightDirty(),
            this._breaksAreDirty = !0)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "debug", {
        get: function() {
            return this._debug
        },
        set: function(t) {
            this._debug = t,
            this._light._markMeshesAsLightDirty()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "depthClamp", {
        get: function() {
            return this._depthClamp
        },
        set: function(t) {
            this._depthClamp = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cascadeBlendPercentage", {
        get: function() {
            return this._cascadeBlendPercentage
        },
        set: function(t) {
            this._cascadeBlendPercentage = t,
            this._light._markMeshesAsLightDirty()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "lambda", {
        get: function() {
            return this._lambda
        },
        set: function(t) {
            var r = Math.min(Math.max(t, 0), 1);
            this._lambda != r && (this._lambda = r,
            this._breaksAreDirty = !0)
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getCascadeViewMatrix = function(t) {
        return t >= 0 && t < this._numCascades ? this._viewMatrices[t] : null
    }
    ,
    e.prototype.getCascadeProjectionMatrix = function(t) {
        return t >= 0 && t < this._numCascades ? this._projectionMatrices[t] : null
    }
    ,
    e.prototype.getCascadeTransformMatrix = function(t) {
        return t >= 0 && t < this._numCascades ? this._transformMatrices[t] : null
    }
    ,
    e.prototype.setDepthRenderer = function(t) {
        this._depthRenderer = t,
        this._depthReducer && this._depthReducer.setDepthRenderer(this._depthRenderer)
    }
    ,
    Object.defineProperty(e.prototype, "autoCalcDepthBounds", {
        get: function() {
            return this._autoCalcDepthBounds
        },
        set: function(t) {
            var r = this
              , n = this._scene.activeCamera;
            if (!!n) {
                if (this._autoCalcDepthBounds = t,
                !t) {
                    this._depthReducer && this._depthReducer.deactivate(),
                    this.setMinMaxDistance(0, 1);
                    return
                }
                this._depthReducer || (this._depthReducer = new DepthReducer(n),
                this._depthReducer.onAfterReductionPerformed.add(function(o) {
                    var a = o.min
                      , s = o.max;
                    a >= s && (a = 0,
                    s = 1),
                    (a != r._minDistance || s != r._maxDistance) && r.setMinMaxDistance(a, s)
                }),
                this._depthReducer.setDepthRenderer(this._depthRenderer)),
                this._depthReducer.activate()
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "autoCalcDepthBoundsRefreshRate", {
        get: function() {
            var t, r, n;
            return (n = (r = (t = this._depthReducer) === null || t === void 0 ? void 0 : t.depthRenderer) === null || r === void 0 ? void 0 : r.getDepthMap().refreshRate) !== null && n !== void 0 ? n : -1
        },
        set: function(t) {
            var r;
            !((r = this._depthReducer) === null || r === void 0) && r.depthRenderer && (this._depthReducer.depthRenderer.getDepthMap().refreshRate = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.splitFrustum = function() {
        this._breaksAreDirty = !0
    }
    ,
    e.prototype._splitFrustum = function() {
        var t = this._scene.activeCamera;
        if (!!t) {
            for (var r = t.minZ, n = t.maxZ, o = n - r, a = this._minDistance, s = this._shadowMaxZ < n && this._shadowMaxZ >= r ? Math.min((this._shadowMaxZ - r) / (n - r), this._maxDistance) : this._maxDistance, l = r + a * o, u = r + s * o, c = u - l, h = u / l, f = 0; f < this._cascades.length; ++f) {
                var d = (f + 1) / this._numCascades
                  , _ = l * Math.pow(h, d)
                  , g = l + c * d
                  , m = this._lambda * (_ - g) + g;
                this._cascades[f].prevBreakDistance = f === 0 ? a : this._cascades[f - 1].breakDistance,
                this._cascades[f].breakDistance = (m - r) / o,
                this._viewSpaceFrustumsZ[f] = m,
                this._frustumLengths[f] = (this._cascades[f].breakDistance - this._cascades[f].prevBreakDistance) * o
            }
            this._breaksAreDirty = !1
        }
    }
    ,
    e.prototype._computeMatrices = function() {
        var t = this._scene
          , r = t.activeCamera;
        if (!!r) {
            Vector3.NormalizeToRef(this._light.getShadowDirection(0), this._lightDirection),
            Math.abs(Vector3.Dot(this._lightDirection, Vector3.Up())) === 1 && (this._lightDirection.z = 1e-13),
            this._cachedDirection.copyFrom(this._lightDirection);
            for (var n = t.getEngine().useReverseDepthBuffer, o = 0; o < this._numCascades; ++o) {
                this._computeFrustumInWorldSpace(o),
                this._computeCascadeFrustum(o),
                this._cascadeMaxExtents[o].subtractToRef(this._cascadeMinExtents[o], tmpv1),
                this._frustumCenter[o].addToRef(this._lightDirection.scale(this._cascadeMinExtents[o].z), this._shadowCameraPos[o]),
                Matrix.LookAtLHToRef(this._shadowCameraPos[o], this._frustumCenter[o], UpDir, this._viewMatrices[o]);
                var a = 0
                  , s = tmpv1.z
                  , l = this._shadowCastersBoundingInfo;
                l.update(this._viewMatrices[o]),
                s = Math.min(s, l.boundingBox.maximumWorld.z),
                !this._depthClamp || this.filter === ShadowGenerator.FILTER_PCSS ? a = Math.min(a, l.boundingBox.minimumWorld.z) : a = Math.max(a, l.boundingBox.minimumWorld.z),
                Matrix.OrthoOffCenterLHToRef(this._cascadeMinExtents[o].x, this._cascadeMaxExtents[o].x, this._cascadeMinExtents[o].y, this._cascadeMaxExtents[o].y, n ? s : a, n ? a : s, this._projectionMatrices[o], t.getEngine().isNDCHalfZRange),
                this._cascadeMinExtents[o].z = a,
                this._cascadeMaxExtents[o].z = s,
                this._viewMatrices[o].multiplyToRef(this._projectionMatrices[o], this._transformMatrices[o]),
                Vector3.TransformCoordinatesToRef(ZeroVec, this._transformMatrices[o], tmpv1),
                tmpv1.scaleInPlace(this._mapSize / 2),
                tmpv2.copyFromFloats(Math.round(tmpv1.x), Math.round(tmpv1.y), Math.round(tmpv1.z)),
                tmpv2.subtractInPlace(tmpv1).scaleInPlace(2 / this._mapSize),
                Matrix.TranslationToRef(tmpv2.x, tmpv2.y, 0, tmpMatrix),
                this._projectionMatrices[o].multiplyToRef(tmpMatrix, this._projectionMatrices[o]),
                this._viewMatrices[o].multiplyToRef(this._projectionMatrices[o], this._transformMatrices[o]),
                this._transformMatrices[o].copyToArray(this._transformMatricesAsArray, o * 16)
            }
        }
    }
    ,
    e.prototype._computeFrustumInWorldSpace = function(t) {
        if (!!this._scene.activeCamera) {
            var r = this._cascades[t].prevBreakDistance
              , n = this._cascades[t].breakDistance
              , o = this._scene.getEngine().isNDCHalfZRange;
            this._scene.activeCamera.getViewMatrix();
            for (var a = Matrix.Invert(this._scene.activeCamera.getTransformationMatrix()), s = this._scene.getEngine().useReverseDepthBuffer ? 4 : 0, l = 0; l < e.frustumCornersNDCSpace.length; ++l)
                tmpv1.copyFrom(e.frustumCornersNDCSpace[(l + s) % e.frustumCornersNDCSpace.length]),
                o && tmpv1.z === -1 && (tmpv1.z = 0),
                Vector3.TransformCoordinatesToRef(tmpv1, a, this._frustumCornersWorldSpace[t][l]);
            for (var l = 0; l < e.frustumCornersNDCSpace.length / 2; ++l)
                tmpv1.copyFrom(this._frustumCornersWorldSpace[t][l + 4]).subtractInPlace(this._frustumCornersWorldSpace[t][l]),
                tmpv2.copyFrom(tmpv1).scaleInPlace(r),
                tmpv1.scaleInPlace(n),
                tmpv1.addInPlace(this._frustumCornersWorldSpace[t][l]),
                this._frustumCornersWorldSpace[t][l + 4].copyFrom(tmpv1),
                this._frustumCornersWorldSpace[t][l].addInPlace(tmpv2)
        }
    }
    ,
    e.prototype._computeCascadeFrustum = function(t) {
        this._cascadeMinExtents[t].copyFromFloats(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE),
        this._cascadeMaxExtents[t].copyFromFloats(Number.MIN_VALUE, Number.MIN_VALUE, Number.MIN_VALUE),
        this._frustumCenter[t].copyFromFloats(0, 0, 0);
        var r = this._scene.activeCamera;
        if (!!r) {
            for (var n = 0; n < this._frustumCornersWorldSpace[t].length; ++n)
                this._frustumCenter[t].addInPlace(this._frustumCornersWorldSpace[t][n]);
            if (this._frustumCenter[t].scaleInPlace(1 / this._frustumCornersWorldSpace[t].length),
            this.stabilizeCascades) {
                for (var o = 0, n = 0; n < this._frustumCornersWorldSpace[t].length; ++n) {
                    var a = this._frustumCornersWorldSpace[t][n].subtractToRef(this._frustumCenter[t], tmpv1).length();
                    o = Math.max(o, a)
                }
                o = Math.ceil(o * 16) / 16,
                this._cascadeMaxExtents[t].copyFromFloats(o, o, o),
                this._cascadeMinExtents[t].copyFromFloats(-o, -o, -o)
            } else {
                var s = this._frustumCenter[t];
                this._frustumCenter[t].addToRef(this._lightDirection, tmpv1),
                Matrix.LookAtLHToRef(s, tmpv1, UpDir, tmpMatrix);
                for (var n = 0; n < this._frustumCornersWorldSpace[t].length; ++n)
                    Vector3.TransformCoordinatesToRef(this._frustumCornersWorldSpace[t][n], tmpMatrix, tmpv1),
                    this._cascadeMinExtents[t].minimizeInPlace(tmpv1),
                    this._cascadeMaxExtents[t].maximizeInPlace(tmpv1)
            }
        }
    }
    ,
    e.prototype._recreateSceneUBOs = function() {
        if (this._disposeSceneUBOs(),
        this._sceneUBOs)
            for (var t = 0; t < this._numCascades; ++t)
                this._sceneUBOs.push(this._scene.createSceneUniformBuffer('Scene for CSM Shadow Generator (light "' + this._light.name + '" cascade #' + t + ")"))
    }
    ,
    Object.defineProperty(e, "IsSupported", {
        get: function() {
            var t = EngineStore.LastCreatedEngine;
            return t ? t._features.supportCSM : !1
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._initializeGenerator = function() {
        var t, r, n, o, a, s, l, u, c, h, f, d, _, g, m, v, y, b, T, C;
        this.penumbraDarkness = (t = this.penumbraDarkness) !== null && t !== void 0 ? t : 1,
        this._numCascades = (r = this._numCascades) !== null && r !== void 0 ? r : e.DEFAULT_CASCADES_COUNT,
        this.stabilizeCascades = (n = this.stabilizeCascades) !== null && n !== void 0 ? n : !1,
        this._freezeShadowCastersBoundingInfoObservable = (o = this._freezeShadowCastersBoundingInfoObservable) !== null && o !== void 0 ? o : null,
        this.freezeShadowCastersBoundingInfo = (a = this.freezeShadowCastersBoundingInfo) !== null && a !== void 0 ? a : !1,
        this._scbiMin = (s = this._scbiMin) !== null && s !== void 0 ? s : new Vector3(0,0,0),
        this._scbiMax = (l = this._scbiMax) !== null && l !== void 0 ? l : new Vector3(0,0,0),
        this._shadowCastersBoundingInfo = (u = this._shadowCastersBoundingInfo) !== null && u !== void 0 ? u : new BoundingInfo(new Vector3(0,0,0),new Vector3(0,0,0)),
        this._breaksAreDirty = (c = this._breaksAreDirty) !== null && c !== void 0 ? c : !0,
        this._minDistance = (h = this._minDistance) !== null && h !== void 0 ? h : 0,
        this._maxDistance = (f = this._maxDistance) !== null && f !== void 0 ? f : 1,
        this._currentLayer = (d = this._currentLayer) !== null && d !== void 0 ? d : 0,
        this._shadowMaxZ = (m = (_ = this._shadowMaxZ) !== null && _ !== void 0 ? _ : (g = this._scene.activeCamera) === null || g === void 0 ? void 0 : g.maxZ) !== null && m !== void 0 ? m : 1e4,
        this._debug = (v = this._debug) !== null && v !== void 0 ? v : !1,
        this._depthClamp = (y = this._depthClamp) !== null && y !== void 0 ? y : !0,
        this._cascadeBlendPercentage = (b = this._cascadeBlendPercentage) !== null && b !== void 0 ? b : .1,
        this._lambda = (T = this._lambda) !== null && T !== void 0 ? T : .5,
        this._autoCalcDepthBounds = (C = this._autoCalcDepthBounds) !== null && C !== void 0 ? C : !1,
        this._recreateSceneUBOs(),
        i.prototype._initializeGenerator.call(this)
    }
    ,
    e.prototype._createTargetRenderTexture = function() {
        var t = this._scene.getEngine()
          , r = {
            width: this._mapSize,
            height: this._mapSize,
            layers: this.numCascades
        };
        this._shadowMap = new RenderTargetTexture(this._light.name + "_CSMShadowMap",r,this._scene,!1,!0,this._textureType,!1,void 0,!1,!1,void 0),
        this._shadowMap.createDepthStencilTexture(t.useReverseDepthBuffer ? 516 : 513, !0)
    }
    ,
    e.prototype._initializeShadowMap = function() {
        var t = this;
        if (i.prototype._initializeShadowMap.call(this),
        this._shadowMap !== null) {
            this._transformMatricesAsArray = new Float32Array(this._numCascades * 16),
            this._viewSpaceFrustumsZ = new Array(this._numCascades),
            this._frustumLengths = new Array(this._numCascades),
            this._lightSizeUVCorrection = new Array(this._numCascades * 2),
            this._depthCorrection = new Array(this._numCascades),
            this._cascades = [],
            this._viewMatrices = [],
            this._projectionMatrices = [],
            this._transformMatrices = [],
            this._cascadeMinExtents = [],
            this._cascadeMaxExtents = [],
            this._frustumCenter = [],
            this._shadowCameraPos = [],
            this._frustumCornersWorldSpace = [];
            for (var r = 0; r < this._numCascades; ++r) {
                this._cascades[r] = {
                    prevBreakDistance: 0,
                    breakDistance: 0
                },
                this._viewMatrices[r] = Matrix.Zero(),
                this._projectionMatrices[r] = Matrix.Zero(),
                this._transformMatrices[r] = Matrix.Zero(),
                this._cascadeMinExtents[r] = new Vector3,
                this._cascadeMaxExtents[r] = new Vector3,
                this._frustumCenter[r] = new Vector3,
                this._shadowCameraPos[r] = new Vector3,
                this._frustumCornersWorldSpace[r] = new Array(e.frustumCornersNDCSpace.length);
                for (var n = 0; n < e.frustumCornersNDCSpace.length; ++n)
                    this._frustumCornersWorldSpace[r][n] = new Vector3
            }
            var o = this._scene.getEngine();
            this._shadowMap.onBeforeBindObservable.clear(),
            this._shadowMap.onBeforeRenderObservable.clear(),
            this._shadowMap.onBeforeRenderObservable.add(function(a) {
                t._sceneUBOs && t._scene.setSceneUniformBuffer(t._sceneUBOs[a]),
                t._currentLayer = a,
                t._filter === ShadowGenerator.FILTER_PCF && o.setColorWrite(!1),
                t._scene.setTransformMatrix(t.getCascadeViewMatrix(a), t.getCascadeProjectionMatrix(a)),
                t._useUBO && (t._scene.getSceneUniformBuffer().unbindEffect(),
                t._scene.finalizeSceneUbo())
            }),
            this._shadowMap.onBeforeBindObservable.add(function() {
                var a;
                t._currentSceneUBO = t._scene.getSceneUniformBuffer(),
                (a = o._debugPushGroup) === null || a === void 0 || a.call(o, "cascaded shadow map generation for pass id " + o.currentRenderPassId, 1),
                t._breaksAreDirty && t._splitFrustum(),
                t._computeMatrices()
            }),
            this._splitFrustum()
        }
    }
    ,
    e.prototype._bindCustomEffectForRenderSubMeshForShadowMap = function(t, r, n) {
        r.setMatrix("viewProjection", this.getCascadeTransformMatrix(this._currentLayer))
    }
    ,
    e.prototype._isReadyCustomDefines = function(t, r, n) {
        t.push("#define SM_DEPTHCLAMP " + (this._depthClamp && this._filter !== ShadowGenerator.FILTER_PCSS ? "1" : "0"))
    }
    ,
    e.prototype.prepareDefines = function(t, r) {
        i.prototype.prepareDefines.call(this, t, r);
        var n = this._scene
          , o = this._light;
        if (!(!n.shadowsEnabled || !o.shadowEnabled)) {
            t["SHADOWCSM" + r] = !0,
            t["SHADOWCSMDEBUG" + r] = this.debug,
            t["SHADOWCSMNUM_CASCADES" + r] = this.numCascades,
            t["SHADOWCSM_RIGHTHANDED" + r] = n.useRightHandedSystem;
            var a = n.activeCamera;
            a && this._shadowMaxZ < a.maxZ && (t["SHADOWCSMUSESHADOWMAXZ" + r] = !0),
            this.cascadeBlendPercentage === 0 && (t["SHADOWCSMNOBLEND" + r] = !0)
        }
    }
    ,
    e.prototype.bindShadowLight = function(t, r) {
        var n = this._light
          , o = this._scene;
        if (!(!o.shadowsEnabled || !n.shadowEnabled)) {
            var a = o.activeCamera;
            if (!!a) {
                var s = this.getShadowMap();
                if (!!s) {
                    var l = s.getSize().width;
                    if (r.setMatrices("lightMatrix" + t, this._transformMatricesAsArray),
                    r.setArray("viewFrustumZ" + t, this._viewSpaceFrustumsZ),
                    r.setFloat("cascadeBlendFactor" + t, this.cascadeBlendPercentage === 0 ? 1e4 : 1 / this.cascadeBlendPercentage),
                    r.setArray("frustumLengths" + t, this._frustumLengths),
                    this._filter === ShadowGenerator.FILTER_PCF)
                        r.setDepthStencilTexture("shadowSampler" + t, s),
                        n._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), l, 1 / l, this.frustumEdgeFalloff, t);
                    else if (this._filter === ShadowGenerator.FILTER_PCSS) {
                        for (var u = 0; u < this._numCascades; ++u)
                            this._lightSizeUVCorrection[u * 2 + 0] = u === 0 ? 1 : (this._cascadeMaxExtents[0].x - this._cascadeMinExtents[0].x) / (this._cascadeMaxExtents[u].x - this._cascadeMinExtents[u].x),
                            this._lightSizeUVCorrection[u * 2 + 1] = u === 0 ? 1 : (this._cascadeMaxExtents[0].y - this._cascadeMinExtents[0].y) / (this._cascadeMaxExtents[u].y - this._cascadeMinExtents[u].y),
                            this._depthCorrection[u] = u === 0 ? 1 : (this._cascadeMaxExtents[u].z - this._cascadeMinExtents[u].z) / (this._cascadeMaxExtents[0].z - this._cascadeMinExtents[0].z);
                        r.setDepthStencilTexture("shadowSampler" + t, s),
                        r.setTexture("depthSampler" + t, s),
                        r.setArray2("lightSizeUVCorrection" + t, this._lightSizeUVCorrection),
                        r.setArray("depthCorrection" + t, this._depthCorrection),
                        r.setFloat("penumbraDarkness" + t, this.penumbraDarkness),
                        n._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / l, this._contactHardeningLightSizeUVRatio * l, this.frustumEdgeFalloff, t)
                    } else
                        r.setTexture("shadowSampler" + t, s),
                        n._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), l, 1 / l, this.frustumEdgeFalloff, t);
                    n._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(a), this.getLight().getDepthMinZ(a) + this.getLight().getDepthMaxZ(a), t)
                }
            }
        }
    }
    ,
    e.prototype.getTransformMatrix = function() {
        return this.getCascadeTransformMatrix(0)
    }
    ,
    e.prototype.dispose = function() {
        i.prototype.dispose.call(this),
        this._freezeShadowCastersBoundingInfoObservable && (this._scene.onBeforeRenderObservable.remove(this._freezeShadowCastersBoundingInfoObservable),
        this._freezeShadowCastersBoundingInfoObservable = null),
        this._depthReducer && (this._depthReducer.dispose(),
        this._depthReducer = null)
    }
    ,
    e.prototype.serialize = function() {
        var t = i.prototype.serialize.call(this)
          , r = this.getShadowMap();
        if (!r)
            return t;
        if (t.numCascades = this._numCascades,
        t.debug = this._debug,
        t.stabilizeCascades = this.stabilizeCascades,
        t.lambda = this._lambda,
        t.cascadeBlendPercentage = this.cascadeBlendPercentage,
        t.depthClamp = this._depthClamp,
        t.autoCalcDepthBounds = this.autoCalcDepthBounds,
        t.shadowMaxZ = this._shadowMaxZ,
        t.penumbraDarkness = this.penumbraDarkness,
        t.freezeShadowCastersBoundingInfo = this._freezeShadowCastersBoundingInfo,
        t.minDistance = this.minDistance,
        t.maxDistance = this.maxDistance,
        t.renderList = [],
        r.renderList)
            for (var n = 0; n < r.renderList.length; n++) {
                var o = r.renderList[n];
                t.renderList.push(o.id)
            }
        return t
    }
    ,
    e.Parse = function(t, r) {
        var n = ShadowGenerator.Parse(t, r, function(o, a) {
            return new e(o,a)
        });
        return t.numCascades !== void 0 && (n.numCascades = t.numCascades),
        t.debug !== void 0 && (n.debug = t.debug),
        t.stabilizeCascades !== void 0 && (n.stabilizeCascades = t.stabilizeCascades),
        t.lambda !== void 0 && (n.lambda = t.lambda),
        t.cascadeBlendPercentage !== void 0 && (n.cascadeBlendPercentage = t.cascadeBlendPercentage),
        t.depthClamp !== void 0 && (n.depthClamp = t.depthClamp),
        t.autoCalcDepthBounds !== void 0 && (n.autoCalcDepthBounds = t.autoCalcDepthBounds),
        t.shadowMaxZ !== void 0 && (n.shadowMaxZ = t.shadowMaxZ),
        t.penumbraDarkness !== void 0 && (n.penumbraDarkness = t.penumbraDarkness),
        t.freezeShadowCastersBoundingInfo !== void 0 && (n.freezeShadowCastersBoundingInfo = t.freezeShadowCastersBoundingInfo),
        t.minDistance !== void 0 && t.maxDistance !== void 0 && n.setMinMaxDistance(t.minDistance, t.maxDistance),
        n
    }
    ,
    e.frustumCornersNDCSpace = [new Vector3(-1,1,-1), new Vector3(1,1,-1), new Vector3(1,-1,-1), new Vector3(-1,-1,-1), new Vector3(-1,1,1), new Vector3(1,1,1), new Vector3(1,-1,1), new Vector3(-1,-1,1)],
    e.CLASSNAME = "CascadedShadowGenerator",
    e.DEFAULT_CASCADES_COUNT = 4,
    e.MIN_CASCADES_COUNT = 2,
    e.MAX_CASCADES_COUNT = 4,
    e._SceneComponentInitialization = function(t) {
        throw _WarnImport("ShadowGeneratorSceneComponent")
    }
    ,
    e
}(ShadowGenerator);
AbstractScene.AddParser(SceneComponentConstants.NAME_SHADOWGENERATOR, function(i, e) {
    if (i.shadowGenerators !== void 0 && i.shadowGenerators !== null)
        for (var t = 0, r = i.shadowGenerators.length; t < r; t++) {
            var n = i.shadowGenerators[t];
            n.className === CascadedShadowGenerator.CLASSNAME ? CascadedShadowGenerator.Parse(n, e) : ShadowGenerator.Parse(n, e)
        }
});
var ShadowGeneratorSceneComponent = function() {
    function i(e) {
        this.name = SceneComponentConstants.NAME_SHADOWGENERATOR,
        this.scene = e
    }
    return i.prototype.register = function() {
        this.scene._gatherRenderTargetsStage.registerStep(SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets)
    }
    ,
    i.prototype.rebuild = function() {}
    ,
    i.prototype.serialize = function(e) {
        e.shadowGenerators = [];
        for (var t = this.scene.lights, r = 0, n = t; r < n.length; r++) {
            var o = n[r]
              , a = o.getShadowGenerator();
            a && e.shadowGenerators.push(a.serialize())
        }
    }
    ,
    i.prototype.addFromContainer = function(e) {}
    ,
    i.prototype.removeFromContainer = function(e, t) {}
    ,
    i.prototype.dispose = function() {}
    ,
    i.prototype._gatherRenderTargets = function(e) {
        var t = this.scene;
        if (this.scene.shadowsEnabled)
            for (var r = 0; r < t.lights.length; r++) {
                var n = t.lights[r]
                  , o = n.getShadowGenerator();
                if (n.isEnabled() && n.shadowEnabled && o) {
                    var a = o.getShadowMap();
                    t.textures.indexOf(a) !== -1 && e.push(a)
                }
            }
    }
    ,
    i
}();
ShadowGenerator._SceneComponentInitialization = function(i) {
    var e = i._getComponent(SceneComponentConstants.NAME_SHADOWGENERATOR);
    e || (e = new ShadowGeneratorSceneComponent(i),
    i._addComponent(e))
}
;
var DDS_MAGIC = 542327876
  , DDSD_MIPMAPCOUNT = 131072
  , DDSCAPS2_CUBEMAP = 512
  , DDPF_FOURCC = 4
  , DDPF_RGB = 64
  , DDPF_LUMINANCE = 131072;
function FourCCToInt32(i) {
    return i.charCodeAt(0) + (i.charCodeAt(1) << 8) + (i.charCodeAt(2) << 16) + (i.charCodeAt(3) << 24)
}
function Int32ToFourCC(i) {
    return String.fromCharCode(i & 255, i >> 8 & 255, i >> 16 & 255, i >> 24 & 255)
}
var FOURCC_DXT1 = FourCCToInt32("DXT1")
  , FOURCC_DXT3 = FourCCToInt32("DXT3")
  , FOURCC_DXT5 = FourCCToInt32("DXT5")
  , FOURCC_DX10 = FourCCToInt32("DX10")
  , FOURCC_D3DFMT_R16G16B16A16F = 113
  , FOURCC_D3DFMT_R32G32B32A32F = 116
  , DXGI_FORMAT_R32G32B32A32_FLOAT = 2
  , DXGI_FORMAT_R16G16B16A16_FLOAT = 10
  , DXGI_FORMAT_B8G8R8X8_UNORM = 88
  , headerLengthInt = 31
  , off_magic = 0
  , off_size = 1
  , off_flags = 2
  , off_height = 3
  , off_width = 4
  , off_mipmapCount = 7
  , off_pfFlags = 20
  , off_pfFourCC = 21
  , off_RGBbpp = 22
  , off_RMask = 23
  , off_GMask = 24
  , off_BMask = 25
  , off_AMask = 26
  , off_caps2 = 28
  , off_dxgiFormat = 32
  , DDSTools = function() {
    function i() {}
    return i.GetDDSInfo = function(e) {
        var t = new Int32Array(e.buffer,e.byteOffset,headerLengthInt)
          , r = new Int32Array(e.buffer,e.byteOffset,headerLengthInt + 4)
          , n = 1;
        t[off_flags] & DDSD_MIPMAPCOUNT && (n = Math.max(1, t[off_mipmapCount]));
        var o = t[off_pfFourCC]
          , a = o === FOURCC_DX10 ? r[off_dxgiFormat] : 0
          , s = 0;
        switch (o) {
        case FOURCC_D3DFMT_R16G16B16A16F:
            s = 2;
            break;
        case FOURCC_D3DFMT_R32G32B32A32F:
            s = 1;
            break;
        case FOURCC_DX10:
            if (a === DXGI_FORMAT_R16G16B16A16_FLOAT) {
                s = 2;
                break
            }
            if (a === DXGI_FORMAT_R32G32B32A32_FLOAT) {
                s = 1;
                break
            }
        }
        return {
            width: t[off_width],
            height: t[off_height],
            mipmapCount: n,
            isFourCC: (t[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
            isRGB: (t[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
            isLuminance: (t[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
            isCube: (t[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
            isCompressed: o === FOURCC_DXT1 || o === FOURCC_DXT3 || o === FOURCC_DXT5,
            dxgiFormat: a,
            textureType: s
        }
    }
    ,
    i._GetHalfFloatAsFloatRGBAArrayBuffer = function(e, t, r, n, o, a) {
        for (var s = new Float32Array(n), l = new Uint16Array(o,r), u = 0, c = 0; c < t; c++)
            for (var h = 0; h < e; h++) {
                var f = (h + c * e) * 4;
                s[u] = FromHalfFloat(l[f]),
                s[u + 1] = FromHalfFloat(l[f + 1]),
                s[u + 2] = FromHalfFloat(l[f + 2]),
                i.StoreLODInAlphaChannel ? s[u + 3] = a : s[u + 3] = FromHalfFloat(l[f + 3]),
                u += 4
            }
        return s
    }
    ,
    i._GetHalfFloatRGBAArrayBuffer = function(e, t, r, n, o, a) {
        if (i.StoreLODInAlphaChannel) {
            for (var s = new Uint16Array(n), l = new Uint16Array(o,r), u = 0, c = 0; c < t; c++)
                for (var h = 0; h < e; h++) {
                    var f = (h + c * e) * 4;
                    s[u] = l[f],
                    s[u + 1] = l[f + 1],
                    s[u + 2] = l[f + 2],
                    s[u + 3] = ToHalfFloat(a),
                    u += 4
                }
            return s
        }
        return new Uint16Array(o,r,n)
    }
    ,
    i._GetFloatRGBAArrayBuffer = function(e, t, r, n, o, a) {
        if (i.StoreLODInAlphaChannel) {
            for (var s = new Float32Array(n), l = new Float32Array(o,r), u = 0, c = 0; c < t; c++)
                for (var h = 0; h < e; h++) {
                    var f = (h + c * e) * 4;
                    s[u] = l[f],
                    s[u + 1] = l[f + 1],
                    s[u + 2] = l[f + 2],
                    s[u + 3] = a,
                    u += 4
                }
            return s
        }
        return new Float32Array(o,r,n)
    }
    ,
    i._GetFloatAsHalfFloatRGBAArrayBuffer = function(e, t, r, n, o, a) {
        for (var s = new Uint16Array(n), l = new Float32Array(o,r), u = 0, c = 0; c < t; c++)
            for (var h = 0; h < e; h++)
                s[u] = ToHalfFloat(l[u]),
                s[u + 1] = ToHalfFloat(l[u + 1]),
                s[u + 2] = ToHalfFloat(l[u + 2]),
                i.StoreLODInAlphaChannel ? s[u + 3] = ToHalfFloat(a) : s[u + 3] = ToHalfFloat(l[u + 3]),
                u += 4;
        return s
    }
    ,
    i._GetFloatAsUIntRGBAArrayBuffer = function(e, t, r, n, o, a) {
        for (var s = new Uint8Array(n), l = new Float32Array(o,r), u = 0, c = 0; c < t; c++)
            for (var h = 0; h < e; h++) {
                var f = (h + c * e) * 4;
                s[u] = Scalar.Clamp(l[f]) * 255,
                s[u + 1] = Scalar.Clamp(l[f + 1]) * 255,
                s[u + 2] = Scalar.Clamp(l[f + 2]) * 255,
                i.StoreLODInAlphaChannel ? s[u + 3] = a : s[u + 3] = Scalar.Clamp(l[f + 3]) * 255,
                u += 4
            }
        return s
    }
    ,
    i._GetHalfFloatAsUIntRGBAArrayBuffer = function(e, t, r, n, o, a) {
        for (var s = new Uint8Array(n), l = new Uint16Array(o,r), u = 0, c = 0; c < t; c++)
            for (var h = 0; h < e; h++) {
                var f = (h + c * e) * 4;
                s[u] = Scalar.Clamp(FromHalfFloat(l[f])) * 255,
                s[u + 1] = Scalar.Clamp(FromHalfFloat(l[f + 1])) * 255,
                s[u + 2] = Scalar.Clamp(FromHalfFloat(l[f + 2])) * 255,
                i.StoreLODInAlphaChannel ? s[u + 3] = a : s[u + 3] = Scalar.Clamp(FromHalfFloat(l[f + 3])) * 255,
                u += 4
            }
        return s
    }
    ,
    i._GetRGBAArrayBuffer = function(e, t, r, n, o, a, s, l, u) {
        for (var c = new Uint8Array(n), h = new Uint8Array(o,r), f = 0, d = 0; d < t; d++)
            for (var _ = 0; _ < e; _++) {
                var g = (_ + d * e) * 4;
                c[f] = h[g + a],
                c[f + 1] = h[g + s],
                c[f + 2] = h[g + l],
                c[f + 3] = h[g + u],
                f += 4
            }
        return c
    }
    ,
    i._ExtractLongWordOrder = function(e) {
        return e === 0 || e === 255 || e === -16777216 ? 0 : 1 + i._ExtractLongWordOrder(e >> 8)
    }
    ,
    i._GetRGBArrayBuffer = function(e, t, r, n, o, a, s, l) {
        for (var u = new Uint8Array(n), c = new Uint8Array(o,r), h = 0, f = 0; f < t; f++)
            for (var d = 0; d < e; d++) {
                var _ = (d + f * e) * 3;
                u[h] = c[_ + a],
                u[h + 1] = c[_ + s],
                u[h + 2] = c[_ + l],
                h += 3
            }
        return u
    }
    ,
    i._GetLuminanceArrayBuffer = function(e, t, r, n, o) {
        for (var a = new Uint8Array(n), s = new Uint8Array(o,r), l = 0, u = 0; u < t; u++)
            for (var c = 0; c < e; c++) {
                var h = c + u * e;
                a[l] = s[h],
                l++
            }
        return a
    }
    ,
    i.UploadDDSLevels = function(e, t, r, n, o, a, s, l, u) {
        s === void 0 && (s = -1),
        u === void 0 && (u = !0);
        var c = null;
        n.sphericalPolynomial && (c = new Array);
        var h = !!e.getCaps().s3tc;
        t.generateMipMaps = o;
        var f = new Int32Array(r.buffer,r.byteOffset,headerLengthInt), d, _, g, m = 0, v, y, b, T, C = 0, A = 1;
        if (f[off_magic] !== DDS_MAGIC) {
            Logger$2.Error("Invalid magic number in DDS header");
            return
        }
        if (!n.isFourCC && !n.isRGB && !n.isLuminance) {
            Logger$2.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
            return
        }
        if (n.isCompressed && !h) {
            Logger$2.Error("Compressed textures are not supported on this platform.");
            return
        }
        var S = f[off_RGBbpp];
        v = f[off_size] + 4;
        var P = !1;
        if (n.isFourCC)
            switch (d = f[off_pfFourCC],
            d) {
            case FOURCC_DXT1:
                A = 8,
                C = 33777;
                break;
            case FOURCC_DXT3:
                A = 16,
                C = 33778;
                break;
            case FOURCC_DXT5:
                A = 16,
                C = 33779;
                break;
            case FOURCC_D3DFMT_R16G16B16A16F:
                P = !0;
                break;
            case FOURCC_D3DFMT_R32G32B32A32F:
                P = !0;
                break;
            case FOURCC_DX10:
                v += 5 * 4;
                var R = !1;
                switch (n.dxgiFormat) {
                case DXGI_FORMAT_R16G16B16A16_FLOAT:
                case DXGI_FORMAT_R32G32B32A32_FLOAT:
                    P = !0,
                    R = !0;
                    break;
                case DXGI_FORMAT_B8G8R8X8_UNORM:
                    n.isRGB = !0,
                    n.isFourCC = !1,
                    S = 32,
                    R = !0;
                    break
                }
                if (R)
                    break;
            default:
                console.error("Unsupported FourCC code:", Int32ToFourCC(d));
                return
            }
        var M = i._ExtractLongWordOrder(f[off_RMask])
          , x = i._ExtractLongWordOrder(f[off_GMask])
          , I = i._ExtractLongWordOrder(f[off_BMask])
          , w = i._ExtractLongWordOrder(f[off_AMask]);
        P && (C = e._getRGBABufferInternalSizedFormat(n.textureType)),
        b = 1,
        f[off_flags] & DDSD_MIPMAPCOUNT && o !== !1 && (b = Math.max(1, f[off_mipmapCount]));
        for (var O = l || 0, D = e.getCaps(), F = O; F < a; F++) {
            for (_ = f[off_width],
            g = f[off_height],
            T = 0; T < b; ++T) {
                if (s === -1 || s === T) {
                    var V = s === -1 ? T : 0;
                    if (!n.isCompressed && n.isFourCC) {
                        t.format = 5,
                        m = _ * g * 4;
                        var N = null;
                        if (e._badOS || e._badDesktopOS || !D.textureHalfFloat && !D.textureFloat)
                            S === 128 ? (N = i._GetFloatAsUIntRGBAArrayBuffer(_, g, r.byteOffset + v, m, r.buffer, V),
                            c && V == 0 && c.push(i._GetFloatRGBAArrayBuffer(_, g, r.byteOffset + v, m, r.buffer, V))) : S === 64 && (N = i._GetHalfFloatAsUIntRGBAArrayBuffer(_, g, r.byteOffset + v, m, r.buffer, V),
                            c && V == 0 && c.push(i._GetHalfFloatAsFloatRGBAArrayBuffer(_, g, r.byteOffset + v, m, r.buffer, V))),
                            t.type = 0;
                        else {
                            var L = D.textureFloat && (u && D.textureFloatLinearFiltering || !u)
                              , k = D.textureHalfFloat && (u && D.textureHalfFloatLinearFiltering || !u)
                              , U = (S === 128 || S === 64 && !k) && L ? 1 : (S === 64 || S === 128 && !L) && k ? 2 : 0
                              , z = void 0
                              , H = null;
                            switch (S) {
                            case 128:
                                {
                                    switch (U) {
                                    case 1:
                                        z = i._GetFloatRGBAArrayBuffer,
                                        H = null;
                                        break;
                                    case 2:
                                        z = i._GetFloatAsHalfFloatRGBAArrayBuffer,
                                        H = i._GetFloatRGBAArrayBuffer;
                                        break;
                                    case 0:
                                        z = i._GetFloatAsUIntRGBAArrayBuffer,
                                        H = i._GetFloatRGBAArrayBuffer;
                                        break
                                    }
                                    break
                                }
                            default:
                                {
                                    switch (U) {
                                    case 1:
                                        z = i._GetHalfFloatAsFloatRGBAArrayBuffer,
                                        H = null;
                                        break;
                                    case 2:
                                        z = i._GetHalfFloatRGBAArrayBuffer,
                                        H = i._GetHalfFloatAsFloatRGBAArrayBuffer;
                                        break;
                                    case 0:
                                        z = i._GetHalfFloatAsUIntRGBAArrayBuffer,
                                        H = i._GetHalfFloatAsFloatRGBAArrayBuffer;
                                        break
                                    }
                                    break
                                }
                            }
                            t.type = U,
                            N = z(_, g, r.byteOffset + v, m, r.buffer, V),
                            c && V == 0 && c.push(H ? H(_, g, r.byteOffset + v, m, r.buffer, V) : N)
                        }
                        N && e._uploadDataToTextureDirectly(t, N, F, V)
                    } else if (n.isRGB)
                        t.type = 0,
                        S === 24 ? (t.format = 4,
                        m = _ * g * 3,
                        y = i._GetRGBArrayBuffer(_, g, r.byteOffset + v, m, r.buffer, M, x, I),
                        e._uploadDataToTextureDirectly(t, y, F, V)) : (t.format = 5,
                        m = _ * g * 4,
                        y = i._GetRGBAArrayBuffer(_, g, r.byteOffset + v, m, r.buffer, M, x, I, w),
                        e._uploadDataToTextureDirectly(t, y, F, V));
                    else if (n.isLuminance) {
                        var G = e._getUnpackAlignement()
                          , W = _
                          , j = Math.floor((_ + G - 1) / G) * G;
                        m = j * (g - 1) + W,
                        y = i._GetLuminanceArrayBuffer(_, g, r.byteOffset + v, m, r.buffer),
                        t.format = 1,
                        t.type = 0,
                        e._uploadDataToTextureDirectly(t, y, F, V)
                    } else
                        m = Math.max(4, _) / 4 * Math.max(4, g) / 4 * A,
                        y = new Uint8Array(r.buffer,r.byteOffset + v,m),
                        t.type = 0,
                        e._uploadCompressedDataToTextureDirectly(t, C, _, g, y, F, V)
                }
                v += S ? _ * g * (S / 8) : m,
                _ *= .5,
                g *= .5,
                _ = Math.max(1, _),
                g = Math.max(1, g)
            }
            if (l !== void 0)
                break
        }
        c && c.length > 0 ? n.sphericalPolynomial = CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
            size: f[off_width],
            right: c[0],
            left: c[1],
            up: c[2],
            down: c[3],
            front: c[4],
            back: c[5],
            format: 5,
            type: 1,
            gammaSpace: !1
        }) : n.sphericalPolynomial = void 0
    }
    ,
    i.StoreLODInAlphaChannel = !1,
    i
}();
ThinEngine.prototype.createPrefilteredCubeTexture = function(i, e, t, r, n, o, a, s, l) {
    var u = this;
    n === void 0 && (n = null),
    o === void 0 && (o = null),
    s === void 0 && (s = null),
    l === void 0 && (l = !0);
    var c = function(h) {
        if (!h) {
            n && n(null);
            return
        }
        var f = h.texture;
        if (l ? h.info.sphericalPolynomial && (f._sphericalPolynomial = h.info.sphericalPolynomial) : f._sphericalPolynomial = new SphericalPolynomial,
        f._source = InternalTextureSource.CubePrefiltered,
        u.getCaps().textureLOD) {
            n && n(f);
            return
        }
        var d = 3
          , _ = u._gl
          , g = h.width;
        if (!!g) {
            for (var m = [], v = 0; v < d; v++) {
                var y = v / (d - 1)
                  , b = 1 - y
                  , T = r
                  , C = Scalar.Log2(g) * t + r
                  , A = T + (C - T) * b
                  , S = Math.round(Math.min(Math.max(A, 0), C))
                  , P = new InternalTexture(u,InternalTextureSource.Temp);
                if (P.type = f.type,
                P.format = f.format,
                P.width = Math.pow(2, Math.max(Scalar.Log2(g) - S, 0)),
                P.height = P.width,
                P.isCube = !0,
                P._cachedWrapU = 0,
                P._cachedWrapV = 0,
                u._bindTextureDirectly(_.TEXTURE_CUBE_MAP, P, !0),
                P.samplingMode = 2,
                _.texParameteri(_.TEXTURE_CUBE_MAP, _.TEXTURE_MAG_FILTER, _.LINEAR),
                _.texParameteri(_.TEXTURE_CUBE_MAP, _.TEXTURE_MIN_FILTER, _.LINEAR),
                _.texParameteri(_.TEXTURE_CUBE_MAP, _.TEXTURE_WRAP_S, _.CLAMP_TO_EDGE),
                _.texParameteri(_.TEXTURE_CUBE_MAP, _.TEXTURE_WRAP_T, _.CLAMP_TO_EDGE),
                h.isDDS) {
                    var R = h.info
                      , M = h.data;
                    u._unpackFlipY(R.isCompressed),
                    DDSTools.UploadDDSLevels(u, P, M, R, !0, 6, S)
                } else
                    Logger$2.Warn("DDS is the only prefiltered cube map supported so far.");
                u._bindTextureDirectly(_.TEXTURE_CUBE_MAP, null);
                var x = new BaseTexture(e);
                x.isCube = !0,
                x._texture = P,
                P.isReady = !0,
                m.push(x)
            }
            f._lodTextureHigh = m[2],
            f._lodTextureMid = m[1],
            f._lodTextureLow = m[0],
            n && n(f)
        }
    };
    return this.createCubeTexture(i, e, null, !1, c, o, a, s, l, t, r)
}
;
var _DDSTextureLoader = function() {
    function i() {
        this.supportCascades = !0
    }
    return i.prototype.canLoad = function(e) {
        return EndsWith(e, ".dds")
    }
    ,
    i.prototype.loadCubeData = function(e, t, r, n, o) {
        var a = t.getEngine(), s, l = !1;
        if (Array.isArray(e))
            for (var u = 0; u < e.length; u++) {
                var c = e[u];
                s = DDSTools.GetDDSInfo(c),
                t.width = s.width,
                t.height = s.height,
                l = (s.isRGB || s.isLuminance || s.mipmapCount > 1) && t.generateMipMaps,
                a._unpackFlipY(s.isCompressed),
                DDSTools.UploadDDSLevels(a, t, c, s, l, 6, -1, u),
                !s.isFourCC && s.mipmapCount === 1 && a.generateMipMapsForCubemap(t)
            }
        else {
            var h = e;
            s = DDSTools.GetDDSInfo(h),
            t.width = s.width,
            t.height = s.height,
            r && (s.sphericalPolynomial = new SphericalPolynomial),
            l = (s.isRGB || s.isLuminance || s.mipmapCount > 1) && t.generateMipMaps,
            a._unpackFlipY(s.isCompressed),
            DDSTools.UploadDDSLevels(a, t, h, s, l, 6),
            !s.isFourCC && s.mipmapCount === 1 && a.generateMipMapsForCubemap(t, !1)
        }
        a._setCubeMapTextureParams(t, l),
        t.isReady = !0,
        t.onLoadedObservable.notifyObservers(t),
        t.onLoadedObservable.clear(),
        n && n({
            isDDS: !0,
            width: t.width,
            info: s,
            data: e,
            texture: t
        })
    }
    ,
    i.prototype.loadData = function(e, t, r) {
        var n = DDSTools.GetDDSInfo(e)
          , o = (n.isRGB || n.isLuminance || n.mipmapCount > 1) && t.generateMipMaps && n.width >> n.mipmapCount - 1 === 1;
        r(n.width, n.height, o, n.isFourCC, function() {
            DDSTools.UploadDDSLevels(t.getEngine(), t, e, n, o, 1)
        })
    }
    ,
    i
}();
Engine._TextureLoaders.push(new _DDSTextureLoader);
var MirrorTexture = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a, s, l) {
        a === void 0 && (a = 0),
        s === void 0 && (s = Texture.BILINEAR_SAMPLINGMODE),
        l === void 0 && (l = !0);
        var u = i.call(this, t, r, n, o, !0, a, !1, s, l) || this;
        u.scene = n,
        u.mirrorPlane = new Plane(0,1,0,1),
        u._transformMatrix = Matrix.Zero(),
        u._mirrorMatrix = Matrix.Zero(),
        u._adaptiveBlurKernel = 0,
        u._blurKernelX = 0,
        u._blurKernelY = 0,
        u._blurRatio = 1,
        u.ignoreCameraViewport = !0,
        u._updateGammaSpace(),
        u._imageProcessingConfigChangeObserver = n.imageProcessingConfiguration.onUpdateParameters.add(function() {
            u._updateGammaSpace()
        });
        var c = u.getScene().getEngine();
        c.supportsUniformBuffers && (u._sceneUBO = n.createSceneUniformBuffer('Scene for Mirror Texture (name "' + t + '")')),
        u.onBeforeBindObservable.add(function() {
            var f;
            (f = c._debugPushGroup) === null || f === void 0 || f.call(c, "mirror generation for " + t, 1)
        }),
        u.onAfterUnbindObservable.add(function() {
            var f;
            (f = c._debugPopGroup) === null || f === void 0 || f.call(c, 1)
        });
        var h;
        return u.onBeforeRenderObservable.add(function() {
            u._sceneUBO && (u._currentSceneUBO = n.getSceneUniformBuffer(),
            n.setSceneUniformBuffer(u._sceneUBO),
            n.getSceneUniformBuffer().unbindEffect()),
            Matrix.ReflectionToRef(u.mirrorPlane, u._mirrorMatrix),
            u._mirrorMatrix.multiplyToRef(n.getViewMatrix(), u._transformMatrix),
            n.setTransformMatrix(u._transformMatrix, n.getProjectionMatrix()),
            h = n.clipPlane,
            n.clipPlane = u.mirrorPlane,
            n.getEngine().cullBackFaces = !1,
            n._mirroredCameraPosition = Vector3.TransformCoordinates(n.activeCamera.globalPosition, u._mirrorMatrix)
        }),
        u.onAfterRenderObservable.add(function() {
            u._sceneUBO && n.setSceneUniformBuffer(u._currentSceneUBO),
            n.updateTransformMatrix(),
            n.getEngine().cullBackFaces = null,
            n._mirroredCameraPosition = null,
            n.clipPlane = h
        }),
        u
    }
    return Object.defineProperty(e.prototype, "blurRatio", {
        get: function() {
            return this._blurRatio
        },
        set: function(t) {
            this._blurRatio !== t && (this._blurRatio = t,
            this._preparePostProcesses())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "adaptiveBlurKernel", {
        set: function(t) {
            this._adaptiveBlurKernel = t,
            this._autoComputeBlurKernel()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "blurKernel", {
        set: function(t) {
            this.blurKernelX = t,
            this.blurKernelY = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "blurKernelX", {
        get: function() {
            return this._blurKernelX
        },
        set: function(t) {
            this._blurKernelX !== t && (this._blurKernelX = t,
            this._preparePostProcesses())
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "blurKernelY", {
        get: function() {
            return this._blurKernelY
        },
        set: function(t) {
            this._blurKernelY !== t && (this._blurKernelY = t,
            this._preparePostProcesses())
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._autoComputeBlurKernel = function() {
        var t = this.getScene().getEngine()
          , r = this.getRenderWidth() / t.getRenderWidth()
          , n = this.getRenderHeight() / t.getRenderHeight();
        this.blurKernelX = this._adaptiveBlurKernel * r,
        this.blurKernelY = this._adaptiveBlurKernel * n
    }
    ,
    e.prototype._onRatioRescale = function() {
        this._sizeRatio && (this.resize(this._initialSizeParameter),
        this._adaptiveBlurKernel || this._preparePostProcesses()),
        this._adaptiveBlurKernel && this._autoComputeBlurKernel()
    }
    ,
    e.prototype._updateGammaSpace = function() {
        this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess
    }
    ,
    e.prototype._preparePostProcesses = function() {
        if (this.clearPostProcesses(!0),
        this._blurKernelX && this._blurKernelY) {
            var t = this.getScene().getEngine()
              , r = t.getCaps().textureFloatRender && t.getCaps().textureFloatLinearFiltering ? 1 : 2;
            this._blurX = new BlurPostProcess("horizontal blur",new Vector2(1,0),this._blurKernelX,this._blurRatio,null,Texture.BILINEAR_SAMPLINGMODE,t,!1,r),
            this._blurX.autoClear = !1,
            this._blurRatio === 1 && this.samples < 2 && this._texture ? this._blurX.inputTexture = this._renderTarget : this._blurX.alwaysForcePOT = !0,
            this._blurY = new BlurPostProcess("vertical blur",new Vector2(0,1),this._blurKernelY,this._blurRatio,null,Texture.BILINEAR_SAMPLINGMODE,t,!1,r),
            this._blurY.autoClear = !1,
            this._blurY.alwaysForcePOT = this._blurRatio !== 1,
            this.addPostProcess(this._blurX),
            this.addPostProcess(this._blurY)
        } else
            this._blurY && (this.removePostProcess(this._blurY),
            this._blurY.dispose(),
            this._blurY = null),
            this._blurX && (this.removePostProcess(this._blurX),
            this._blurX.dispose(),
            this._blurX = null)
    }
    ,
    e.prototype.clone = function() {
        var t = this.getScene();
        if (!t)
            return this;
        var r = this.getSize()
          , n = new e(this.name,r.width,t,this._renderTargetOptions.generateMipMaps,this._renderTargetOptions.type,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer);
        return n.hasAlpha = this.hasAlpha,
        n.level = this.level,
        n.mirrorPlane = this.mirrorPlane.clone(),
        this.renderList && (n.renderList = this.renderList.slice(0)),
        n
    }
    ,
    e.prototype.serialize = function() {
        if (!this.name)
            return null;
        var t = i.prototype.serialize.call(this);
        return t.mirrorPlane = this.mirrorPlane.asArray(),
        t
    }
    ,
    e.prototype.dispose = function() {
        var t;
        i.prototype.dispose.call(this),
        this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver),
        (t = this._sceneUBO) === null || t === void 0 || t.dispose()
    }
    ,
    e
}(RenderTargetTexture);
Texture._CreateMirror = function(i, e, t, r) {
    return new MirrorTexture(i,e,t,r)
}
;
var name$o = "backgroundFragmentDeclaration"
  , shader$o = ` uniform vec4 vEyePosition;
uniform vec4 vPrimaryColor;
#ifdef USEHIGHLIGHTANDSHADOWCOLORS
uniform vec4 vPrimaryColorShadow;
#endif
uniform float shadowLevel;
uniform float alpha;
#ifdef DIFFUSE
uniform vec2 vDiffuseInfos;
#endif
#ifdef REFLECTION
uniform vec2 vReflectionInfos;
uniform mat4 reflectionMatrix;
uniform vec3 vReflectionMicrosurfaceInfos;
#endif
#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)
uniform vec3 vBackgroundCenter;
#endif
#ifdef REFLECTIONFRESNEL
uniform vec4 vReflectionControl;
#endif
#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)
uniform mat4 view;
#endif`;
ShaderStore.IncludesShadersStore[name$o] = shader$o;
var name$n = "backgroundUboDeclaration"
  , shader$n = `layout(std140,column_major) uniform;
uniform Material
{
uniform vec4 vPrimaryColor;
uniform vec4 vPrimaryColorShadow;
uniform vec2 vDiffuseInfos;
uniform vec2 vReflectionInfos;
uniform mat4 diffuseMatrix;
uniform mat4 reflectionMatrix;
uniform vec3 vReflectionMicrosurfaceInfos;
uniform float fFovMultiplier;
uniform float pointSize;
uniform float shadowLevel;
uniform float alpha;
#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)
uniform vec3 vBackgroundCenter;
#endif
#ifdef REFLECTIONFRESNEL
uniform vec4 vReflectionControl;
#endif
};
#include<sceneUboDeclaration>
`;
ShaderStore.IncludesShadersStore[name$n] = shader$n;
var name$m = "backgroundPixelShader"
  , shader$m = `#ifdef TEXTURELODSUPPORT
#extension GL_EXT_shader_texture_lod : enable
#endif
precision highp float;
#include<__decl__backgroundFragment>
#include<helperFunctions>
#define RECIPROCAL_PI2 0.15915494

varying vec3 vPositionW;
#ifdef MAINUV1
varying vec2 vMainUV1;
#endif
#ifdef MAINUV2
varying vec2 vMainUV2;
#endif
#ifdef NORMAL
varying vec3 vNormalW;
#endif
#ifdef DIFFUSE
#if DIFFUSEDIRECTUV == 1
#define vDiffuseUV vMainUV1
#elif DIFFUSEDIRECTUV == 2
#define vDiffuseUV vMainUV2
#else
varying vec2 vDiffuseUV;
#endif
uniform sampler2D diffuseSampler;
#endif

#ifdef REFLECTION
#ifdef REFLECTIONMAP_3D
#define sampleReflection(s,c) textureCube(s,c)
uniform samplerCube reflectionSampler;
#ifdef TEXTURELODSUPPORT
#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)
#else
uniform samplerCube reflectionSamplerLow;
uniform samplerCube reflectionSamplerHigh;
#endif
#else
#define sampleReflection(s,c) texture2D(s,c)
uniform sampler2D reflectionSampler;
#ifdef TEXTURELODSUPPORT
#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)
#else
uniform samplerCube reflectionSamplerLow;
uniform samplerCube reflectionSamplerHigh;
#endif
#endif
#ifdef REFLECTIONMAP_SKYBOX
varying vec3 vPositionUVW;
#else
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
varying vec3 vDirectionW;
#endif
#endif
#include<reflectionFunction>
#endif

#ifndef FROMLINEARSPACE
#define FROMLINEARSPACE;
#endif

#ifndef SHADOWONLY
#define SHADOWONLY;
#endif
#include<imageProcessingDeclaration>

#include<__decl__lightFragment>[0..maxSimultaneousLights]
#include<lightsFragmentFunctions>
#include<shadowsFragmentFunctions>
#include<imageProcessingFunctions>
#include<clipPlaneFragmentDeclaration>

#include<fogFragmentDeclaration>
#ifdef REFLECTIONFRESNEL
#define FRESNEL_MAXIMUM_ON_ROUGH 0.25
vec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)
{

float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);
return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));
}
#endif
void main(void) {
#include<clipPlaneFragment>
vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);

#ifdef NORMAL
vec3 normalW=normalize(vNormalW);
#else
vec3 normalW=vec3(0.0,1.0,0.0);
#endif

float shadow=1.;
float globalShadow=0.;
float shadowLightCount=0.;
#include<lightFragment>[0..maxSimultaneousLights]
#ifdef SHADOWINUSE
globalShadow/=shadowLightCount;
#else
globalShadow=1.0;
#endif
#ifndef BACKMAT_SHADOWONLY

vec4 reflectionColor=vec4(1.,1.,1.,1.);
#ifdef REFLECTION
vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);
#ifdef REFLECTIONMAP_OPPOSITEZ
reflectionVector.z*=-1.0;
#endif

#ifdef REFLECTIONMAP_3D
vec3 reflectionCoords=reflectionVector;
#else
vec2 reflectionCoords=reflectionVector.xy;
#ifdef REFLECTIONMAP_PROJECTION
reflectionCoords/=reflectionVector.z;
#endif
reflectionCoords.y=1.0-reflectionCoords.y;
#endif
#ifdef REFLECTIONBLUR
float reflectionLOD=vReflectionInfos.y;
#ifdef TEXTURELODSUPPORT

reflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;
reflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);
#else
float lodReflectionNormalized=saturate(reflectionLOD);
float lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;
vec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);
if(lodReflectionNormalizedDoubled<1.0){
reflectionColor=mix(
sampleReflection(reflectionSamplerHigh,reflectionCoords),
reflectionSpecularMid,
lodReflectionNormalizedDoubled
);
} else {
reflectionColor=mix(
reflectionSpecularMid,
sampleReflection(reflectionSamplerLow,reflectionCoords),
lodReflectionNormalizedDoubled-1.0
);
}
#endif
#else
vec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);
reflectionColor=reflectionSample;
#endif
#ifdef RGBDREFLECTION
reflectionColor.rgb=fromRGBD(reflectionColor);
#endif
#ifdef GAMMAREFLECTION
reflectionColor.rgb=toLinearSpace(reflectionColor.rgb);
#endif
#ifdef REFLECTIONBGR
reflectionColor.rgb=reflectionColor.bgr;
#endif

reflectionColor.rgb*=vReflectionInfos.x;
#endif

vec3 diffuseColor=vec3(1.,1.,1.);
float finalAlpha=alpha;
#ifdef DIFFUSE
vec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);
#ifdef GAMMADIFFUSE
diffuseMap.rgb=toLinearSpace(diffuseMap.rgb);
#endif

diffuseMap.rgb*=vDiffuseInfos.y;
#ifdef DIFFUSEHASALPHA
finalAlpha*=diffuseMap.a;
#endif
diffuseColor=diffuseMap.rgb;
#endif

#ifdef REFLECTIONFRESNEL
vec3 colorBase=diffuseColor;
#else
vec3 colorBase=reflectionColor.rgb*diffuseColor;
#endif
colorBase=max(colorBase,0.0);

#ifdef USERGBCOLOR
vec3 finalColor=colorBase;
#else
#ifdef USEHIGHLIGHTANDSHADOWCOLORS
vec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);
#else
vec3 mainColor=vPrimaryColor.rgb;
#endif
vec3 finalColor=colorBase*mainColor;
#endif

#ifdef REFLECTIONFRESNEL
vec3 reflectionAmount=vReflectionControl.xxx;
vec3 reflectionReflectance0=vReflectionControl.yyy;
vec3 reflectionReflectance90=vReflectionControl.zzz;
float VdotN=dot(normalize(vEyePosition.xyz),normalW);
vec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(saturate(VdotN),reflectionReflectance0,reflectionReflectance90,1.0);
reflectionAmount*=planarReflectionFresnel;
#ifdef REFLECTIONFALLOFF
float reflectionDistanceFalloff=1.0-saturate(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w);
reflectionDistanceFalloff*=reflectionDistanceFalloff;
reflectionAmount*=reflectionDistanceFalloff;
#endif
finalColor=mix(finalColor,reflectionColor.rgb,saturate(reflectionAmount));
#endif
#ifdef OPACITYFRESNEL
float viewAngleToFloor=dot(normalW,normalize(vEyePosition.xyz-vBackgroundCenter));

const float startAngle=0.1;
float fadeFactor=saturate(viewAngleToFloor/startAngle);
finalAlpha*=fadeFactor*fadeFactor;
#endif

#ifdef SHADOWINUSE
finalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);
#endif

vec4 color=vec4(finalColor,finalAlpha);
#else
vec4 color=vec4(vPrimaryColor.rgb,(1.0-clamp(globalShadow,0.,1.))*alpha);
#endif
#include<fogFragment>
#ifdef IMAGEPROCESSINGPOSTPROCESS


#if !defined(SKIPFINALCOLORCLAMP)
color.rgb=clamp(color.rgb,0.,30.0);
#endif
#else

color=applyImageProcessing(color);
#endif
#ifdef PREMULTIPLYALPHA

color.rgb*=color.a;
#endif
#ifdef NOISE
color.rgb+=dither(vPositionW.xy,0.5);
color=max(color,0.0);
#endif
gl_FragColor=color;
}
`;
ShaderStore.ShadersStore[name$m] = shader$m;
var name$l = "backgroundVertexDeclaration"
  , shader$l = `uniform mat4 view;
uniform mat4 viewProjection;
uniform float shadowLevel;
#ifdef DIFFUSE
uniform mat4 diffuseMatrix;
uniform vec2 vDiffuseInfos;
#endif
#ifdef REFLECTION
uniform vec2 vReflectionInfos;
uniform mat4 reflectionMatrix;
uniform vec3 vReflectionMicrosurfaceInfos;
uniform float fFovMultiplier;
#endif
#ifdef POINTSIZE
uniform float pointSize;
#endif`;
ShaderStore.IncludesShadersStore[name$l] = shader$l;
var name$k = "backgroundVertexShader"
  , shader$k = `precision highp float;
#include<__decl__backgroundVertex>
#include<helperFunctions>

attribute vec3 position;
#ifdef NORMAL
attribute vec3 normal;
#endif
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>

#include<instancesDeclaration>

varying vec3 vPositionW;
#ifdef NORMAL
varying vec3 vNormalW;
#endif
#ifdef UV1
attribute vec2 uv;
#endif
#ifdef UV2
attribute vec2 uv2;
#endif
#ifdef MAINUV1
varying vec2 vMainUV1;
#endif
#ifdef MAINUV2
varying vec2 vMainUV2;
#endif
#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0
varying vec2 vDiffuseUV;
#endif
#include<clipPlaneVertexDeclaration>
#include<fogVertexDeclaration>
#include<__decl__lightVxFragment>[0..maxSimultaneousLights]
#ifdef REFLECTIONMAP_SKYBOX
varying vec3 vPositionUVW;
#endif
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
varying vec3 vDirectionW;
#endif
void main(void) {
#ifdef REFLECTIONMAP_SKYBOX
vPositionUVW=position;
#endif
#include<instancesVertex>
#include<bonesVertex>
#include<bakedVertexAnimation>
#ifdef MULTIVIEW
if (gl_ViewID_OVR == 0u) {
gl_Position=viewProjection*finalWorld*vec4(position,1.0);
} else {
gl_Position=viewProjectionR*finalWorld*vec4(position,1.0);
}
#else
gl_Position=viewProjection*finalWorld*vec4(position,1.0);
#endif
vec4 worldPos=finalWorld*vec4(position,1.0);
vPositionW=vec3(worldPos);
#ifdef NORMAL
mat3 normalWorld=mat3(finalWorld);
#ifdef NONUNIFORMSCALING
normalWorld=transposeMat3(inverseMat3(normalWorld));
#endif
vNormalW=normalize(normalWorld*normal);
#endif
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
vDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));
#ifdef EQUIRECTANGULAR_RELFECTION_FOV
mat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));
vec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));
if (fFovMultiplier<=1.0) {
vDirectionW=normalize(segment);
} else {
vDirectionW=normalize(vDirectionW+(vDirectionW-segment));
}
#endif
#endif
#ifndef UV1
vec2 uv=vec2(0.,0.);
#endif
#ifndef UV2
vec2 uv2=vec2(0.,0.);
#endif
#ifdef MAINUV1
vMainUV1=uv;
#endif
#ifdef MAINUV2
vMainUV2=uv2;
#endif
#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0
if (vDiffuseInfos.x == 0.)
{
vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));
}
else
{
vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));
}
#endif

#include<clipPlaneVertex>

#include<fogVertex>

#include<shadowsVertex>[0..maxSimultaneousLights]

#ifdef VERTEXCOLOR
vColor=color;
#endif

#ifdef POINTSIZE
gl_PointSize=pointSize;
#endif
}
`;
ShaderStore.ShadersStore[name$k] = shader$k;
var BackgroundMaterialDefines = function(i) {
    __extends(e, i);
    function e() {
        var t = i.call(this) || this;
        return t.DIFFUSE = !1,
        t.DIFFUSEDIRECTUV = 0,
        t.GAMMADIFFUSE = !1,
        t.DIFFUSEHASALPHA = !1,
        t.OPACITYFRESNEL = !1,
        t.REFLECTIONBLUR = !1,
        t.REFLECTIONFRESNEL = !1,
        t.REFLECTIONFALLOFF = !1,
        t.TEXTURELODSUPPORT = !1,
        t.PREMULTIPLYALPHA = !1,
        t.USERGBCOLOR = !1,
        t.USEHIGHLIGHTANDSHADOWCOLORS = !1,
        t.BACKMAT_SHADOWONLY = !1,
        t.NOISE = !1,
        t.REFLECTIONBGR = !1,
        t.IMAGEPROCESSING = !1,
        t.VIGNETTE = !1,
        t.VIGNETTEBLENDMODEMULTIPLY = !1,
        t.VIGNETTEBLENDMODEOPAQUE = !1,
        t.TONEMAPPING = !1,
        t.TONEMAPPING_ACES = !1,
        t.CONTRAST = !1,
        t.COLORCURVES = !1,
        t.COLORGRADING = !1,
        t.COLORGRADING3D = !1,
        t.SAMPLER3DGREENDEPTH = !1,
        t.SAMPLER3DBGRMAP = !1,
        t.IMAGEPROCESSINGPOSTPROCESS = !1,
        t.SKIPFINALCOLORCLAMP = !1,
        t.EXPOSURE = !1,
        t.MULTIVIEW = !1,
        t.REFLECTION = !1,
        t.REFLECTIONMAP_3D = !1,
        t.REFLECTIONMAP_SPHERICAL = !1,
        t.REFLECTIONMAP_PLANAR = !1,
        t.REFLECTIONMAP_CUBIC = !1,
        t.REFLECTIONMAP_PROJECTION = !1,
        t.REFLECTIONMAP_SKYBOX = !1,
        t.REFLECTIONMAP_EXPLICIT = !1,
        t.REFLECTIONMAP_EQUIRECTANGULAR = !1,
        t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = !1,
        t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = !1,
        t.INVERTCUBICMAP = !1,
        t.REFLECTIONMAP_OPPOSITEZ = !1,
        t.LODINREFLECTIONALPHA = !1,
        t.GAMMAREFLECTION = !1,
        t.RGBDREFLECTION = !1,
        t.EQUIRECTANGULAR_RELFECTION_FOV = !1,
        t.MAINUV1 = !1,
        t.MAINUV2 = !1,
        t.UV1 = !1,
        t.UV2 = !1,
        t.CLIPPLANE = !1,
        t.CLIPPLANE2 = !1,
        t.CLIPPLANE3 = !1,
        t.CLIPPLANE4 = !1,
        t.CLIPPLANE5 = !1,
        t.CLIPPLANE6 = !1,
        t.POINTSIZE = !1,
        t.FOG = !1,
        t.NORMAL = !1,
        t.NUM_BONE_INFLUENCERS = 0,
        t.BonesPerMesh = 0,
        t.INSTANCES = !1,
        t.SHADOWFLOAT = !1,
        t.LOGARITHMICDEPTH = !1,
        t.NONUNIFORMSCALING = !1,
        t.ALPHATEST = !1,
        t.rebuild(),
        t
    }
    return e
}(MaterialDefines)
  , BackgroundMaterial = function(i) {
    __extends(e, i);
    function e(t, r) {
        var n = i.call(this, t, r) || this;
        return n.primaryColor = Color3.White(),
        n._primaryColorShadowLevel = 0,
        n._primaryColorHighlightLevel = 0,
        n.reflectionTexture = null,
        n.reflectionBlur = 0,
        n.diffuseTexture = null,
        n._shadowLights = null,
        n.shadowLights = null,
        n.shadowLevel = 0,
        n.sceneCenter = Vector3.Zero(),
        n.opacityFresnel = !0,
        n.reflectionFresnel = !1,
        n.reflectionFalloffDistance = 0,
        n.reflectionAmount = 1,
        n.reflectionReflectance0 = .05,
        n.reflectionReflectance90 = .5,
        n.useRGBColor = !0,
        n.enableNoise = !1,
        n._fovMultiplier = 1,
        n.useEquirectangularFOV = !1,
        n._maxSimultaneousLights = 4,
        n.maxSimultaneousLights = 4,
        n._shadowOnly = !1,
        n.shadowOnly = !1,
        n._imageProcessingObserver = null,
        n.switchToBGR = !1,
        n._renderTargets = new SmartArray(16),
        n._reflectionControls = Vector4.Zero(),
        n._white = Color3.White(),
        n._primaryShadowColor = Color3.Black(),
        n._primaryHighlightColor = Color3.Black(),
        n._attachImageProcessingConfiguration(null),
        n.getRenderTargetTextures = function() {
            return n._renderTargets.reset(),
            n._diffuseTexture && n._diffuseTexture.isRenderTarget && n._renderTargets.push(n._diffuseTexture),
            n._reflectionTexture && n._reflectionTexture.isRenderTarget && n._renderTargets.push(n._reflectionTexture),
            n._renderTargets
        }
        ,
        n
    }
    return Object.defineProperty(e.prototype, "_perceptualColor", {
        get: function() {
            return this.__perceptualColor
        },
        set: function(t) {
            this.__perceptualColor = t,
            this._computePrimaryColorFromPerceptualColor(),
            this._markAllSubMeshesAsLightsDirty()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "primaryColorShadowLevel", {
        get: function() {
            return this._primaryColorShadowLevel
        },
        set: function(t) {
            this._primaryColorShadowLevel = t,
            this._computePrimaryColors(),
            this._markAllSubMeshesAsLightsDirty()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "primaryColorHighlightLevel", {
        get: function() {
            return this._primaryColorHighlightLevel
        },
        set: function(t) {
            this._primaryColorHighlightLevel = t,
            this._computePrimaryColors(),
            this._markAllSubMeshesAsLightsDirty()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "reflectionStandardFresnelWeight", {
        set: function(t) {
            var r = t;
            r < .5 ? (r = r * 2,
            this.reflectionReflectance0 = e.StandardReflectance0 * r,
            this.reflectionReflectance90 = e.StandardReflectance90 * r) : (r = r * 2 - 1,
            this.reflectionReflectance0 = e.StandardReflectance0 + (1 - e.StandardReflectance0) * r,
            this.reflectionReflectance90 = e.StandardReflectance90 + (1 - e.StandardReflectance90) * r)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "fovMultiplier", {
        get: function() {
            return this._fovMultiplier
        },
        set: function(t) {
            isNaN(t) && (t = 1),
            this._fovMultiplier = Math.max(0, Math.min(2, t))
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._attachImageProcessingConfiguration = function(t) {
        var r = this;
        t !== this._imageProcessingConfiguration && (this._imageProcessingConfiguration && this._imageProcessingObserver && this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),
        t ? this._imageProcessingConfiguration = t : this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration,
        this._imageProcessingConfiguration && (this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function() {
            r._computePrimaryColorFromPerceptualColor(),
            r._markAllSubMeshesAsImageProcessingDirty()
        })))
    }
    ,
    Object.defineProperty(e.prototype, "imageProcessingConfiguration", {
        get: function() {
            return this._imageProcessingConfiguration
        },
        set: function(t) {
            this._attachImageProcessingConfiguration(t),
            this._markAllSubMeshesAsTexturesDirty()
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cameraColorCurvesEnabled", {
        get: function() {
            return this.imageProcessingConfiguration.colorCurvesEnabled
        },
        set: function(t) {
            this.imageProcessingConfiguration.colorCurvesEnabled = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cameraColorGradingEnabled", {
        get: function() {
            return this.imageProcessingConfiguration.colorGradingEnabled
        },
        set: function(t) {
            this.imageProcessingConfiguration.colorGradingEnabled = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cameraToneMappingEnabled", {
        get: function() {
            return this._imageProcessingConfiguration.toneMappingEnabled
        },
        set: function(t) {
            this._imageProcessingConfiguration.toneMappingEnabled = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cameraExposure", {
        get: function() {
            return this._imageProcessingConfiguration.exposure
        },
        set: function(t) {
            this._imageProcessingConfiguration.exposure = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cameraContrast", {
        get: function() {
            return this._imageProcessingConfiguration.contrast
        },
        set: function(t) {
            this._imageProcessingConfiguration.contrast = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cameraColorGradingTexture", {
        get: function() {
            return this._imageProcessingConfiguration.colorGradingTexture
        },
        set: function(t) {
            this.imageProcessingConfiguration.colorGradingTexture = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cameraColorCurves", {
        get: function() {
            return this.imageProcessingConfiguration.colorCurves
        },
        set: function(t) {
            this.imageProcessingConfiguration.colorCurves = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "hasRenderTargetTextures", {
        get: function() {
            return !!(this._diffuseTexture && this._diffuseTexture.isRenderTarget || this._reflectionTexture && this._reflectionTexture.isRenderTarget)
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.needAlphaTesting = function() {
        return !0
    }
    ,
    e.prototype.needAlphaBlending = function() {
        return this.alpha < 1 || this._diffuseTexture != null && this._diffuseTexture.hasAlpha || this._shadowOnly
    }
    ,
    e.prototype.isReadyForSubMesh = function(t, r, n) {
        if (n === void 0 && (n = !1),
        r.effect && this.isFrozen && r.effect._wasPreviouslyReady)
            return !0;
        r.materialDefines || (r.materialDefines = new BackgroundMaterialDefines);
        var o = this.getScene()
          , a = r.materialDefines;
        if (this._isReadyForSubMesh(r))
            return !0;
        var s = o.getEngine();
        if (MaterialHelper.PrepareDefinesForLights(o, t, a, !1, this._maxSimultaneousLights),
        a._needNormals = !0,
        MaterialHelper.PrepareDefinesForMultiview(o, a),
        a._areTexturesDirty) {
            if (a._needUVs = !1,
            o.texturesEnabled) {
                if (o.getEngine().getCaps().textureLOD && (a.TEXTURELODSUPPORT = !0),
                this._diffuseTexture && MaterialFlags.DiffuseTextureEnabled) {
                    if (!this._diffuseTexture.isReadyOrNotBlocking())
                        return !1;
                    MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, a, "DIFFUSE"),
                    a.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha,
                    a.GAMMADIFFUSE = this._diffuseTexture.gammaSpace,
                    a.OPACITYFRESNEL = this._opacityFresnel
                } else
                    a.DIFFUSE = !1,
                    a.DIFFUSEHASALPHA = !1,
                    a.GAMMADIFFUSE = !1,
                    a.OPACITYFRESNEL = !1;
                var l = this._reflectionTexture;
                if (l && MaterialFlags.ReflectionTextureEnabled) {
                    if (!l.isReadyOrNotBlocking())
                        return !1;
                    switch (a.REFLECTION = !0,
                    a.GAMMAREFLECTION = l.gammaSpace,
                    a.RGBDREFLECTION = l.isRGBD,
                    a.REFLECTIONBLUR = this._reflectionBlur > 0,
                    a.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !l.invertZ : l.invertZ,
                    a.LODINREFLECTIONALPHA = l.lodLevelInAlpha,
                    a.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV,
                    a.REFLECTIONBGR = this.switchToBGR,
                    l.coordinatesMode === Texture.INVCUBIC_MODE && (a.INVERTCUBICMAP = !0),
                    a.REFLECTIONMAP_3D = l.isCube,
                    l.coordinatesMode) {
                    case Texture.EXPLICIT_MODE:
                        a.REFLECTIONMAP_EXPLICIT = !0;
                        break;
                    case Texture.PLANAR_MODE:
                        a.REFLECTIONMAP_PLANAR = !0;
                        break;
                    case Texture.PROJECTION_MODE:
                        a.REFLECTIONMAP_PROJECTION = !0;
                        break;
                    case Texture.SKYBOX_MODE:
                        a.REFLECTIONMAP_SKYBOX = !0;
                        break;
                    case Texture.SPHERICAL_MODE:
                        a.REFLECTIONMAP_SPHERICAL = !0;
                        break;
                    case Texture.EQUIRECTANGULAR_MODE:
                        a.REFLECTIONMAP_EQUIRECTANGULAR = !0;
                        break;
                    case Texture.FIXED_EQUIRECTANGULAR_MODE:
                        a.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = !0;
                        break;
                    case Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
                        a.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = !0;
                        break;
                    case Texture.CUBIC_MODE:
                    case Texture.INVCUBIC_MODE:
                    default:
                        a.REFLECTIONMAP_CUBIC = !0;
                        break
                    }
                    this.reflectionFresnel ? (a.REFLECTIONFRESNEL = !0,
                    a.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) : (a.REFLECTIONFRESNEL = !1,
                    a.REFLECTIONFALLOFF = !1)
                } else
                    a.REFLECTION = !1,
                    a.REFLECTIONFRESNEL = !1,
                    a.REFLECTIONFALLOFF = !1,
                    a.REFLECTIONBLUR = !1,
                    a.REFLECTIONMAP_3D = !1,
                    a.REFLECTIONMAP_SPHERICAL = !1,
                    a.REFLECTIONMAP_PLANAR = !1,
                    a.REFLECTIONMAP_CUBIC = !1,
                    a.REFLECTIONMAP_PROJECTION = !1,
                    a.REFLECTIONMAP_SKYBOX = !1,
                    a.REFLECTIONMAP_EXPLICIT = !1,
                    a.REFLECTIONMAP_EQUIRECTANGULAR = !1,
                    a.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = !1,
                    a.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = !1,
                    a.INVERTCUBICMAP = !1,
                    a.REFLECTIONMAP_OPPOSITEZ = !1,
                    a.LODINREFLECTIONALPHA = !1,
                    a.GAMMAREFLECTION = !1,
                    a.RGBDREFLECTION = !1
            }
            a.PREMULTIPLYALPHA = this.alphaMode === 7 || this.alphaMode === 8,
            a.USERGBCOLOR = this._useRGBColor,
            a.NOISE = this._enableNoise
        }
        if (a._areLightsDirty && (a.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0),
        a.BACKMAT_SHADOWONLY = this._shadowOnly),
        a._areImageProcessingDirty && this._imageProcessingConfiguration) {
            if (!this._imageProcessingConfiguration.isReady())
                return !1;
            this._imageProcessingConfiguration.prepareDefines(a)
        }
        if (MaterialHelper.PrepareDefinesForMisc(t, o, !1, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(t), a),
        MaterialHelper.PrepareDefinesForFrameBoundValues(o, s, a, n, null, r.getRenderingMesh().hasThinInstances),
        MaterialHelper.PrepareDefinesForAttributes(t, a, !1, !0, !1) && t && !o.getEngine().getCaps().standardDerivatives && !t.isVerticesDataPresent(VertexBuffer.NormalKind) && (t.createNormals(!0),
        Logger$2.Warn("BackgroundMaterial: Normals have been created for the mesh: " + t.name)),
        a.isDirty) {
            a.markAsProcessed(),
            o.resetCachedMaterial();
            var u = new EffectFallbacks;
            a.FOG && u.addFallback(0, "FOG"),
            a.POINTSIZE && u.addFallback(1, "POINTSIZE"),
            a.MULTIVIEW && u.addFallback(0, "MULTIVIEW"),
            MaterialHelper.HandleFallbacksForShadows(a, u, this._maxSimultaneousLights);
            var c = [VertexBuffer.PositionKind];
            a.NORMAL && c.push(VertexBuffer.NormalKind),
            a.UV1 && c.push(VertexBuffer.UVKind),
            a.UV2 && c.push(VertexBuffer.UV2Kind),
            MaterialHelper.PrepareAttributesForBones(c, t, a, u),
            MaterialHelper.PrepareAttributesForInstances(c, a);
            var h = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vFogInfos", "vFogColor", "pointSize", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "vClipPlane5", "vClipPlane6", "mBones", "vPrimaryColor", "vPrimaryColorShadow", "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier", "shadowLevel", "alpha", "vBackgroundCenter", "vReflectionControl", "vDiffuseInfos", "diffuseMatrix"]
              , f = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"]
              , d = ["Material", "Scene"];
            ImageProcessingConfiguration && (ImageProcessingConfiguration.PrepareUniforms(h, a),
            ImageProcessingConfiguration.PrepareSamplers(f, a)),
            MaterialHelper.PrepareUniformsAndSamplersList({
                uniformsNames: h,
                uniformBuffersNames: d,
                samplers: f,
                defines: a,
                maxSimultaneousLights: this._maxSimultaneousLights
            });
            var _ = a.toString()
              , g = o.getEngine().createEffect("background", {
                attributes: c,
                uniformsNames: h,
                uniformBuffersNames: d,
                samplers: f,
                defines: _,
                fallbacks: u,
                onCompiled: this.onCompiled,
                onError: this.onError,
                indexParameters: {
                    maxSimultaneousLights: this._maxSimultaneousLights
                }
            }, s);
            r.setEffect(g, a, this._materialContext),
            this.buildUniformLayout()
        }
        return !r.effect || !r.effect.isReady() ? !1 : (a._renderId = o.getRenderId(),
        r.effect._wasPreviouslyReady = !0,
        !0)
    }
    ,
    e.prototype._computePrimaryColorFromPerceptualColor = function() {
        !this.__perceptualColor || (this._primaryColor.copyFrom(this.__perceptualColor),
        this._primaryColor.toLinearSpaceToRef(this._primaryColor),
        this._imageProcessingConfiguration && this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor),
        this._computePrimaryColors())
    }
    ,
    e.prototype._computePrimaryColors = function() {
        this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0 || (this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor),
        this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor),
        this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor),
        this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor),
        this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor))
    }
    ,
    e.prototype.buildUniformLayout = function() {
        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()
    }
    ,
    e.prototype.unbind = function() {
        this._diffuseTexture && this._diffuseTexture.isRenderTarget && this._uniformBuffer.setTexture("diffuseSampler", null),
        this._reflectionTexture && this._reflectionTexture.isRenderTarget && this._uniformBuffer.setTexture("reflectionSampler", null),
        i.prototype.unbind.call(this)
    }
    ,
    e.prototype.bindOnlyWorldMatrix = function(t) {
        this._activeEffect.setMatrix("world", t)
    }
    ,
    e.prototype.bindForSubMesh = function(t, r, n) {
        var o = this.getScene()
          , a = n.materialDefines;
        if (!!a) {
            var s = n.effect;
            if (!!s) {
                this._activeEffect = s,
                this.bindOnlyWorldMatrix(t),
                MaterialHelper.BindBonesParameters(r, this._activeEffect);
                var l = this._mustRebind(o, s, r.visibility);
                if (l) {
                    this._uniformBuffer.bindToEffect(s, "Material"),
                    this.bindViewProjection(s);
                    var u = this._reflectionTexture;
                    (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) && (o.texturesEnabled && (this._diffuseTexture && MaterialFlags.DiffuseTextureEnabled && (this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level),
                    MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse")),
                    u && MaterialFlags.ReflectionTextureEnabled && (this._uniformBuffer.updateMatrix("reflectionMatrix", u.getReflectionTextureMatrix()),
                    this._uniformBuffer.updateFloat2("vReflectionInfos", u.level, this._reflectionBlur),
                    this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", u.getSize().width, u.lodGenerationScale, u.lodGenerationOffset))),
                    this.shadowLevel > 0 && this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel),
                    this._uniformBuffer.updateFloat("alpha", this.alpha),
                    this.pointsCloud && this._uniformBuffer.updateFloat("pointSize", this.pointSize),
                    a.USEHIGHLIGHTANDSHADOWCOLORS ? (this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1),
                    this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1)) : this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1)),
                    this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier),
                    o.texturesEnabled && (this._diffuseTexture && MaterialFlags.DiffuseTextureEnabled && this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture),
                    u && MaterialFlags.ReflectionTextureEnabled && (a.REFLECTIONBLUR && a.TEXTURELODSUPPORT ? this._uniformBuffer.setTexture("reflectionSampler", u) : a.REFLECTIONBLUR ? (this._uniformBuffer.setTexture("reflectionSampler", u._lodTextureMid || u),
                    this._uniformBuffer.setTexture("reflectionSamplerLow", u._lodTextureLow || u),
                    this._uniformBuffer.setTexture("reflectionSamplerHigh", u._lodTextureHigh || u)) : this._uniformBuffer.setTexture("reflectionSampler", u),
                    a.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)))),
                    MaterialHelper.BindClipPlane(this._activeEffect, o),
                    o.bindEyePosition(s)
                } else
                    o.getEngine()._features.needToAlwaysBindUniformBuffers && (this._uniformBuffer.bindToEffect(s, "Material"),
                    this._needToBindSceneUbo = !0);
                (l || !this.isFrozen) && (o.lightsEnabled && MaterialHelper.BindLights(o, r, this._activeEffect, a, this._maxSimultaneousLights),
                this.bindView(s),
                MaterialHelper.BindFogParameters(o, r, this._activeEffect, !0),
                this._imageProcessingConfiguration && this._imageProcessingConfiguration.bind(this._activeEffect)),
                this._afterBind(r, this._activeEffect),
                this._uniformBuffer.update()
            }
        }
    }
    ,
    e.prototype.hasTexture = function(t) {
        return !!(i.prototype.hasTexture.call(this, t) || this._reflectionTexture === t || this._diffuseTexture === t)
    }
    ,
    e.prototype.dispose = function(t, r) {
        t === void 0 && (t = !1),
        r === void 0 && (r = !1),
        r && (this.diffuseTexture && this.diffuseTexture.dispose(),
        this.reflectionTexture && this.reflectionTexture.dispose()),
        this._renderTargets.dispose(),
        this._imageProcessingConfiguration && this._imageProcessingObserver && this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),
        i.prototype.dispose.call(this, t)
    }
    ,
    e.prototype.clone = function(t) {
        var r = this;
        return SerializationHelper.Clone(function() {
            return new e(t,r.getScene())
        }, this)
    }
    ,
    e.prototype.serialize = function() {
        var t = SerializationHelper.Serialize(this);
        return t.customType = "BABYLON.BackgroundMaterial",
        t
    }
    ,
    e.prototype.getClassName = function() {
        return "BackgroundMaterial"
    }
    ,
    e.Parse = function(t, r, n) {
        return SerializationHelper.Parse(function() {
            return new e(t.name,r)
        }, t, r, n)
    }
    ,
    e.StandardReflectance0 = .05,
    e.StandardReflectance90 = .5,
    __decorate([serializeAsColor3()], e.prototype, "_primaryColor", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsLightsDirty")], e.prototype, "primaryColor", void 0),
    __decorate([serializeAsColor3()], e.prototype, "__perceptualColor", void 0),
    __decorate([serialize()], e.prototype, "_primaryColorShadowLevel", void 0),
    __decorate([serialize()], e.prototype, "_primaryColorHighlightLevel", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsLightsDirty")], e.prototype, "primaryColorHighlightLevel", null),
    __decorate([serializeAsTexture()], e.prototype, "_reflectionTexture", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "reflectionTexture", void 0),
    __decorate([serialize()], e.prototype, "_reflectionBlur", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "reflectionBlur", void 0),
    __decorate([serializeAsTexture()], e.prototype, "_diffuseTexture", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "diffuseTexture", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "shadowLights", void 0),
    __decorate([serialize()], e.prototype, "_shadowLevel", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "shadowLevel", void 0),
    __decorate([serializeAsVector3()], e.prototype, "_sceneCenter", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "sceneCenter", void 0),
    __decorate([serialize()], e.prototype, "_opacityFresnel", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "opacityFresnel", void 0),
    __decorate([serialize()], e.prototype, "_reflectionFresnel", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "reflectionFresnel", void 0),
    __decorate([serialize()], e.prototype, "_reflectionFalloffDistance", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "reflectionFalloffDistance", void 0),
    __decorate([serialize()], e.prototype, "_reflectionAmount", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "reflectionAmount", void 0),
    __decorate([serialize()], e.prototype, "_reflectionReflectance0", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "reflectionReflectance0", void 0),
    __decorate([serialize()], e.prototype, "_reflectionReflectance90", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "reflectionReflectance90", void 0),
    __decorate([serialize()], e.prototype, "_useRGBColor", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "useRGBColor", void 0),
    __decorate([serialize()], e.prototype, "_enableNoise", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "enableNoise", void 0),
    __decorate([serialize()], e.prototype, "_maxSimultaneousLights", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")], e.prototype, "maxSimultaneousLights", void 0),
    __decorate([serialize()], e.prototype, "_shadowOnly", void 0),
    __decorate([expandToProperty("_markAllSubMeshesAsLightsDirty")], e.prototype, "shadowOnly", void 0),
    __decorate([serializeAsImageProcessingConfiguration()], e.prototype, "_imageProcessingConfiguration", void 0),
    e
}(PushMaterial);
RegisterClass("BABYLON.BackgroundMaterial", BackgroundMaterial);
var EnvironmentHelper = function() {
    function i(e, t) {
        var r = this;
        this._errorHandler = function(n, o) {
            r.onErrorObservable.notifyObservers({
                message: n,
                exception: o
            })
        }
        ,
        this._options = __assign(__assign({}, i._getDefaultOptions()), e),
        this._scene = t,
        this.onErrorObservable = new Observable,
        this._setupBackground(),
        this._setupImageProcessing()
    }
    return i._getDefaultOptions = function() {
        return {
            createGround: !0,
            groundSize: 15,
            groundTexture: this._groundTextureCDNUrl,
            groundColor: new Color3(.2,.2,.3).toLinearSpace().scale(3),
            groundOpacity: .9,
            enableGroundShadow: !0,
            groundShadowLevel: .5,
            enableGroundMirror: !1,
            groundMirrorSizeRatio: .3,
            groundMirrorBlurKernel: 64,
            groundMirrorAmount: 1,
            groundMirrorFresnelWeight: 1,
            groundMirrorFallOffDistance: 0,
            groundMirrorTextureType: 0,
            groundYBias: 1e-5,
            createSkybox: !0,
            skyboxSize: 20,
            skyboxTexture: this._skyboxTextureCDNUrl,
            skyboxColor: new Color3(.2,.2,.3).toLinearSpace().scale(3),
            backgroundYRotation: 0,
            sizeAuto: !0,
            rootPosition: Vector3.Zero(),
            setupImageProcessing: !0,
            environmentTexture: this._environmentTextureCDNUrl,
            cameraExposure: .8,
            cameraContrast: 1.2,
            toneMappingEnabled: !0
        }
    }
    ,
    Object.defineProperty(i.prototype, "rootMesh", {
        get: function() {
            return this._rootMesh
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "skybox", {
        get: function() {
            return this._skybox
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "skyboxTexture", {
        get: function() {
            return this._skyboxTexture
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "skyboxMaterial", {
        get: function() {
            return this._skyboxMaterial
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "ground", {
        get: function() {
            return this._ground
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "groundTexture", {
        get: function() {
            return this._groundTexture
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "groundMirror", {
        get: function() {
            return this._groundMirror
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "groundMirrorRenderList", {
        get: function() {
            return this._groundMirror ? this._groundMirror.renderList : null
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "groundMaterial", {
        get: function() {
            return this._groundMaterial
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.updateOptions = function(e) {
        var t = __assign(__assign({}, this._options), e);
        this._ground && !t.createGround && (this._ground.dispose(),
        this._ground = null),
        this._groundMaterial && !t.createGround && (this._groundMaterial.dispose(),
        this._groundMaterial = null),
        this._groundTexture && this._options.groundTexture != t.groundTexture && (this._groundTexture.dispose(),
        this._groundTexture = null),
        this._skybox && !t.createSkybox && (this._skybox.dispose(),
        this._skybox = null),
        this._skyboxMaterial && !t.createSkybox && (this._skyboxMaterial.dispose(),
        this._skyboxMaterial = null),
        this._skyboxTexture && this._options.skyboxTexture != t.skyboxTexture && (this._skyboxTexture.dispose(),
        this._skyboxTexture = null),
        this._groundMirror && !t.enableGroundMirror && (this._groundMirror.dispose(),
        this._groundMirror = null),
        this._scene.environmentTexture && this._options.environmentTexture != t.environmentTexture && this._scene.environmentTexture.dispose(),
        this._options = t,
        this._setupBackground(),
        this._setupImageProcessing()
    }
    ,
    i.prototype.setMainColor = function(e) {
        this.groundMaterial && (this.groundMaterial.primaryColor = e),
        this.skyboxMaterial && (this.skyboxMaterial.primaryColor = e),
        this.groundMirror && (this.groundMirror.clearColor = new Color4(e.r,e.g,e.b,1))
    }
    ,
    i.prototype._setupImageProcessing = function() {
        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())
    }
    ,
    i.prototype._setupEnvironmentTexture = function() {
        if (!this._scene.environmentTexture) {
            if (this._options.environmentTexture instanceof BaseTexture) {
                this._scene.environmentTexture = this._options.environmentTexture;
                return
            }
            var e = CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
            this._scene.environmentTexture = e
        }
    }
    ,
    i.prototype._setupBackground = function() {
        this._rootMesh || (this._rootMesh = new Mesh("BackgroundHelper",this._scene)),
        this._rootMesh.rotation.y = this._options.backgroundYRotation;
        var e = this._getSceneSize();
        this._options.createGround && (this._setupGround(e),
        this._setupGroundMaterial(),
        this._setupGroundDiffuseTexture(),
        this._options.enableGroundMirror && this._setupGroundMirrorTexture(e),
        this._setupMirrorInGroundMaterial()),
        this._options.createSkybox && (this._setupSkybox(e),
        this._setupSkyboxMaterial(),
        this._setupSkyboxReflectionTexture()),
        this._rootMesh.position.x = e.rootPosition.x,
        this._rootMesh.position.z = e.rootPosition.z,
        this._rootMesh.position.y = e.rootPosition.y
    }
    ,
    i.prototype._getSceneSize = function() {
        var e = this
          , t = this._options.groundSize
          , r = this._options.skyboxSize
          , n = this._options.rootPosition;
        if (!this._scene.meshes || this._scene.meshes.length === 1)
            return {
                groundSize: t,
                skyboxSize: r,
                rootPosition: n
            };
        var o = this._scene.getWorldExtends(function(l) {
            return l !== e._ground && l !== e._rootMesh && l !== e._skybox
        })
          , a = o.max.subtract(o.min);
        if (this._options.sizeAuto) {
            this._scene.activeCamera instanceof ArcRotateCamera && this._scene.activeCamera.upperRadiusLimit && (t = this._scene.activeCamera.upperRadiusLimit * 2,
            r = t);
            var s = a.length();
            s > t && (t = s * 2,
            r = t),
            t *= 1.1,
            r *= 1.5,
            n = o.min.add(a.scale(.5)),
            n.y = o.min.y - this._options.groundYBias
        }
        return {
            groundSize: t,
            skyboxSize: r,
            rootPosition: n
        }
    }
    ,
    i.prototype._setupGround = function(e) {
        var t = this;
        (!this._ground || this._ground.isDisposed()) && (this._ground = CreatePlane("BackgroundPlane", {
            size: e.groundSize
        }, this._scene),
        this._ground.rotation.x = Math.PI / 2,
        this._ground.parent = this._rootMesh,
        this._ground.onDisposeObservable.add(function() {
            t._ground = null
        })),
        this._ground.receiveShadows = this._options.enableGroundShadow
    }
    ,
    i.prototype._setupGroundMaterial = function() {
        this._groundMaterial || (this._groundMaterial = new BackgroundMaterial("BackgroundPlaneMaterial",this._scene)),
        this._groundMaterial.alpha = this._options.groundOpacity,
        this._groundMaterial.alphaMode = 8,
        this._groundMaterial.shadowLevel = this._options.groundShadowLevel,
        this._groundMaterial.primaryColor = this._options.groundColor,
        this._groundMaterial.useRGBColor = !1,
        this._groundMaterial.enableNoise = !0,
        this._ground && (this._ground.material = this._groundMaterial)
    }
    ,
    i.prototype._setupGroundDiffuseTexture = function() {
        if (!!this._groundMaterial && !this._groundTexture) {
            if (this._options.groundTexture instanceof BaseTexture) {
                this._groundMaterial.diffuseTexture = this._options.groundTexture;
                return
            }
            this._groundTexture = new Texture(this._options.groundTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),
            this._groundTexture.gammaSpace = !1,
            this._groundTexture.hasAlpha = !0,
            this._groundMaterial.diffuseTexture = this._groundTexture
        }
    }
    ,
    i.prototype._setupGroundMirrorTexture = function(e) {
        var t = Texture.CLAMP_ADDRESSMODE;
        if (!this._groundMirror && (this._groundMirror = new MirrorTexture("BackgroundPlaneMirrorTexture",{
            ratio: this._options.groundMirrorSizeRatio
        },this._scene,!1,this._options.groundMirrorTextureType,Texture.BILINEAR_SAMPLINGMODE,!0),
        this._groundMirror.mirrorPlane = new Plane(0,-1,0,e.rootPosition.y),
        this._groundMirror.anisotropicFilteringLevel = 1,
        this._groundMirror.wrapU = t,
        this._groundMirror.wrapV = t,
        this._groundMirror.gammaSpace = !1,
        this._groundMirror.renderList))
            for (var r = 0; r < this._scene.meshes.length; r++) {
                var n = this._scene.meshes[r];
                n !== this._ground && n !== this._skybox && n !== this._rootMesh && this._groundMirror.renderList.push(n)
            }
        this._groundMirror.clearColor = new Color4(this._options.groundColor.r,this._options.groundColor.g,this._options.groundColor.b,1),
        this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel
    }
    ,
    i.prototype._setupMirrorInGroundMaterial = function() {
        this._groundMaterial && (this._groundMaterial.reflectionTexture = this._groundMirror,
        this._groundMaterial.reflectionFresnel = !0,
        this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount,
        this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight,
        this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance)
    }
    ,
    i.prototype._setupSkybox = function(e) {
        var t = this;
        (!this._skybox || this._skybox.isDisposed()) && (this._skybox = CreateBox("BackgroundSkybox", {
            size: e.skyboxSize,
            sideOrientation: Mesh.BACKSIDE
        }, this._scene),
        this._skybox.onDisposeObservable.add(function() {
            t._skybox = null
        })),
        this._skybox.parent = this._rootMesh
    }
    ,
    i.prototype._setupSkyboxMaterial = function() {
        !this._skybox || (this._skyboxMaterial || (this._skyboxMaterial = new BackgroundMaterial("BackgroundSkyboxMaterial",this._scene)),
        this._skyboxMaterial.useRGBColor = !1,
        this._skyboxMaterial.primaryColor = this._options.skyboxColor,
        this._skyboxMaterial.enableNoise = !0,
        this._skybox.material = this._skyboxMaterial)
    }
    ,
    i.prototype._setupSkyboxReflectionTexture = function() {
        if (!!this._skyboxMaterial && !this._skyboxTexture) {
            if (this._options.skyboxTexture instanceof BaseTexture) {
                this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
                return
            }
            this._skyboxTexture = new CubeTexture(this._options.skyboxTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),
            this._skyboxTexture.coordinatesMode = Texture.SKYBOX_MODE,
            this._skyboxTexture.gammaSpace = !1,
            this._skyboxMaterial.reflectionTexture = this._skyboxTexture
        }
    }
    ,
    i.prototype.dispose = function() {
        this._groundMaterial && this._groundMaterial.dispose(!0, !0),
        this._skyboxMaterial && this._skyboxMaterial.dispose(!0, !0),
        this._rootMesh.dispose(!1)
    }
    ,
    i._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png",
    i._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds",
    i._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env",
    i
}();
FreeCameraInputsManager.prototype.addDeviceOrientation = function() {
    return this._deviceOrientationInput || (this._deviceOrientationInput = new FreeCameraDeviceOrientationInput,
    this.add(this._deviceOrientationInput)),
    this
}
;
var FreeCameraDeviceOrientationInput = function() {
    function i() {
        var e = this;
        this._screenOrientationAngle = 0,
        this._screenQuaternion = new Quaternion,
        this._alpha = 0,
        this._beta = 0,
        this._gamma = 0,
        this._onDeviceOrientationChangedObservable = new Observable,
        this._orientationChanged = function() {
            e._screenOrientationAngle = window.orientation !== void 0 ? +window.orientation : window.screen.orientation && window.screen.orientation.angle ? window.screen.orientation.angle : 0,
            e._screenOrientationAngle = -Tools.ToRadians(e._screenOrientationAngle / 2),
            e._screenQuaternion.copyFromFloats(0, Math.sin(e._screenOrientationAngle), 0, Math.cos(e._screenOrientationAngle))
        }
        ,
        this._deviceOrientation = function(t) {
            e._alpha = t.alpha !== null ? t.alpha : 0,
            e._beta = t.beta !== null ? t.beta : 0,
            e._gamma = t.gamma !== null ? t.gamma : 0,
            t.alpha !== null && e._onDeviceOrientationChangedObservable.notifyObservers()
        }
        ,
        this._constantTranform = new Quaternion(-Math.sqrt(.5),0,0,Math.sqrt(.5)),
        this._orientationChanged()
    }
    return i.WaitForOrientationChangeAsync = function(e) {
        return new Promise(function(t, r) {
            var n = !1
              , o = function() {
                window.removeEventListener("deviceorientation", o),
                n = !0,
                t()
            };
            e && setTimeout(function() {
                n || (window.removeEventListener("deviceorientation", o),
                r("WaitForOrientationChangeAsync timed out"))
            }, e),
            typeof DeviceOrientationEvent != "undefined" && typeof DeviceOrientationEvent.requestPermission == "function" ? DeviceOrientationEvent.requestPermission().then(function(a) {
                a == "granted" ? window.addEventListener("deviceorientation", o) : Tools.Warn("Permission not granted.")
            }).catch(function(a) {
                Tools.Error(a)
            }) : window.addEventListener("deviceorientation", o)
        }
        )
    }
    ,
    Object.defineProperty(i.prototype, "camera", {
        get: function() {
            return this._camera
        },
        set: function(e) {
            var t = this;
            this._camera = e,
            this._camera != null && !this._camera.rotationQuaternion && (this._camera.rotationQuaternion = new Quaternion),
            this._camera && this._camera.onDisposeObservable.add(function() {
                t._onDeviceOrientationChangedObservable.clear()
            })
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.attachControl = function() {
        var e = this
          , t = this.camera.getScene().getEngine().getHostWindow();
        if (t) {
            var r = function() {
                t.addEventListener("orientationchange", e._orientationChanged),
                t.addEventListener("deviceorientation", e._deviceOrientation),
                e._orientationChanged()
            };
            typeof DeviceOrientationEvent != "undefined" && typeof DeviceOrientationEvent.requestPermission == "function" ? DeviceOrientationEvent.requestPermission().then(function(n) {
                n === "granted" ? r() : Tools.Warn("Permission not granted.")
            }).catch(function(n) {
                Tools.Error(n)
            }) : r()
        }
    }
    ,
    i.prototype.detachControl = function(e) {
        window.removeEventListener("orientationchange", this._orientationChanged),
        window.removeEventListener("deviceorientation", this._deviceOrientation),
        this._alpha = 0
    }
    ,
    i.prototype.checkInputs = function() {
        !this._alpha || (Quaternion.RotationYawPitchRollToRef(Tools.ToRadians(this._alpha), Tools.ToRadians(this._beta), -Tools.ToRadians(this._gamma), this.camera.rotationQuaternion),
        this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion),
        this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform),
        this._camera.rotationQuaternion.z *= -1,
        this._camera.rotationQuaternion.w *= -1)
    }
    ,
    i.prototype.getClassName = function() {
        return "FreeCameraDeviceOrientationInput"
    }
    ,
    i.prototype.getSimpleName = function() {
        return "deviceOrientation"
    }
    ,
    i
}();
CameraInputTypes.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
Node$2.AddNodeConstructor("DeviceOrientationCamera", function(i, e) {
    return function() {
        return new DeviceOrientationCamera(i,Vector3.Zero(),e)
    }
});
var DeviceOrientationCamera = function(i) {
    __extends(e, i);
    function e(t, r, n) {
        var o = i.call(this, t, r, n) || this;
        return o._tmpDragQuaternion = new Quaternion,
        o._disablePointerInputWhenUsingDeviceOrientation = !0,
        o._dragFactor = 0,
        o._quaternionCache = new Quaternion,
        o.inputs.addDeviceOrientation(),
        o.inputs._deviceOrientationInput && o.inputs._deviceOrientationInput._onDeviceOrientationChangedObservable.addOnce(function() {
            o._disablePointerInputWhenUsingDeviceOrientation && o.inputs._mouseInput && (o.inputs._mouseInput._allowCameraRotation = !1,
            o.inputs._mouseInput.onPointerMovedObservable.add(function(a) {
                o._dragFactor != 0 && (o._initialQuaternion || (o._initialQuaternion = new Quaternion),
                Quaternion.FromEulerAnglesToRef(0, a.offsetX * o._dragFactor, 0, o._tmpDragQuaternion),
                o._initialQuaternion.multiplyToRef(o._tmpDragQuaternion, o._initialQuaternion))
            }))
        }),
        o
    }
    return Object.defineProperty(e.prototype, "disablePointerInputWhenUsingDeviceOrientation", {
        get: function() {
            return this._disablePointerInputWhenUsingDeviceOrientation
        },
        set: function(t) {
            this._disablePointerInputWhenUsingDeviceOrientation = t
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.enableHorizontalDragging = function(t) {
        t === void 0 && (t = 1 / 300),
        this._dragFactor = t
    }
    ,
    e.prototype.getClassName = function() {
        return "DeviceOrientationCamera"
    }
    ,
    e.prototype._checkInputs = function() {
        i.prototype._checkInputs.call(this),
        this._quaternionCache.copyFrom(this.rotationQuaternion),
        this._initialQuaternion && this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion)
    }
    ,
    e.prototype.resetToCurrentRotation = function(t) {
        var r = this;
        t === void 0 && (t = Axis.Y),
        this.rotationQuaternion && (this._initialQuaternion || (this._initialQuaternion = new Quaternion),
        this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion),
        ["x", "y", "z"].forEach(function(n) {
            t[n] ? r._initialQuaternion[n] *= -1 : r._initialQuaternion[n] = 0
        }),
        this._initialQuaternion.normalize(),
        this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion))
    }
    ,
    e
}(FreeCamera)
  , VRCameraMetrics = function() {
    function i() {
        this.compensateDistortion = !0,
        this.multiviewEnabled = !1
    }
    return Object.defineProperty(i.prototype, "aspectRatio", {
        get: function() {
            return this.hResolution / (2 * this.vResolution)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "aspectRatioFov", {
        get: function() {
            return 2 * Math.atan(this.postProcessScaleFactor * this.vScreenSize / (2 * this.eyeToScreenDistance))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "leftHMatrix", {
        get: function() {
            var e = this.hScreenSize / 4 - this.lensSeparationDistance / 2
              , t = 4 * e / this.hScreenSize;
            return Matrix.Translation(t, 0, 0)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "rightHMatrix", {
        get: function() {
            var e = this.hScreenSize / 4 - this.lensSeparationDistance / 2
              , t = 4 * e / this.hScreenSize;
            return Matrix.Translation(-t, 0, 0)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "leftPreViewMatrix", {
        get: function() {
            return Matrix.Translation(.5 * this.interpupillaryDistance, 0, 0)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "rightPreViewMatrix", {
        get: function() {
            return Matrix.Translation(-.5 * this.interpupillaryDistance, 0, 0)
        },
        enumerable: !1,
        configurable: !0
    }),
    i.GetDefault = function() {
        var e = new i;
        return e.hResolution = 1280,
        e.vResolution = 800,
        e.hScreenSize = .149759993,
        e.vScreenSize = .0935999975,
        e.vScreenCenter = .0467999987,
        e.eyeToScreenDistance = .0410000011,
        e.lensSeparationDistance = .063500002,
        e.interpupillaryDistance = .064000003,
        e.distortionK = [1, .219999999, .239999995, 0],
        e.chromaAbCorrection = [.995999992, -.00400000019, 1.01400006, 0],
        e.postProcessScaleFactor = 1.714605507808412,
        e.lensCenterOffset = .151976421,
        e
    }
    ,
    i
}()
  , name$j = "vrDistortionCorrectionPixelShader"
  , shader$j = `
varying vec2 vUV;
uniform sampler2D textureSampler;
uniform vec2 LensCenter;
uniform vec2 Scale;
uniform vec2 ScaleIn;
uniform vec4 HmdWarpParam;
vec2 HmdWarp(vec2 in01) {
vec2 theta=(in01-LensCenter)*ScaleIn;
float rSq=theta.x*theta.x+theta.y*theta.y;
vec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);
return LensCenter+Scale*rvector;
}
void main(void)
{
vec2 tc=HmdWarp(vUV);
if (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)
gl_FragColor=vec4(0.0,0.0,0.0,0.0);
else{
gl_FragColor=texture2D(textureSampler,tc);
}
}`;
ShaderStore.ShadersStore[name$j] = shader$j;
var VRDistortionCorrectionPostProcess = function(i) {
    __extends(e, i);
    function e(t, r, n, o) {
        var a = i.call(this, t, "vrDistortionCorrection", ["LensCenter", "Scale", "ScaleIn", "HmdWarpParam"], null, o.postProcessScaleFactor, r, Texture.BILINEAR_SAMPLINGMODE) || this;
        return a._isRightEye = n,
        a._distortionFactors = o.distortionK,
        a._postProcessScaleFactor = o.postProcessScaleFactor,
        a._lensCenterOffset = o.lensCenterOffset,
        a.adaptScaleToCurrentViewport = !0,
        a.onSizeChangedObservable.add(function() {
            a._scaleIn = new Vector2(2,2 / a.aspectRatio),
            a._scaleFactor = new Vector2(.5 * (1 / a._postProcessScaleFactor),.5 * (1 / a._postProcessScaleFactor) * a.aspectRatio),
            a._lensCenter = new Vector2(a._isRightEye ? .5 - a._lensCenterOffset * .5 : .5 + a._lensCenterOffset * .5,.5)
        }),
        a.onApplyObservable.add(function(s) {
            s.setFloat2("LensCenter", a._lensCenter.x, a._lensCenter.y),
            s.setFloat2("Scale", a._scaleFactor.x, a._scaleFactor.y),
            s.setFloat2("ScaleIn", a._scaleIn.x, a._scaleIn.y),
            s.setFloat4("HmdWarpParam", a._distortionFactors[0], a._distortionFactors[1], a._distortionFactors[2], a._distortionFactors[3])
        }),
        a
    }
    return e.prototype.getClassName = function() {
        return "VRDistortionCorrectionPostProcess"
    }
    ,
    e
}(PostProcess)
  , name$i = "vrMultiviewToSingleviewPixelShader"
  , shader$i = `precision mediump sampler2DArray;
varying vec2 vUV;
uniform sampler2DArray multiviewSampler;
uniform int imageIndex;
void main(void)
{
gl_FragColor=texture2D(multiviewSampler,vec3(vUV,imageIndex));
}`;
ShaderStore.ShadersStore[name$i] = shader$i;
var MultiviewRenderTarget = function(i) {
    __extends(e, i);
    function e(t, r) {
        r === void 0 && (r = 512);
        var n = i.call(this, "multiview rtt", r, t, !1, !0, 0, !1, void 0, !1, !1, !0, void 0, !0) || this
          , o = t.getEngine().createMultiviewRenderTargetTexture(n.getRenderWidth(), n.getRenderHeight());
        return n._texture = o.texture,
        n._texture.isMultiview = !0,
        n._texture.format = 5,
        n.samples = n._getEngine().getCaps().maxSamples || n.samples,
        n
    }
    return e.prototype._bindFrameBuffer = function(t) {
        !this._renderTarget || this.getScene().getEngine().bindMultiviewFramebuffer(this._renderTarget)
    }
    ,
    e.prototype.getViewCount = function() {
        return 2
    }
    ,
    e
}(RenderTargetTexture);
Engine.prototype.createMultiviewRenderTargetTexture = function(i, e) {
    var t = this._gl;
    if (!this.getCaps().multiview)
        throw "Multiview is not supported";
    var r = this._createHardwareRenderTargetWrapper(!1, !1, {
        width: i,
        height: e
    });
    r._framebuffer = t.createFramebuffer();
    var n = new InternalTexture(this,InternalTextureSource.Unknown,!0);
    return n.width = i,
    n.height = e,
    r._colorTextureArray = t.createTexture(),
    t.bindTexture(t.TEXTURE_2D_ARRAY, r._colorTextureArray),
    t.texStorage3D(t.TEXTURE_2D_ARRAY, 1, t.RGBA8, i, e, 2),
    r._depthStencilTextureArray = t.createTexture(),
    t.bindTexture(t.TEXTURE_2D_ARRAY, r._depthStencilTextureArray),
    t.texStorage3D(t.TEXTURE_2D_ARRAY, 1, t.DEPTH32F_STENCIL8, i, e, 2),
    n.isReady = !0,
    r.setTextures(n),
    r
}
;
Engine.prototype.bindMultiviewFramebuffer = function(i) {
    var e = i
      , t = this._gl
      , r = this.getCaps().oculusMultiview || this.getCaps().multiview;
    if (this.bindFramebuffer(e, void 0, void 0, void 0, !0),
    t.bindFramebuffer(t.DRAW_FRAMEBUFFER, e._framebuffer),
    e._colorTextureArray && e._depthStencilTextureArray)
        this.getCaps().oculusMultiview ? (r.framebufferTextureMultisampleMultiviewOVR(t.DRAW_FRAMEBUFFER, t.COLOR_ATTACHMENT0, e._colorTextureArray, 0, e.samples, 0, 2),
        r.framebufferTextureMultisampleMultiviewOVR(t.DRAW_FRAMEBUFFER, t.DEPTH_STENCIL_ATTACHMENT, e._depthStencilTextureArray, 0, e.samples, 0, 2)) : (r.framebufferTextureMultiviewOVR(t.DRAW_FRAMEBUFFER, t.COLOR_ATTACHMENT0, e._colorTextureArray, 0, 0, 2),
        r.framebufferTextureMultiviewOVR(t.DRAW_FRAMEBUFFER, t.DEPTH_STENCIL_ATTACHMENT, e._depthStencilTextureArray, 0, 0, 2));
    else
        throw "Invalid multiview frame buffer"
}
;
Camera$1.prototype._useMultiviewToSingleView = !1;
Camera$1.prototype._multiviewTexture = null;
Camera$1.prototype._resizeOrCreateMultiviewTexture = function(i, e) {
    this._multiviewTexture ? (this._multiviewTexture.getRenderWidth() != i || this._multiviewTexture.getRenderHeight() != e) && (this._multiviewTexture.dispose(),
    this._multiviewTexture = new MultiviewRenderTarget(this.getScene(),{
        width: i,
        height: e
    })) : this._multiviewTexture = new MultiviewRenderTarget(this.getScene(),{
        width: i,
        height: e
    })
}
;
function createMultiviewUbo(i, e) {
    var t = new UniformBuffer(i,void 0,!0,e);
    return t.addUniform("viewProjection", 16),
    t.addUniform("viewProjectionR", 16),
    t.addUniform("view", 16),
    t.addUniform("projection", 16),
    t.addUniform("viewPosition", 4),
    t
}
var currentCreateSceneUniformBuffer = Scene.prototype.createSceneUniformBuffer;
Scene.prototype._transformMatrixR = Matrix.Zero();
Scene.prototype._multiviewSceneUbo = null;
Scene.prototype._createMultiviewUbo = function() {
    this._multiviewSceneUbo = createMultiviewUbo(this.getEngine(), "scene_multiview")
}
;
Scene.prototype.createSceneUniformBuffer = function(i) {
    return this._multiviewSceneUbo ? createMultiviewUbo(this.getEngine(), i) : currentCreateSceneUniformBuffer.bind(this)(i)
}
;
Scene.prototype._updateMultiviewUbo = function(i, e) {
    i && e && i.multiplyToRef(e, this._transformMatrixR),
    i && e && (i.multiplyToRef(e, TmpVectors.Matrix[0]),
    Frustum.GetRightPlaneToRef(TmpVectors.Matrix[0], this._frustumPlanes[3])),
    this._multiviewSceneUbo && (this._multiviewSceneUbo.updateMatrix("viewProjection", this.getTransformMatrix()),
    this._multiviewSceneUbo.updateMatrix("viewProjectionR", this._transformMatrixR),
    this._multiviewSceneUbo.updateMatrix("view", this._viewMatrix),
    this._multiviewSceneUbo.updateMatrix("projection", this._projectionMatrix))
}
;
Scene.prototype._renderMultiviewToSingleView = function(i) {
    i._resizeOrCreateMultiviewTexture(i._rigPostProcess && i._rigPostProcess && i._rigPostProcess.width > 0 ? i._rigPostProcess.width : this.getEngine().getRenderWidth(!0), i._rigPostProcess && i._rigPostProcess && i._rigPostProcess.height > 0 ? i._rigPostProcess.height : this.getEngine().getRenderHeight(!0)),
    this._multiviewSceneUbo || this._createMultiviewUbo(),
    i.outputRenderTarget = i._multiviewTexture,
    this._renderForCamera(i),
    i.outputRenderTarget = null;
    for (var e = 0; e < i._rigCameras.length; e++) {
        var t = this.getEngine();
        this._activeCamera = i._rigCameras[e],
        t.setViewport(this._activeCamera.viewport),
        this.postProcessManager && (this.postProcessManager._prepareFrame(),
        this.postProcessManager._finalizeFrame(this._activeCamera.isIntermediate))
    }
}
;
var VRMultiviewToSingleviewPostProcess = function(i) {
    __extends(e, i);
    function e(t, r, n) {
        var o = i.call(this, t, "vrMultiviewToSingleview", ["imageIndex"], ["multiviewSampler"], n, r, Texture.BILINEAR_SAMPLINGMODE) || this;
        return o.onSizeChangedObservable.add(function() {}),
        o.onApplyObservable.add(function(a) {
            r._scene.activeCamera && r._scene.activeCamera.isLeftCamera ? a.setInt("imageIndex", 0) : a.setInt("imageIndex", 1),
            a.setTexture("multiviewSampler", r._multiviewTexture)
        }),
        o
    }
    return e.prototype.getClassName = function() {
        return "VRMultiviewToSingleviewPostProcess"
    }
    ,
    e
}(PostProcess);
function setVRRigMode(i, e) {
    var t = e.vrCameraMetrics || VRCameraMetrics.GetDefault();
    i._rigCameras[0]._cameraRigParams.vrMetrics = t,
    i._rigCameras[0].viewport = new Viewport(0,0,.5,1),
    i._rigCameras[0]._cameraRigParams.vrWorkMatrix = new Matrix,
    i._rigCameras[0]._cameraRigParams.vrHMatrix = t.leftHMatrix,
    i._rigCameras[0]._cameraRigParams.vrPreViewMatrix = t.leftPreViewMatrix,
    i._rigCameras[0].getProjectionMatrix = i._rigCameras[0]._getVRProjectionMatrix,
    i._rigCameras[1]._cameraRigParams.vrMetrics = t,
    i._rigCameras[1].viewport = new Viewport(.5,0,.5,1),
    i._rigCameras[1]._cameraRigParams.vrWorkMatrix = new Matrix,
    i._rigCameras[1]._cameraRigParams.vrHMatrix = t.rightHMatrix,
    i._rigCameras[1]._cameraRigParams.vrPreViewMatrix = t.rightPreViewMatrix,
    i._rigCameras[1].getProjectionMatrix = i._rigCameras[1]._getVRProjectionMatrix,
    t.multiviewEnabled && (i.getScene().getEngine().getCaps().multiview ? (i._useMultiviewToSingleView = !0,
    i._rigPostProcess = new VRMultiviewToSingleviewPostProcess("VRMultiviewToSingleview",i,t.postProcessScaleFactor)) : (Logger$2.Warn("Multiview is not supported, falling back to standard rendering"),
    t.multiviewEnabled = !1)),
    t.compensateDistortion && (i._rigCameras[0]._rigPostProcess = new VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left",i._rigCameras[0],!1,t),
    i._rigCameras[1]._rigPostProcess = new VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right",i._rigCameras[1],!0,t))
}
Node$2.AddNodeConstructor("VRDeviceOrientationFreeCamera", function(i, e) {
    return function() {
        return new VRDeviceOrientationFreeCamera(i,Vector3.Zero(),e)
    }
});
var VRDeviceOrientationFreeCamera = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a) {
        o === void 0 && (o = !0),
        a === void 0 && (a = VRCameraMetrics.GetDefault());
        var s = i.call(this, t, r, n) || this;
        return s._setRigMode = setVRRigMode.bind(null, s),
        a.compensateDistortion = o,
        s.setCameraRigMode(Camera$1.RIG_MODE_VR, {
            vrCameraMetrics: a
        }),
        s
    }
    return e.prototype.getClassName = function() {
        return "VRDeviceOrientationFreeCamera"
    }
    ,
    e
}(DeviceOrientationCamera), Gamepad = function() {
    function i(e, t, r, n, o, a, s) {
        n === void 0 && (n = 0),
        o === void 0 && (o = 1),
        a === void 0 && (a = 2),
        s === void 0 && (s = 3),
        this.id = e,
        this.index = t,
        this.browserGamepad = r,
        this._leftStick = {
            x: 0,
            y: 0
        },
        this._rightStick = {
            x: 0,
            y: 0
        },
        this._isConnected = !0,
        this._invertLeftStickY = !1,
        this.type = i.GAMEPAD,
        this._leftStickAxisX = n,
        this._leftStickAxisY = o,
        this._rightStickAxisX = a,
        this._rightStickAxisY = s,
        this.browserGamepad.axes.length >= 2 && (this._leftStick = {
            x: this.browserGamepad.axes[this._leftStickAxisX],
            y: this.browserGamepad.axes[this._leftStickAxisY]
        }),
        this.browserGamepad.axes.length >= 4 && (this._rightStick = {
            x: this.browserGamepad.axes[this._rightStickAxisX],
            y: this.browserGamepad.axes[this._rightStickAxisY]
        })
    }
    return Object.defineProperty(i.prototype, "isConnected", {
        get: function() {
            return this._isConnected
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.onleftstickchanged = function(e) {
        this._onleftstickchanged = e
    }
    ,
    i.prototype.onrightstickchanged = function(e) {
        this._onrightstickchanged = e
    }
    ,
    Object.defineProperty(i.prototype, "leftStick", {
        get: function() {
            return this._leftStick
        },
        set: function(e) {
            this._onleftstickchanged && (this._leftStick.x !== e.x || this._leftStick.y !== e.y) && this._onleftstickchanged(e),
            this._leftStick = e
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "rightStick", {
        get: function() {
            return this._rightStick
        },
        set: function(e) {
            this._onrightstickchanged && (this._rightStick.x !== e.x || this._rightStick.y !== e.y) && this._onrightstickchanged(e),
            this._rightStick = e
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.update = function() {
        this._leftStick && (this.leftStick = {
            x: this.browserGamepad.axes[this._leftStickAxisX],
            y: this.browserGamepad.axes[this._leftStickAxisY]
        },
        this._invertLeftStickY && (this.leftStick.y *= -1)),
        this._rightStick && (this.rightStick = {
            x: this.browserGamepad.axes[this._rightStickAxisX],
            y: this.browserGamepad.axes[this._rightStickAxisY]
        })
    }
    ,
    i.prototype.dispose = function() {}
    ,
    i.GAMEPAD = 0,
    i.GENERIC = 1,
    i.XBOX = 2,
    i.POSE_ENABLED = 3,
    i.DUALSHOCK = 4,
    i
}(), GenericPad = function(i) {
    __extends(e, i);
    function e(t, r, n) {
        var o = i.call(this, t, r, n) || this;
        return o.onButtonDownObservable = new Observable,
        o.onButtonUpObservable = new Observable,
        o.type = Gamepad.GENERIC,
        o._buttons = new Array(n.buttons.length),
        o
    }
    return e.prototype.onbuttondown = function(t) {
        this._onbuttondown = t
    }
    ,
    e.prototype.onbuttonup = function(t) {
        this._onbuttonup = t
    }
    ,
    e.prototype._setButtonValue = function(t, r, n) {
        return t !== r && (t === 1 && (this._onbuttondown && this._onbuttondown(n),
        this.onButtonDownObservable.notifyObservers(n)),
        t === 0 && (this._onbuttonup && this._onbuttonup(n),
        this.onButtonUpObservable.notifyObservers(n))),
        t
    }
    ,
    e.prototype.update = function() {
        i.prototype.update.call(this);
        for (var t = 0; t < this._buttons.length; t++)
            this._buttons[t] = this._setButtonValue(this.browserGamepad.buttons[t].value, this._buttons[t], t)
    }
    ,
    e.prototype.dispose = function() {
        i.prototype.dispose.call(this),
        this.onButtonDownObservable.clear(),
        this.onButtonUpObservable.clear()
    }
    ,
    e
}(Gamepad), PoseEnabledControllerType;
(function(i) {
    i[i.VIVE = 0] = "VIVE",
    i[i.OCULUS = 1] = "OCULUS",
    i[i.WINDOWS = 2] = "WINDOWS",
    i[i.GEAR_VR = 3] = "GEAR_VR",
    i[i.DAYDREAM = 4] = "DAYDREAM",
    i[i.GENERIC = 5] = "GENERIC"
}
)(PoseEnabledControllerType || (PoseEnabledControllerType = {}));
var PoseEnabledControllerHelper = function() {
    function i() {}
    return i.InitiateController = function(e) {
        for (var t = 0, r = this._ControllerFactories; t < r.length; t++) {
            var n = r[t];
            if (n.canCreate(e))
                return n.create(e)
        }
        if (this._DefaultControllerFactory)
            return this._DefaultControllerFactory(e);
        throw "The type of gamepad you are trying to load needs to be imported first or is not supported."
    }
    ,
    i._ControllerFactories = [],
    i._DefaultControllerFactory = null,
    i
}()
  , PoseEnabledController = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t.id, t.index, t) || this;
        return r.isXR = !1,
        r._deviceRoomPosition = Vector3.Zero(),
        r._deviceRoomRotationQuaternion = new Quaternion,
        r.devicePosition = Vector3.Zero(),
        r.deviceRotationQuaternion = new Quaternion,
        r.deviceScaleFactor = 1,
        r._trackPosition = !0,
        r._maxRotationDistFromHeadset = Math.PI / 5,
        r._draggedRoomRotation = 0,
        r._leftHandSystemQuaternion = new Quaternion,
        r._deviceToWorld = Matrix.Identity(),
        r._pointingPoseNode = null,
        r._workingMatrix = Matrix.Identity(),
        r._meshAttachedObservable = new Observable,
        r.type = Gamepad.POSE_ENABLED,
        r.controllerType = PoseEnabledControllerType.GENERIC,
        r.position = Vector3.Zero(),
        r.rotationQuaternion = new Quaternion,
        r._calculatedPosition = Vector3.Zero(),
        r._calculatedRotation = new Quaternion,
        Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, r._leftHandSystemQuaternion),
        r
    }
    return e.prototype._disableTrackPosition = function(t) {
        this._trackPosition && (this._calculatedPosition.copyFrom(t),
        this._trackPosition = !1)
    }
    ,
    e.prototype.update = function() {
        i.prototype.update.call(this),
        this._updatePoseAndMesh()
    }
    ,
    e.prototype._updatePoseAndMesh = function() {
        if (!this.isXR) {
            var t = this.browserGamepad.pose;
            if (this.updateFromDevice(t),
            !this._trackPosition && EngineStore.LastCreatedScene && EngineStore.LastCreatedScene.activeCamera && EngineStore.LastCreatedScene.activeCamera.devicePosition) {
                var r = EngineStore.LastCreatedScene.activeCamera;
                if (r._computeDevicePosition(),
                this._deviceToWorld.setTranslation(r.devicePosition),
                r.deviceRotationQuaternion) {
                    var r = r;
                    r._deviceRoomRotationQuaternion.toEulerAnglesToRef(TmpVectors.Vector3[0]);
                    var n = Math.atan2(Math.sin(TmpVectors.Vector3[0].y - this._draggedRoomRotation), Math.cos(TmpVectors.Vector3[0].y - this._draggedRoomRotation));
                    if (Math.abs(n) > this._maxRotationDistFromHeadset) {
                        var o = n - (n < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
                        this._draggedRoomRotation += o;
                        var a = Math.sin(-o)
                          , s = Math.cos(-o);
                        this._calculatedPosition.x = this._calculatedPosition.x * s - this._calculatedPosition.z * a,
                        this._calculatedPosition.z = this._calculatedPosition.x * a + this._calculatedPosition.z * s
                    }
                }
            }
            Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition),
            this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix),
            Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion),
            this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation),
            this._mesh && (this._mesh.position.copyFrom(this.devicePosition),
            this._mesh.rotationQuaternion && this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion))
        }
    }
    ,
    e.prototype.updateFromDevice = function(t) {
        if (!this.isXR && t) {
            this.rawPose = t,
            t.position && (this._deviceRoomPosition.copyFromFloats(t.position[0], t.position[1], -t.position[2]),
            this._mesh && this._mesh.getScene().useRightHandedSystem && (this._deviceRoomPosition.z *= -1),
            this._trackPosition && this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition),
            this._calculatedPosition.addInPlace(this.position));
            var r = this.rawPose;
            t.orientation && r.orientation && r.orientation.length === 4 && (this._deviceRoomRotationQuaternion.copyFromFloats(r.orientation[0], r.orientation[1], -r.orientation[2], -r.orientation[3]),
            this._mesh && (this._mesh.getScene().useRightHandedSystem ? (this._deviceRoomRotationQuaternion.z *= -1,
            this._deviceRoomRotationQuaternion.w *= -1) : this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion)),
            this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation))
        }
    }
    ,
    e.prototype.attachToMesh = function(t) {
        if (this._mesh && (this._mesh.parent = null),
        this._mesh = t,
        this._poseControlledCamera && (this._mesh.parent = this._poseControlledCamera),
        this._mesh.rotationQuaternion || (this._mesh.rotationQuaternion = new Quaternion),
        !this.isXR && (this._updatePoseAndMesh(),
        this._pointingPoseNode)) {
            for (var r = [], n = this._pointingPoseNode; n.parent; )
                r.push(n.parent),
                n = n.parent;
            r.reverse().forEach(function(o) {
                o.computeWorldMatrix(!0)
            })
        }
        this._meshAttachedObservable.notifyObservers(t)
    }
    ,
    e.prototype.attachToPoseControlledCamera = function(t) {
        this._poseControlledCamera = t,
        this._mesh && (this._mesh.parent = this._poseControlledCamera)
    }
    ,
    e.prototype.dispose = function() {
        this._mesh && this._mesh.dispose(),
        this._mesh = null,
        i.prototype.dispose.call(this)
    }
    ,
    Object.defineProperty(e.prototype, "mesh", {
        get: function() {
            return this._mesh
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getForwardRay = function(t) {
        if (t === void 0 && (t = 100),
        !this.mesh)
            return new Ray(Vector3.Zero(),new Vector3(0,0,1),t);
        var r = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix()
          , n = r.getTranslation()
          , o = new Vector3(0,0,-1)
          , a = Vector3.TransformNormal(o, r)
          , s = Vector3.Normalize(a);
        return new Ray(n,s,t)
    }
    ,
    e.POINTING_POSE = "POINTING_POSE",
    e
}(Gamepad);
function setWebVRRigMode(i, e) {
    if (e.vrDisplay) {
        var t = e.vrDisplay.getEyeParameters("left")
          , r = e.vrDisplay.getEyeParameters("right");
        i._rigCameras[0].viewport = new Viewport(0,0,.5,1),
        i._rigCameras[0].setCameraRigParameter("left", !0),
        i._rigCameras[0].setCameraRigParameter("specs", e.specs),
        i._rigCameras[0].setCameraRigParameter("eyeParameters", t),
        i._rigCameras[0].setCameraRigParameter("frameData", e.frameData),
        i._rigCameras[0].setCameraRigParameter("parentCamera", e.parentCamera),
        i._rigCameras[0]._cameraRigParams.vrWorkMatrix = new Matrix,
        i._rigCameras[0].getProjectionMatrix = i._getWebVRProjectionMatrix,
        i._rigCameras[0].parent = i,
        i._rigCameras[0]._getViewMatrix = i._getWebVRViewMatrix,
        i._rigCameras[1].viewport = new Viewport(.5,0,.5,1),
        i._rigCameras[1].setCameraRigParameter("eyeParameters", r),
        i._rigCameras[1].setCameraRigParameter("specs", e.specs),
        i._rigCameras[1].setCameraRigParameter("frameData", e.frameData),
        i._rigCameras[1].setCameraRigParameter("parentCamera", e.parentCamera),
        i._rigCameras[1]._cameraRigParams.vrWorkMatrix = new Matrix,
        i._rigCameras[1].getProjectionMatrix = i._getWebVRProjectionMatrix,
        i._rigCameras[1].parent = i,
        i._rigCameras[1]._getViewMatrix = i._getWebVRViewMatrix
    }
}
Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
    get: function() {
        return this._vrExclusivePointerMode
    },
    enumerable: !0,
    configurable: !0
});
Engine.prototype._prepareVRComponent = function() {
    this._vrSupported = !1,
    this._vrExclusivePointerMode = !1,
    this.onVRDisplayChangedObservable = new Observable,
    this.onVRRequestPresentComplete = new Observable,
    this.onVRRequestPresentStart = new Observable
}
;
Engine.prototype.isVRDevicePresent = function() {
    return !!this._vrDisplay
}
;
Engine.prototype.getVRDevice = function() {
    return this._vrDisplay
}
;
Engine.prototype.initWebVR = function() {
    return this.initWebVRAsync(),
    this.onVRDisplayChangedObservable
}
;
Engine.prototype.initWebVRAsync = function() {
    var i = this
      , e = function() {
        var r = {
            vrDisplay: i._vrDisplay,
            vrSupported: i._vrSupported
        };
        i.onVRDisplayChangedObservable.notifyObservers(r),
        i._webVRInitPromise = new Promise(function(n) {
            n(r)
        }
        )
    };
    if (!this._onVrDisplayConnect) {
        this._onVrDisplayConnect = function(r) {
            i._vrDisplay = r.display,
            e()
        }
        ,
        this._onVrDisplayDisconnect = function() {
            i._vrDisplay.cancelAnimationFrame(i._frameHandler),
            i._vrDisplay = void 0,
            i._frameHandler = Engine.QueueNewFrame(i._boundRenderFunction),
            e()
        }
        ,
        this._onVrDisplayPresentChange = function() {
            i._vrExclusivePointerMode = i._vrDisplay && i._vrDisplay.isPresenting
        }
        ;
        var t = this.getHostWindow();
        t && (t.addEventListener("vrdisplayconnect", this._onVrDisplayConnect),
        t.addEventListener("vrdisplaydisconnect", this._onVrDisplayDisconnect),
        t.addEventListener("vrdisplaypresentchange", this._onVrDisplayPresentChange))
    }
    return this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync(),
    this._webVRInitPromise.then(e),
    this._webVRInitPromise
}
;
Engine.prototype._getVRDisplaysAsync = function() {
    var i = this;
    return new Promise(function(e) {
        navigator.getVRDisplays ? navigator.getVRDisplays().then(function(t) {
            i._vrSupported = !0,
            i._vrDisplay = t[0],
            e({
                vrDisplay: i._vrDisplay,
                vrSupported: i._vrSupported
            })
        }) : (i._vrDisplay = void 0,
        i._vrSupported = !1,
        e({
            vrDisplay: i._vrDisplay,
            vrSupported: i._vrSupported
        }))
    }
    )
}
;
Engine.prototype.enableVR = function(i) {
    var e = this;
    if (this._vrDisplay && !this._vrDisplay.isPresenting) {
        var t = function() {
            e.onVRRequestPresentComplete.notifyObservers(!0),
            e._onVRFullScreenTriggered()
        }
          , r = function() {
            e.onVRRequestPresentComplete.notifyObservers(!1)
        };
        this.onVRRequestPresentStart.notifyObservers(this);
        var n = {
            highRefreshRate: this.vrPresentationAttributes ? this.vrPresentationAttributes.highRefreshRate : !1,
            foveationLevel: this.vrPresentationAttributes ? this.vrPresentationAttributes.foveationLevel : 1,
            multiview: (this.getCaps().multiview || this.getCaps().oculusMultiview) && i.useMultiview
        };
        this._vrDisplay.requestPresent([__assign({
            source: this.getRenderingCanvas(),
            attributes: n
        }, n)]).then(t).catch(r)
    }
}
;
Engine.prototype._onVRFullScreenTriggered = function() {
    if (this._vrDisplay && this._vrDisplay.isPresenting) {
        this._oldSize = new Size(this.getRenderWidth(),this.getRenderHeight()),
        this._oldHardwareScaleFactor = this.getHardwareScalingLevel();
        var i = this._vrDisplay.getEyeParameters("left");
        this.setHardwareScalingLevel(1),
        this.setSize(i.renderWidth * 2, i.renderHeight)
    } else
        this.setHardwareScalingLevel(this._oldHardwareScaleFactor),
        this.setSize(this._oldSize.width, this._oldSize.height)
}
;
Engine.prototype.disableVR = function() {
    var i = this;
    this._vrDisplay && this._vrDisplay.isPresenting && this._vrDisplay.exitPresent().then(function() {
        return i._onVRFullScreenTriggered()
    }).catch(function() {
        return i._onVRFullScreenTriggered()
    }),
    IsWindowObjectExist() && (window.removeEventListener("vrdisplaypointerrestricted", this._onVRDisplayPointerRestricted),
    window.removeEventListener("vrdisplaypointerunrestricted", this._onVRDisplayPointerUnrestricted),
    this._onVrDisplayConnect && (window.removeEventListener("vrdisplayconnect", this._onVrDisplayConnect),
    this._onVrDisplayDisconnect && window.removeEventListener("vrdisplaydisconnect", this._onVrDisplayDisconnect),
    this._onVrDisplayPresentChange && window.removeEventListener("vrdisplaypresentchange", this._onVrDisplayPresentChange),
    this._onVrDisplayConnect = null,
    this._onVrDisplayDisconnect = null))
}
;
Engine.prototype._connectVREvents = function(i, e) {
    var t = this;
    if (this._onVRDisplayPointerRestricted = function() {
        i && i.requestPointerLock()
    }
    ,
    this._onVRDisplayPointerUnrestricted = function() {
        if (!e) {
            var n = t.getHostWindow();
            n.document && n.document.exitPointerLock && n.document.exitPointerLock();
            return
        }
        !e.exitPointerLock || e.exitPointerLock()
    }
    ,
    IsWindowObjectExist()) {
        var r = this.getHostWindow();
        r.addEventListener("vrdisplaypointerrestricted", this._onVRDisplayPointerRestricted, !1),
        r.addEventListener("vrdisplaypointerunrestricted", this._onVRDisplayPointerUnrestricted, !1)
    }
}
;
Engine.prototype._submitVRFrame = function() {
    if (this._vrDisplay && this._vrDisplay.isPresenting)
        try {
            this._vrDisplay.submitFrame()
        } catch (i) {
            Tools.Warn("webVR submitFrame has had an unexpected failure: " + i)
        }
}
;
Engine.prototype.isVRPresenting = function() {
    return this._vrDisplay && this._vrDisplay.isPresenting
}
;
Engine.prototype._requestVRFrame = function() {
    this._frameHandler = Engine.QueueNewFrame(this._boundRenderFunction, this._vrDisplay)
}
;
Node$2.AddNodeConstructor("WebVRFreeCamera", function(i, e) {
    return function() {
        return new WebVRFreeCamera(i,Vector3.Zero(),e)
    }
});
Node$2.AddNodeConstructor("WebVRGamepadCamera", function(i, e) {
    return function() {
        return new WebVRFreeCamera(i,Vector3.Zero(),e)
    }
});
var WebVRFreeCamera = function(i) {
    __extends(e, i);
    function e(t, r, n, o) {
        o === void 0 && (o = {});
        var a = i.call(this, t, r, n) || this;
        a.webVROptions = o,
        a._vrDevice = null,
        a.rawPose = null,
        a._specsVersion = "1.1",
        a._attached = !1,
        a._descendants = [],
        a._deviceRoomPosition = Vector3.Zero(),
        a._deviceRoomRotationQuaternion = Quaternion.Identity(),
        a._standingMatrix = null,
        a.devicePosition = Vector3.Zero(),
        a.deviceRotationQuaternion = Quaternion.Identity(),
        a.deviceScaleFactor = 1,
        a._deviceToWorld = Matrix.Identity(),
        a._worldToDevice = Matrix.Identity(),
        a.controllers = [],
        a.onControllersAttachedObservable = new Observable,
        a.onControllerMeshLoadedObservable = new Observable,
        a.onPoseUpdatedFromDeviceObservable = new Observable,
        a._poseSet = !1,
        a.rigParenting = !0,
        a._defaultHeight = void 0,
        a._setRigMode = setWebVRRigMode.bind(null, a),
        a._detachIfAttached = function() {
            var l = a.getEngine().getVRDevice();
            l && !l.isPresenting && a.detachControl()
        }
        ,
        a._workingVector = Vector3.Zero(),
        a._oneVector = Vector3.One(),
        a._workingMatrix = Matrix.Identity(),
        a._tmpMatrix = new Matrix,
        a._cache.position = Vector3.Zero(),
        o.defaultHeight && (a._defaultHeight = o.defaultHeight,
        a.position.y = a._defaultHeight),
        a.minZ = .1,
        arguments.length === 5 && (a.webVROptions = arguments[4]),
        a.webVROptions.trackPosition == null && (a.webVROptions.trackPosition = !0),
        a.webVROptions.controllerMeshes == null && (a.webVROptions.controllerMeshes = !0),
        a.webVROptions.defaultLightingOnControllers == null && (a.webVROptions.defaultLightingOnControllers = !0),
        a.rotationQuaternion = new Quaternion,
        a.webVROptions && a.webVROptions.positionScale && (a.deviceScaleFactor = a.webVROptions.positionScale);
        var s = a.getEngine();
        return a._onVREnabled = function(l) {
            l && a.initControllers()
        }
        ,
        s.onVRRequestPresentComplete.add(a._onVREnabled),
        s.initWebVR().add(function(l) {
            !l.vrDisplay || a._vrDevice === l.vrDisplay || (a._vrDevice = l.vrDisplay,
            a.setCameraRigMode(Camera$1.RIG_MODE_WEBVR, {
                parentCamera: a,
                vrDisplay: a._vrDevice,
                frameData: a._frameData,
                specs: a._specsVersion
            }),
            a._attached && a.getEngine().enableVR(a.webVROptions))
        }),
        typeof VRFrameData != "undefined" && (a._frameData = new VRFrameData),
        o.useMultiview && (a.getScene().getEngine().getCaps().multiview ? (a._useMultiviewToSingleView = !0,
        a._rigPostProcess = new VRMultiviewToSingleviewPostProcess("VRMultiviewToSingleview",a,1)) : (Logger$2.Warn("Multiview is not supported, falling back to standard rendering"),
        a._useMultiviewToSingleView = !1)),
        n.onBeforeCameraRenderObservable.add(function(l) {
            l.parent === a && a.rigParenting && (a._descendants = a.getDescendants(!0, function(u) {
                var c = a.controllers.some(function(f) {
                    return f._mesh === u
                })
                  , h = a._rigCameras.indexOf(u) !== -1;
                return !c && !h
            }),
            a._descendants.forEach(function(u) {
                u.parent = l
            }))
        }),
        n.onAfterCameraRenderObservable.add(function(l) {
            l.parent === a && a.rigParenting && a._descendants.forEach(function(u) {
                u.parent = a
            })
        }),
        a
    }
    return e.prototype.deviceDistanceToRoomGround = function() {
        return this._standingMatrix ? (this._standingMatrix.getTranslationToRef(this._workingVector),
        this._deviceRoomPosition.y + this._workingVector.y) : this._defaultHeight || 0
    }
    ,
    e.prototype.useStandingMatrix = function(t) {
        var r = this;
        t === void 0 && (t = function(n) {}
        ),
        this.getEngine().initWebVRAsync().then(function(n) {
            !n.vrDisplay || !n.vrDisplay.stageParameters || !n.vrDisplay.stageParameters.sittingToStandingTransform || !r.webVROptions.trackPosition ? t(!1) : (r._standingMatrix = new Matrix,
            Matrix.FromFloat32ArrayToRefScaled(n.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, r._standingMatrix),
            r.getScene().useRightHandedSystem || r._standingMatrix && r._standingMatrix.toggleModelMatrixHandInPlace(),
            t(!0))
        })
    }
    ,
    e.prototype.useStandingMatrixAsync = function() {
        var t = this;
        return new Promise(function(r) {
            t.useStandingMatrix(function(n) {
                r(n)
            })
        }
        )
    }
    ,
    e.prototype.dispose = function() {
        this._detachIfAttached(),
        this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled),
        this._updateCacheWhenTrackingDisabledObserver && this._scene.onBeforeRenderObservable.remove(this._updateCacheWhenTrackingDisabledObserver),
        i.prototype.dispose.call(this)
    }
    ,
    e.prototype.getControllerByName = function(t) {
        for (var r = 0, n = this.controllers; r < n.length; r++) {
            var o = n[r];
            if (o.hand === t)
                return o
        }
        return null
    }
    ,
    Object.defineProperty(e.prototype, "leftController", {
        get: function() {
            return this._leftController || (this._leftController = this.getControllerByName("left")),
            this._leftController
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "rightController", {
        get: function() {
            return this._rightController || (this._rightController = this.getControllerByName("right")),
            this._rightController
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getForwardRay = function(t) {
        return t === void 0 && (t = 100),
        this.leftCamera ? i.prototype.getForwardRay.call(this, t, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition) : i.prototype.getForwardRay.call(this, t)
    }
    ,
    e.prototype._checkInputs = function() {
        this._vrDevice && this._vrDevice.isPresenting && (this._vrDevice.getFrameData(this._frameData),
        this.updateFromDevice(this._frameData.pose)),
        i.prototype._checkInputs.call(this)
    }
    ,
    e.prototype.updateFromDevice = function(t) {
        t && t.orientation && t.orientation.length === 4 && (this.rawPose = t,
        this._deviceRoomRotationQuaternion.copyFromFloats(t.orientation[0], t.orientation[1], -t.orientation[2], -t.orientation[3]),
        this.getScene().useRightHandedSystem && (this._deviceRoomRotationQuaternion.z *= -1,
        this._deviceRoomRotationQuaternion.w *= -1),
        this.webVROptions.trackPosition && this.rawPose.position && (this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]),
        this.getScene().useRightHandedSystem && (this._deviceRoomPosition.z *= -1)),
        this._poseSet = !0)
    }
    ,
    e.prototype.attachControl = function(t) {
        t = Tools.BackCompatCameraNoPreventDefault(arguments),
        i.prototype.attachControl.call(this, t),
        this._attached = !0,
        t = Camera$1.ForceAttachControlToAlwaysPreventDefault ? !1 : t,
        this._vrDevice && this.getEngine().enableVR(this.webVROptions);
        var r = this._scene.getEngine().getHostWindow();
        r && r.addEventListener("vrdisplaypresentchange", this._detachIfAttached)
    }
    ,
    e.prototype.detachControl = function(t) {
        this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),
        this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),
        i.prototype.detachControl.call(this),
        this._attached = !1,
        this.getEngine().disableVR(),
        window.removeEventListener("vrdisplaypresentchange", this._detachIfAttached)
    }
    ,
    e.prototype.getClassName = function() {
        return "WebVRFreeCamera"
    }
    ,
    e.prototype.resetToCurrentRotation = function() {
        this._vrDevice.resetPose()
    }
    ,
    e.prototype._updateRigCameras = function() {
        var t = this._rigCameras[0]
          , r = this._rigCameras[1];
        t.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion),
        r.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion),
        t.position.copyFrom(this._deviceRoomPosition),
        r.position.copyFrom(this._deviceRoomPosition)
    }
    ,
    e.prototype._correctPositionIfNotTrackPosition = function(t, r) {
        r === void 0 && (r = !1),
        this.rawPose && this.rawPose.position && !this.webVROptions.trackPosition && (Matrix.TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix),
        r || this._tmpMatrix.invert(),
        this._tmpMatrix.multiplyToRef(t, t))
    }
    ,
    e.prototype._updateCache = function(t) {
        var r = this;
        (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) && (this.updateCacheCalled || (this.updateCacheCalled = !0,
        this.update()),
        this.rotationQuaternion.toRotationMatrix(this._workingMatrix),
        Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector),
        this.devicePosition.subtractToRef(this._workingVector, this._workingVector),
        Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld),
        this._deviceToWorld.getTranslationToRef(this._workingVector),
        this._workingVector.addInPlace(this.position),
        this._workingVector.subtractInPlace(this._cache.position),
        this._deviceToWorld.setTranslation(this._workingVector),
        this._deviceToWorld.invertToRef(this._worldToDevice),
        this.controllers.forEach(function(n) {
            n._deviceToWorld.copyFrom(r._deviceToWorld),
            r._correctPositionIfNotTrackPosition(n._deviceToWorld),
            n.update()
        })),
        t || i.prototype._updateCache.call(this),
        this.updateCacheCalled = !1
    }
    ,
    e.prototype._computeDevicePosition = function() {
        Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition)
    }
    ,
    e.prototype.update = function() {
        this._computeDevicePosition(),
        Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix),
        this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix),
        Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion),
        this._poseSet && this.onPoseUpdatedFromDeviceObservable.notifyObservers(null),
        i.prototype.update.call(this)
    }
    ,
    e.prototype._getViewMatrix = function() {
        return Matrix.Identity()
    }
    ,
    e.prototype._getWebVRViewMatrix = function() {
        var t = this._cameraRigParams.parentCamera;
        t._updateCache();
        var r = this._cameraRigParams.left ? this._cameraRigParams.frameData.leftViewMatrix : this._cameraRigParams.frameData.rightViewMatrix;
        return Matrix.FromArrayToRef(r, 0, this._webvrViewMatrix),
        this.getScene().useRightHandedSystem || this._webvrViewMatrix.toggleModelMatrixHandInPlace(),
        this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix),
        Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint),
        this.position.addToRef(this._transformedReferencePoint, this._currentTarget),
        t.deviceScaleFactor !== 1 && (this._webvrViewMatrix.invert(),
        t.deviceScaleFactor && (this._webvrViewMatrix.multiplyAtIndex(12, t.deviceScaleFactor),
        this._webvrViewMatrix.multiplyAtIndex(13, t.deviceScaleFactor),
        this._webvrViewMatrix.multiplyAtIndex(14, t.deviceScaleFactor)),
        this._webvrViewMatrix.invert()),
        t._correctPositionIfNotTrackPosition(this._webvrViewMatrix, !0),
        t._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix),
        this._workingMatrix = this._workingMatrix || Matrix.Identity(),
        this._webvrViewMatrix.invertToRef(this._workingMatrix),
        this._workingMatrix.multiplyToRef(t.getWorldMatrix(), this._workingMatrix),
        this._workingMatrix.getTranslationToRef(this._globalPosition),
        this._markSyncedWithParent(),
        this._webvrViewMatrix
    }
    ,
    e.prototype._getWebVRProjectionMatrix = function() {
        var t = this.parent;
        t._vrDevice.depthNear = t.minZ,
        t._vrDevice.depthFar = t.maxZ;
        var r = this._cameraRigParams.left ? this._cameraRigParams.frameData.leftProjectionMatrix : this._cameraRigParams.frameData.rightProjectionMatrix;
        return Matrix.FromArrayToRef(r, 0, this._projectionMatrix),
        this.getScene().useRightHandedSystem || this._projectionMatrix.toggleProjectionMatrixHandInPlace(),
        this._projectionMatrix
    }
    ,
    e.prototype.initControllers = function() {
        var t = this;
        this.controllers = [];
        var r = this.getScene().gamepadManager;
        this._onGamepadDisconnectedObserver = r.onGamepadDisconnectedObservable.add(function(n) {
            if (n.type === Gamepad.POSE_ENABLED) {
                var o = n;
                o.defaultModel && o.defaultModel.setEnabled(!1),
                o.hand === "right" && (t._rightController = null),
                o.hand === "left" && (t._leftController = null);
                var a = t.controllers.indexOf(o);
                a !== -1 && t.controllers.splice(a, 1)
            }
        }),
        this._onGamepadConnectedObserver = r.onGamepadConnectedObservable.add(function(n) {
            if (n.type === Gamepad.POSE_ENABLED) {
                var o = n;
                if (t.webVROptions.trackPosition || (o._disableTrackPosition(new Vector3(o.hand == "left" ? -.15 : .15,-.5,.25)),
                t._updateCacheWhenTrackingDisabledObserver || (t._updateCacheWhenTrackingDisabledObserver = t._scene.onBeforeRenderObservable.add(function() {
                    t._updateCache()
                }))),
                o.deviceScaleFactor = t.deviceScaleFactor,
                o._deviceToWorld.copyFrom(t._deviceToWorld),
                t._correctPositionIfNotTrackPosition(o._deviceToWorld),
                t.webVROptions.controllerMeshes && (o.defaultModel ? o.defaultModel.setEnabled(!0) : o.initControllerMesh(t.getScene(), function(l) {
                    if (l.scaling.scaleInPlace(t.deviceScaleFactor),
                    t.onControllerMeshLoadedObservable.notifyObservers(o),
                    t.webVROptions.defaultLightingOnControllers) {
                        t._lightOnControllers || (t._lightOnControllers = new HemisphericLight("vrControllersLight",new Vector3(0,1,0),t.getScene()));
                        var u = function(c, h) {
                            var f = c.getChildren();
                            f && f.length !== 0 && f.forEach(function(d) {
                                h.includedOnlyMeshes.push(d),
                                u(d, h)
                            })
                        };
                        t._lightOnControllers.includedOnlyMeshes.push(l),
                        u(l, t._lightOnControllers)
                    }
                })),
                o.attachToPoseControlledCamera(t),
                t.controllers.indexOf(o) === -1) {
                    t.controllers.push(o);
                    for (var a = !1, s = 0; s < t.controllers.length; s++)
                        t.controllers[s].controllerType === PoseEnabledControllerType.VIVE && (a ? t.controllers[s].hand = "right" : (a = !0,
                        t.controllers[s].hand = "left"));
                    t.controllers.length >= 2 && t.onControllersAttachedObservable.notifyObservers(t.controllers)
                }
            }
        })
    }
    ,
    e
}(FreeCamera), WebVRController = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, t) || this;
        return r.onTriggerStateChangedObservable = new Observable,
        r.onMainButtonStateChangedObservable = new Observable,
        r.onSecondaryButtonStateChangedObservable = new Observable,
        r.onPadStateChangedObservable = new Observable,
        r.onPadValuesChangedObservable = new Observable,
        r.pad = {
            x: 0,
            y: 0
        },
        r._changes = {
            pressChanged: !1,
            touchChanged: !1,
            valueChanged: !1,
            changed: !1
        },
        r._buttons = new Array(t.buttons.length),
        r.hand = t.hand,
        r
    }
    return e.prototype.onButtonStateChange = function(t) {
        this._onButtonStateChange = t
    }
    ,
    Object.defineProperty(e.prototype, "defaultModel", {
        get: function() {
            return this._defaultModel
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.update = function() {
        i.prototype.update.call(this);
        for (var t = 0; t < this._buttons.length; t++)
            this._setButtonValue(this.browserGamepad.buttons[t], this._buttons[t], t);
        (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))
    }
    ,
    e.prototype._setButtonValue = function(t, r, n) {
        if (t || (t = {
            pressed: !1,
            touched: !1,
            value: 0
        }),
        !r) {
            this._buttons[n] = {
                pressed: t.pressed,
                touched: t.touched,
                value: t.value
            };
            return
        }
        this._checkChanges(t, r),
        this._changes.changed && (this._onButtonStateChange && this._onButtonStateChange(this.index, n, t),
        this._handleButtonChange(n, t, this._changes)),
        this._buttons[n].pressed = t.pressed,
        this._buttons[n].touched = t.touched,
        this._buttons[n].value = t.value < 1e-8 ? 0 : t.value
    }
    ,
    e.prototype._checkChanges = function(t, r) {
        return this._changes.pressChanged = t.pressed !== r.pressed,
        this._changes.touchChanged = t.touched !== r.touched,
        this._changes.valueChanged = t.value !== r.value,
        this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged,
        this._changes
    }
    ,
    e.prototype.dispose = function() {
        i.prototype.dispose.call(this),
        this._defaultModel = null,
        this.onTriggerStateChangedObservable.clear(),
        this.onMainButtonStateChangedObservable.clear(),
        this.onSecondaryButtonStateChangedObservable.clear(),
        this.onPadStateChangedObservable.clear(),
        this.onPadValuesChangedObservable.clear()
    }
    ,
    e
}(PoseEnabledController), Xbox360Button;
(function(i) {
    i[i.A = 0] = "A",
    i[i.B = 1] = "B",
    i[i.X = 2] = "X",
    i[i.Y = 3] = "Y",
    i[i.LB = 4] = "LB",
    i[i.RB = 5] = "RB",
    i[i.Back = 8] = "Back",
    i[i.Start = 9] = "Start",
    i[i.LeftStick = 10] = "LeftStick",
    i[i.RightStick = 11] = "RightStick"
}
)(Xbox360Button || (Xbox360Button = {}));
var Xbox360Dpad;
(function(i) {
    i[i.Up = 12] = "Up",
    i[i.Down = 13] = "Down",
    i[i.Left = 14] = "Left",
    i[i.Right = 15] = "Right"
}
)(Xbox360Dpad || (Xbox360Dpad = {}));
var Xbox360Pad = function(i) {
    __extends(e, i);
    function e(t, r, n, o) {
        o === void 0 && (o = !1);
        var a = i.call(this, t, r, n, 0, 1, 2, 3) || this;
        return a._leftTrigger = 0,
        a._rightTrigger = 0,
        a.onButtonDownObservable = new Observable,
        a.onButtonUpObservable = new Observable,
        a.onPadDownObservable = new Observable,
        a.onPadUpObservable = new Observable,
        a._buttonA = 0,
        a._buttonB = 0,
        a._buttonX = 0,
        a._buttonY = 0,
        a._buttonBack = 0,
        a._buttonStart = 0,
        a._buttonLB = 0,
        a._buttonRB = 0,
        a._buttonLeftStick = 0,
        a._buttonRightStick = 0,
        a._dPadUp = 0,
        a._dPadDown = 0,
        a._dPadLeft = 0,
        a._dPadRight = 0,
        a._isXboxOnePad = !1,
        a.type = Gamepad.XBOX,
        a._isXboxOnePad = o,
        a
    }
    return e.prototype.onlefttriggerchanged = function(t) {
        this._onlefttriggerchanged = t
    }
    ,
    e.prototype.onrighttriggerchanged = function(t) {
        this._onrighttriggerchanged = t
    }
    ,
    Object.defineProperty(e.prototype, "leftTrigger", {
        get: function() {
            return this._leftTrigger
        },
        set: function(t) {
            this._onlefttriggerchanged && this._leftTrigger !== t && this._onlefttriggerchanged(t),
            this._leftTrigger = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "rightTrigger", {
        get: function() {
            return this._rightTrigger
        },
        set: function(t) {
            this._onrighttriggerchanged && this._rightTrigger !== t && this._onrighttriggerchanged(t),
            this._rightTrigger = t
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.onbuttondown = function(t) {
        this._onbuttondown = t
    }
    ,
    e.prototype.onbuttonup = function(t) {
        this._onbuttonup = t
    }
    ,
    e.prototype.ondpaddown = function(t) {
        this._ondpaddown = t
    }
    ,
    e.prototype.ondpadup = function(t) {
        this._ondpadup = t
    }
    ,
    e.prototype._setButtonValue = function(t, r, n) {
        return t !== r && (t === 1 && (this._onbuttondown && this._onbuttondown(n),
        this.onButtonDownObservable.notifyObservers(n)),
        t === 0 && (this._onbuttonup && this._onbuttonup(n),
        this.onButtonUpObservable.notifyObservers(n))),
        t
    }
    ,
    e.prototype._setDPadValue = function(t, r, n) {
        return t !== r && (t === 1 && (this._ondpaddown && this._ondpaddown(n),
        this.onPadDownObservable.notifyObservers(n)),
        t === 0 && (this._ondpadup && this._ondpadup(n),
        this.onPadUpObservable.notifyObservers(n))),
        t
    }
    ,
    Object.defineProperty(e.prototype, "buttonA", {
        get: function() {
            return this._buttonA
        },
        set: function(t) {
            this._buttonA = this._setButtonValue(t, this._buttonA, Xbox360Button.A)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "buttonB", {
        get: function() {
            return this._buttonB
        },
        set: function(t) {
            this._buttonB = this._setButtonValue(t, this._buttonB, Xbox360Button.B)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "buttonX", {
        get: function() {
            return this._buttonX
        },
        set: function(t) {
            this._buttonX = this._setButtonValue(t, this._buttonX, Xbox360Button.X)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "buttonY", {
        get: function() {
            return this._buttonY
        },
        set: function(t) {
            this._buttonY = this._setButtonValue(t, this._buttonY, Xbox360Button.Y)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "buttonStart", {
        get: function() {
            return this._buttonStart
        },
        set: function(t) {
            this._buttonStart = this._setButtonValue(t, this._buttonStart, Xbox360Button.Start)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "buttonBack", {
        get: function() {
            return this._buttonBack
        },
        set: function(t) {
            this._buttonBack = this._setButtonValue(t, this._buttonBack, Xbox360Button.Back)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "buttonLB", {
        get: function() {
            return this._buttonLB
        },
        set: function(t) {
            this._buttonLB = this._setButtonValue(t, this._buttonLB, Xbox360Button.LB)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "buttonRB", {
        get: function() {
            return this._buttonRB
        },
        set: function(t) {
            this._buttonRB = this._setButtonValue(t, this._buttonRB, Xbox360Button.RB)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "buttonLeftStick", {
        get: function() {
            return this._buttonLeftStick
        },
        set: function(t) {
            this._buttonLeftStick = this._setButtonValue(t, this._buttonLeftStick, Xbox360Button.LeftStick)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "buttonRightStick", {
        get: function() {
            return this._buttonRightStick
        },
        set: function(t) {
            this._buttonRightStick = this._setButtonValue(t, this._buttonRightStick, Xbox360Button.RightStick)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "dPadUp", {
        get: function() {
            return this._dPadUp
        },
        set: function(t) {
            this._dPadUp = this._setDPadValue(t, this._dPadUp, Xbox360Dpad.Up)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "dPadDown", {
        get: function() {
            return this._dPadDown
        },
        set: function(t) {
            this._dPadDown = this._setDPadValue(t, this._dPadDown, Xbox360Dpad.Down)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "dPadLeft", {
        get: function() {
            return this._dPadLeft
        },
        set: function(t) {
            this._dPadLeft = this._setDPadValue(t, this._dPadLeft, Xbox360Dpad.Left)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "dPadRight", {
        get: function() {
            return this._dPadRight
        },
        set: function(t) {
            this._dPadRight = this._setDPadValue(t, this._dPadRight, Xbox360Dpad.Right)
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.update = function() {
        i.prototype.update.call(this),
        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.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) : (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)
    }
    ,
    e.prototype.dispose = function() {
        i.prototype.dispose.call(this),
        this.onButtonDownObservable.clear(),
        this.onButtonUpObservable.clear(),
        this.onPadDownObservable.clear(),
        this.onPadUpObservable.clear()
    }
    ,
    e
}(Gamepad), DualShockButton;
(function(i) {
    i[i.Cross = 0] = "Cross",
    i[i.Circle = 1] = "Circle",
    i[i.Square = 2] = "Square",
    i[i.Triangle = 3] = "Triangle",
    i[i.L1 = 4] = "L1",
    i[i.R1 = 5] = "R1",
    i[i.Share = 8] = "Share",
    i[i.Options = 9] = "Options",
    i[i.LeftStick = 10] = "LeftStick",
    i[i.RightStick = 11] = "RightStick"
}
)(DualShockButton || (DualShockButton = {}));
var DualShockDpad;
(function(i) {
    i[i.Up = 12] = "Up",
    i[i.Down = 13] = "Down",
    i[i.Left = 14] = "Left",
    i[i.Right = 15] = "Right"
}
)(DualShockDpad || (DualShockDpad = {}));
var DualShockPad = function(i) {
    __extends(e, i);
    function e(t, r, n) {
        var o = i.call(this, t.replace("STANDARD GAMEPAD", "SONY PLAYSTATION DUALSHOCK"), r, n, 0, 1, 2, 3) || this;
        return o._leftTrigger = 0,
        o._rightTrigger = 0,
        o.onButtonDownObservable = new Observable,
        o.onButtonUpObservable = new Observable,
        o.onPadDownObservable = new Observable,
        o.onPadUpObservable = new Observable,
        o._buttonCross = 0,
        o._buttonCircle = 0,
        o._buttonSquare = 0,
        o._buttonTriangle = 0,
        o._buttonShare = 0,
        o._buttonOptions = 0,
        o._buttonL1 = 0,
        o._buttonR1 = 0,
        o._buttonLeftStick = 0,
        o._buttonRightStick = 0,
        o._dPadUp = 0,
        o._dPadDown = 0,
        o._dPadLeft = 0,
        o._dPadRight = 0,
        o.type = Gamepad.DUALSHOCK,
        o
    }
    return e.prototype.onlefttriggerchanged = function(t) {
        this._onlefttriggerchanged = t
    }
    ,
    e.prototype.onrighttriggerchanged = function(t) {
        this._onrighttriggerchanged = t
    }
    ,
    Object.defineProperty(e.prototype, "leftTrigger", {
        get: function() {
            return this._leftTrigger
        },
        set: function(t) {
            this._onlefttriggerchanged && this._leftTrigger !== t && this._onlefttriggerchanged(t),
            this._leftTrigger = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "rightTrigger", {
        get: function() {
            return this._rightTrigger
        },
        set: function(t) {
            this._onrighttriggerchanged && this._rightTrigger !== t && this._onrighttriggerchanged(t),
            this._rightTrigger = t
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.onbuttondown = function(t) {
        this._onbuttondown = t
    }
    ,
    e.prototype.onbuttonup = function(t) {
        this._onbuttonup = t
    }
    ,
    e.prototype.ondpaddown = function(t) {
        this._ondpaddown = t
    }
    ,
    e.prototype.ondpadup = function(t) {
        this._ondpadup = t
    }
    ,
    e.prototype._setButtonValue = function(t, r, n) {
        return t !== r && (t === 1 && (this._onbuttondown && this._onbuttondown(n),
        this.onButtonDownObservable.notifyObservers(n)),
        t === 0 && (this._onbuttonup && this._onbuttonup(n),
        this.onButtonUpObservable.notifyObservers(n))),
        t
    }
    ,
    e.prototype._setDPadValue = function(t, r, n) {
        return t !== r && (t === 1 && (this._ondpaddown && this._ondpaddown(n),
        this.onPadDownObservable.notifyObservers(n)),
        t === 0 && (this._ondpadup && this._ondpadup(n),
        this.onPadUpObservable.notifyObservers(n))),
        t
    }
    ,
    Object.defineProperty(e.prototype, "buttonCross", {
        get: function() {
            return this._buttonCross
        },
        set: function(t) {
            this._buttonCross = this._setButtonValue(t, this._buttonCross, DualShockButton.Cross)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "buttonCircle", {
        get: function() {
            return this._buttonCircle
        },
        set: function(t) {
            this._buttonCircle = this._setButtonValue(t, this._buttonCircle, DualShockButton.Circle)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "buttonSquare", {
        get: function() {
            return this._buttonSquare
        },
        set: function(t) {
            this._buttonSquare = this._setButtonValue(t, this._buttonSquare, DualShockButton.Square)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "buttonTriangle", {
        get: function() {
            return this._buttonTriangle
        },
        set: function(t) {
            this._buttonTriangle = this._setButtonValue(t, this._buttonTriangle, DualShockButton.Triangle)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "buttonOptions", {
        get: function() {
            return this._buttonOptions
        },
        set: function(t) {
            this._buttonOptions = this._setButtonValue(t, this._buttonOptions, DualShockButton.Options)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "buttonShare", {
        get: function() {
            return this._buttonShare
        },
        set: function(t) {
            this._buttonShare = this._setButtonValue(t, this._buttonShare, DualShockButton.Share)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "buttonL1", {
        get: function() {
            return this._buttonL1
        },
        set: function(t) {
            this._buttonL1 = this._setButtonValue(t, this._buttonL1, DualShockButton.L1)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "buttonR1", {
        get: function() {
            return this._buttonR1
        },
        set: function(t) {
            this._buttonR1 = this._setButtonValue(t, this._buttonR1, DualShockButton.R1)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "buttonLeftStick", {
        get: function() {
            return this._buttonLeftStick
        },
        set: function(t) {
            this._buttonLeftStick = this._setButtonValue(t, this._buttonLeftStick, DualShockButton.LeftStick)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "buttonRightStick", {
        get: function() {
            return this._buttonRightStick
        },
        set: function(t) {
            this._buttonRightStick = this._setButtonValue(t, this._buttonRightStick, DualShockButton.RightStick)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "dPadUp", {
        get: function() {
            return this._dPadUp
        },
        set: function(t) {
            this._dPadUp = this._setDPadValue(t, this._dPadUp, DualShockDpad.Up)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "dPadDown", {
        get: function() {
            return this._dPadDown
        },
        set: function(t) {
            this._dPadDown = this._setDPadValue(t, this._dPadDown, DualShockDpad.Down)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "dPadLeft", {
        get: function() {
            return this._dPadLeft
        },
        set: function(t) {
            this._dPadLeft = this._setDPadValue(t, this._dPadLeft, DualShockDpad.Left)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "dPadRight", {
        get: function() {
            return this._dPadRight
        },
        set: function(t) {
            this._dPadRight = this._setDPadValue(t, this._dPadRight, DualShockDpad.Right)
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.update = function() {
        i.prototype.update.call(this),
        this.buttonCross = this.browserGamepad.buttons[0].value,
        this.buttonCircle = this.browserGamepad.buttons[1].value,
        this.buttonSquare = this.browserGamepad.buttons[2].value,
        this.buttonTriangle = this.browserGamepad.buttons[3].value,
        this.buttonL1 = this.browserGamepad.buttons[4].value,
        this.buttonR1 = this.browserGamepad.buttons[5].value,
        this.leftTrigger = this.browserGamepad.buttons[6].value,
        this.rightTrigger = this.browserGamepad.buttons[7].value,
        this.buttonShare = this.browserGamepad.buttons[8].value,
        this.buttonOptions = 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
    }
    ,
    e.prototype.dispose = function() {
        i.prototype.dispose.call(this),
        this.onButtonDownObservable.clear(),
        this.onButtonUpObservable.clear(),
        this.onPadDownObservable.clear(),
        this.onPadUpObservable.clear()
    }
    ,
    e
}(Gamepad)
  , GamepadManager = function() {
    function i(e) {
        var t = this;
        if (this._scene = e,
        this._babylonGamepads = [],
        this._oneGamepadConnected = !1,
        this._isMonitoring = !1,
        this.onGamepadDisconnectedObservable = new Observable,
        IsWindowObjectExist() ? (this._gamepadEventSupported = "GamepadEvent"in window,
        this._gamepadSupport = navigator && (navigator.getGamepads || navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads)) : this._gamepadEventSupported = !1,
        this.onGamepadConnectedObservable = new Observable(function(n) {
            for (var o in t._babylonGamepads) {
                var a = t._babylonGamepads[o];
                a && a._isConnected && t.onGamepadConnectedObservable.notifyObserver(n, a)
            }
        }
        ),
        this._onGamepadConnectedEvent = function(n) {
            var o = n.gamepad;
            if (!(o.index in t._babylonGamepads && t._babylonGamepads[o.index].isConnected)) {
                var a;
                t._babylonGamepads[o.index] ? (a = t._babylonGamepads[o.index],
                a.browserGamepad = o,
                a._isConnected = !0) : a = t._addNewGamepad(o),
                t.onGamepadConnectedObservable.notifyObservers(a),
                t._startMonitoringGamepads()
            }
        }
        ,
        this._onGamepadDisconnectedEvent = function(n) {
            var o = n.gamepad;
            for (var a in t._babylonGamepads)
                if (t._babylonGamepads[a].index === o.index) {
                    var s = t._babylonGamepads[a];
                    s._isConnected = !1,
                    t.onGamepadDisconnectedObservable.notifyObservers(s),
                    s.dispose && s.dispose();
                    break
                }
        }
        ,
        this._gamepadSupport)
            if (this._updateGamepadObjects(),
            this._babylonGamepads.length && this._startMonitoringGamepads(),
            this._gamepadEventSupported) {
                var r = this._scene ? this._scene.getEngine().getHostWindow() : window;
                r && (r.addEventListener("gamepadconnected", this._onGamepadConnectedEvent, !1),
                r.addEventListener("gamepaddisconnected", this._onGamepadDisconnectedEvent, !1))
            } else
                this._startMonitoringGamepads()
    }
    return Object.defineProperty(i.prototype, "gamepads", {
        get: function() {
            return this._babylonGamepads
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.getGamepadByType = function(e) {
        e === void 0 && (e = Gamepad.XBOX);
        for (var t = 0, r = this._babylonGamepads; t < r.length; t++) {
            var n = r[t];
            if (n && n.type === e)
                return n
        }
        return null
    }
    ,
    i.prototype.dispose = function() {
        this._gamepadEventSupported && (this._onGamepadConnectedEvent && window.removeEventListener("gamepadconnected", this._onGamepadConnectedEvent),
        this._onGamepadDisconnectedEvent && window.removeEventListener("gamepaddisconnected", this._onGamepadDisconnectedEvent),
        this._onGamepadConnectedEvent = null,
        this._onGamepadDisconnectedEvent = null),
        this._babylonGamepads.forEach(function(e) {
            e.dispose()
        }),
        this.onGamepadConnectedObservable.clear(),
        this.onGamepadDisconnectedObservable.clear(),
        this._oneGamepadConnected = !1,
        this._stopMonitoringGamepads(),
        this._babylonGamepads = []
    }
    ,
    i.prototype._addNewGamepad = function(e) {
        this._oneGamepadConnected || (this._oneGamepadConnected = !0);
        var t, r = e.id.search("054c") !== -1 && e.id.search("0ce6") === -1, n = e.id.search("Xbox One") !== -1;
        return n || e.id.search("Xbox 360") !== -1 || e.id.search("xinput") !== -1 || e.id.search("045e") !== -1 && e.id.search("Surface Dock") === -1 ? t = new Xbox360Pad(e.id,e.index,e,n) : r ? t = new DualShockPad(e.id,e.index,e) : e.pose ? t = PoseEnabledControllerHelper.InitiateController(e) : t = new GenericPad(e.id,e.index,e),
        this._babylonGamepads[t.index] = t,
        t
    }
    ,
    i.prototype._startMonitoringGamepads = function() {
        this._isMonitoring || (this._isMonitoring = !0,
        this._scene || this._checkGamepadsStatus())
    }
    ,
    i.prototype._stopMonitoringGamepads = function() {
        this._isMonitoring = !1
    }
    ,
    i.prototype._checkGamepadsStatus = function() {
        var e = this;
        this._updateGamepadObjects();
        for (var t in this._babylonGamepads) {
            var r = this._babylonGamepads[t];
            if (!(!r || !r.isConnected))
                try {
                    r.update()
                } catch {
                    this._loggedErrors.indexOf(r.index) === -1 && (Tools.Warn("Error updating gamepad " + r.id),
                    this._loggedErrors.push(r.index))
                }
        }
        this._isMonitoring && !this._scene && Engine.QueueNewFrame(function() {
            e._checkGamepadsStatus()
        })
    }
    ,
    i.prototype._updateGamepadObjects = function() {
        for (var e = navigator.getGamepads ? navigator.getGamepads() : navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : [], t = 0; t < e.length; t++) {
            var r = e[t];
            if (r)
                if (this._babylonGamepads[r.index])
                    this._babylonGamepads[t].browserGamepad = r,
                    this._babylonGamepads[t].isConnected || (this._babylonGamepads[t]._isConnected = !0,
                    this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[t]));
                else {
                    var n = this._addNewGamepad(r);
                    this.onGamepadConnectedObservable.notifyObservers(n)
                }
        }
    }
    ,
    i
}()
  , FreeCameraGamepadInput = function() {
    function i() {
        this.gamepadAngularSensibility = 200,
        this.gamepadMoveSensibility = 40,
        this.deadzoneDelta = .1,
        this._yAxisScale = 1,
        this._cameraTransform = Matrix.Identity(),
        this._deltaTransform = Vector3.Zero(),
        this._vector3 = Vector3.Zero(),
        this._vector2 = Vector2.Zero()
    }
    return Object.defineProperty(i.prototype, "invertYAxis", {
        get: function() {
            return this._yAxisScale !== 1
        },
        set: function(e) {
            this._yAxisScale = e ? -1 : 1
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.attachControl = function() {
        var e = this
          , t = this.camera.getScene().gamepadManager;
        this._onGamepadConnectedObserver = t.onGamepadConnectedObservable.add(function(r) {
            r.type !== Gamepad.POSE_ENABLED && (!e.gamepad || r.type === Gamepad.XBOX) && (e.gamepad = r)
        }),
        this._onGamepadDisconnectedObserver = t.onGamepadDisconnectedObservable.add(function(r) {
            e.gamepad === r && (e.gamepad = null)
        }),
        this.gamepad = t.getGamepadByType(Gamepad.XBOX),
        !this.gamepad && t.gamepads.length && (this.gamepad = t.gamepads[0])
    }
    ,
    i.prototype.detachControl = function(e) {
        this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),
        this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),
        this.gamepad = null
    }
    ,
    i.prototype.checkInputs = function() {
        if (this.gamepad && this.gamepad.leftStick) {
            var e = this.camera
              , t = this.gamepad.leftStick;
            this.gamepadMoveSensibility !== 0 && (t.x = Math.abs(t.x) > this.deadzoneDelta ? t.x / this.gamepadMoveSensibility : 0,
            t.y = Math.abs(t.y) > this.deadzoneDelta ? t.y / this.gamepadMoveSensibility : 0);
            var r = this.gamepad.rightStick;
            r && this.gamepadAngularSensibility !== 0 ? (r.x = Math.abs(r.x) > this.deadzoneDelta ? r.x / this.gamepadAngularSensibility : 0,
            r.y = (Math.abs(r.y) > this.deadzoneDelta ? r.y / this.gamepadAngularSensibility : 0) * this._yAxisScale) : r = {
                x: 0,
                y: 0
            },
            e.rotationQuaternion ? e.rotationQuaternion.toRotationMatrix(this._cameraTransform) : Matrix.RotationYawPitchRollToRef(e.rotation.y, e.rotation.x, 0, this._cameraTransform);
            var n = e._computeLocalCameraSpeed() * 50;
            this._vector3.copyFromFloats(t.x * n, 0, -t.y * n),
            Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform),
            e.cameraDirection.addInPlace(this._deltaTransform),
            this._vector2.copyFromFloats(r.y, r.x),
            e.cameraRotation.addInPlace(this._vector2)
        }
    }
    ,
    i.prototype.getClassName = function() {
        return "FreeCameraGamepadInput"
    }
    ,
    i.prototype.getSimpleName = function() {
        return "gamepad"
    }
    ,
    __decorate([serialize()], i.prototype, "gamepadAngularSensibility", void 0),
    __decorate([serialize()], i.prototype, "gamepadMoveSensibility", void 0),
    i
}();
CameraInputTypes.FreeCameraGamepadInput = FreeCameraGamepadInput;
var ArcRotateCameraGamepadInput = function() {
    function i() {
        this.gamepadRotationSensibility = 80,
        this.gamepadMoveSensibility = 40,
        this._yAxisScale = 1
    }
    return Object.defineProperty(i.prototype, "invertYAxis", {
        get: function() {
            return this._yAxisScale !== 1
        },
        set: function(e) {
            this._yAxisScale = e ? -1 : 1
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.attachControl = function() {
        var e = this
          , t = this.camera.getScene().gamepadManager;
        this._onGamepadConnectedObserver = t.onGamepadConnectedObservable.add(function(r) {
            r.type !== Gamepad.POSE_ENABLED && (!e.gamepad || r.type === Gamepad.XBOX) && (e.gamepad = r)
        }),
        this._onGamepadDisconnectedObserver = t.onGamepadDisconnectedObservable.add(function(r) {
            e.gamepad === r && (e.gamepad = null)
        }),
        this.gamepad = t.getGamepadByType(Gamepad.XBOX)
    }
    ,
    i.prototype.detachControl = function(e) {
        this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),
        this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),
        this.gamepad = null
    }
    ,
    i.prototype.checkInputs = function() {
        if (this.gamepad) {
            var e = this.camera
              , t = this.gamepad.rightStick;
            if (t) {
                if (t.x != 0) {
                    var r = t.x / this.gamepadRotationSensibility;
                    r != 0 && Math.abs(r) > .005 && (e.inertialAlphaOffset += r)
                }
                if (t.y != 0) {
                    var n = t.y / this.gamepadRotationSensibility * this._yAxisScale;
                    n != 0 && Math.abs(n) > .005 && (e.inertialBetaOffset += n)
                }
            }
            var o = this.gamepad.leftStick;
            if (o && o.y != 0) {
                var a = o.y / this.gamepadMoveSensibility;
                a != 0 && Math.abs(a) > .005 && (this.camera.inertialRadiusOffset -= a)
            }
        }
    }
    ,
    i.prototype.getClassName = function() {
        return "ArcRotateCameraGamepadInput"
    }
    ,
    i.prototype.getSimpleName = function() {
        return "gamepad"
    }
    ,
    __decorate([serialize()], i.prototype, "gamepadRotationSensibility", void 0),
    __decorate([serialize()], i.prototype, "gamepadMoveSensibility", void 0),
    i
}();
CameraInputTypes.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
Object.defineProperty(Scene.prototype, "gamepadManager", {
    get: function() {
        if (!this._gamepadManager) {
            this._gamepadManager = new GamepadManager(this);
            var i = this._getComponent(SceneComponentConstants.NAME_GAMEPAD);
            i || (i = new GamepadSystemSceneComponent(this),
            this._addComponent(i))
        }
        return this._gamepadManager
    },
    enumerable: !0,
    configurable: !0
});
FreeCameraInputsManager.prototype.addGamepad = function() {
    return this.add(new FreeCameraGamepadInput),
    this
}
;
ArcRotateCameraInputsManager.prototype.addGamepad = function() {
    return this.add(new ArcRotateCameraGamepadInput),
    this
}
;
var GamepadSystemSceneComponent = function() {
    function i(e) {
        this.name = SceneComponentConstants.NAME_GAMEPAD,
        this.scene = e
    }
    return i.prototype.register = function() {
        this.scene._beforeCameraUpdateStage.registerStep(SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate)
    }
    ,
    i.prototype.rebuild = function() {}
    ,
    i.prototype.dispose = function() {
        var e = this.scene._gamepadManager;
        e && (e.dispose(),
        this.scene._gamepadManager = null)
    }
    ,
    i.prototype._beforeCameraUpdate = function() {
        var e = this.scene._gamepadManager;
        e && e._isMonitoring && e._checkGamepadsStatus()
    }
    ,
    i
}(), WebXRManagedOutputCanvasOptions = function() {
    function i() {}
    return i.GetDefaults = function(e) {
        var t = new i;
        return t.canvasOptions = {
            antialias: !0,
            depth: !0,
            stencil: e ? e.isStencilEnable : !0,
            alpha: !0,
            multiview: !1,
            framebufferScaleFactor: 1
        },
        t.newCanvasCssStyle = "position:absolute; bottom:0px;right:0px;z-index:10;width:90%;height:100%;background-color: #000000;",
        t
    }
    ,
    i
}(), WebXRManagedOutputCanvas = function() {
    function i(e, t) {
        var r = this;
        if (t === void 0 && (t = WebXRManagedOutputCanvasOptions.GetDefaults()),
        this._options = t,
        this._canvas = null,
        this._engine = null,
        this.xrLayer = null,
        this.onXRLayerInitObservable = new Observable,
        this._engine = e.scene.getEngine(),
        this._engine.onDisposeObservable.addOnce(function() {
            r._engine = null
        }),
        t.canvasElement)
            this._setManagedOutputCanvas(t.canvasElement);
        else {
            var n = document.createElement("canvas");
            n.style.cssText = this._options.newCanvasCssStyle || "position:absolute; bottom:0px;right:0px;",
            this._setManagedOutputCanvas(n)
        }
        e.onXRSessionInit.add(function() {
            r._addCanvas()
        }),
        e.onXRSessionEnded.add(function() {
            r._removeCanvas()
        })
    }
    return i.prototype.dispose = function() {
        this._removeCanvas(),
        this._setManagedOutputCanvas(null)
    }
    ,
    i.prototype.initializeXRLayerAsync = function(e) {
        var t = this
          , r = function() {
            var n = new XRWebGLLayer(e,t.canvasContext,t._options.canvasOptions);
            return t.onXRLayerInitObservable.notifyObservers(n),
            n
        };
        return this.canvasContext.makeXRCompatible ? this.canvasContext.makeXRCompatible().then(function() {}, function() {
            Tools.Warn("Error executing makeXRCompatible. This does not mean that the session will work incorrectly.")
        }).then(function() {
            return t.xrLayer = r(),
            t.xrLayer
        }) : (this.xrLayer = r(),
        Promise.resolve(this.xrLayer))
    }
    ,
    i.prototype._addCanvas = function() {
        var e = this;
        this._canvas && this._engine && this._canvas !== this._engine.getRenderingCanvas() && document.body.appendChild(this._canvas),
        this.xrLayer ? this._setCanvasSize(!0) : this.onXRLayerInitObservable.addOnce(function(t) {
            e._setCanvasSize(!0, t)
        })
    }
    ,
    i.prototype._removeCanvas = function() {
        this._canvas && this._engine && document.body.contains(this._canvas) && this._canvas !== this._engine.getRenderingCanvas() && document.body.removeChild(this._canvas),
        this._setCanvasSize(!1)
    }
    ,
    i.prototype._setCanvasSize = function(e, t) {
        e === void 0 && (e = !0),
        t === void 0 && (t = this.xrLayer),
        !(!this._canvas || !this._engine) && (e ? t && (this._canvas !== this._engine.getRenderingCanvas() ? (this._canvas.style.width = t.framebufferWidth + "px",
        this._canvas.style.height = t.framebufferHeight + "px") : this._engine.setSize(t.framebufferWidth, t.framebufferHeight)) : this._originalCanvasSize && (this._canvas !== this._engine.getRenderingCanvas() ? (this._canvas.style.width = this._originalCanvasSize.width + "px",
        this._canvas.style.height = this._originalCanvasSize.height + "px") : this._engine.setSize(this._originalCanvasSize.width, this._originalCanvasSize.height)))
    }
    ,
    i.prototype._setManagedOutputCanvas = function(e) {
        this._removeCanvas(),
        e ? (this._originalCanvasSize = {
            width: e.offsetWidth,
            height: e.offsetHeight
        },
        this._canvas = e,
        this.canvasContext = this._canvas.getContext("webgl2"),
        this.canvasContext || (this.canvasContext = this._canvas.getContext("webgl"))) : (this._canvas = null,
        this.canvasContext = null)
    }
    ,
    i
}(), WebXRSessionManager = function() {
    function i(e) {
        var t = this;
        this.scene = e,
        this._sessionEnded = !1,
        this._baseLayer = null,
        this._renderTargetTextures = [],
        this.currentTimestamp = -1,
        this.defaultHeightCompensation = 1.7,
        this.onXRFrameObservable = new Observable,
        this.onXRReferenceSpaceChanged = new Observable,
        this.onXRSessionEnded = new Observable,
        this.onXRSessionInit = new Observable,
        this._engine = e.getEngine(),
        this._engine.onDisposeObservable.addOnce(function() {
            t._engine = null
        })
    }
    return Object.defineProperty(i.prototype, "referenceSpace", {
        get: function() {
            return this._referenceSpace
        },
        set: function(e) {
            this._referenceSpace = e,
            this.onXRReferenceSpaceChanged.notifyObservers(this._referenceSpace)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "sessionMode", {
        get: function() {
            return this._sessionMode
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.dispose = function() {
        this._sessionEnded || this.exitXRAsync(),
        this.onXRFrameObservable.clear(),
        this.onXRSessionEnded.clear(),
        this.onXRReferenceSpaceChanged.clear(),
        this.onXRSessionInit.clear()
    }
    ,
    i.prototype.exitXRAsync = function() {
        return this.session && !this._sessionEnded ? (this._sessionEnded = !0,
        this.session.end().catch(function(e) {
            Logger$2.Warn("Could not end XR session.")
        })) : Promise.resolve()
    }
    ,
    i.prototype.getRenderTargetTextureForEye = function(e) {
        return this._rttProvider.getRenderTargetForEye(e)
    }
    ,
    i.prototype.getWebXRRenderTarget = function(e) {
        var t = this.scene.getEngine();
        return this._xrNavigator.xr.native ? this._xrNavigator.xr.getWebXRRenderTarget(t) : (e = e || WebXRManagedOutputCanvasOptions.GetDefaults(t),
        e.canvasElement = e.canvasElement || t.getRenderingCanvas() || void 0,
        new WebXRManagedOutputCanvas(this,e))
    }
    ,
    i.prototype.initializeAsync = function() {
        return this._xrNavigator = navigator,
        this._xrNavigator.xr ? Promise.resolve() : Promise.reject("WebXR not available")
    }
    ,
    i.prototype.initializeSessionAsync = function(e, t) {
        var r = this;
        return e === void 0 && (e = "immersive-vr"),
        t === void 0 && (t = {}),
        this._xrNavigator.xr.requestSession(e, t).then(function(n) {
            return r.session = n,
            r._sessionMode = e,
            r.onXRSessionInit.notifyObservers(n),
            r._sessionEnded = !1,
            r.session.addEventListener("end", function() {
                r._sessionEnded = !0,
                r.onXRSessionEnded.notifyObservers(null),
                r._rttProvider = null,
                r._engine && (r._engine.framebufferDimensionsObject = null,
                r._engine.restoreDefaultFramebuffer(),
                r._engine.customAnimationFrameRequester = null,
                r._engine._renderLoop()),
                r.isNative && (r._renderTargetTextures.forEach(function(o) {
                    return o.dispose()
                }),
                r._renderTargetTextures.length = 0)
            }, {
                once: !0
            }),
            r.session
        })
    }
    ,
    i.prototype.isSessionSupportedAsync = function(e) {
        return i.IsSessionSupportedAsync(e)
    }
    ,
    i.prototype.resetReferenceSpace = function() {
        this.referenceSpace = this.baseReferenceSpace
    }
    ,
    i.prototype.runXRRenderLoop = function() {
        var e = this;
        if (!(this._sessionEnded || !this._engine)) {
            if (this._engine.customAnimationFrameRequester = {
                requestAnimationFrame: this.session.requestAnimationFrame.bind(this.session),
                renderFunction: function(a, s) {
                    e._sessionEnded || !e._engine || (e.currentFrame = s,
                    e.currentTimestamp = a,
                    s && (e._engine.framebufferDimensionsObject = e._baseLayer,
                    e.onXRFrameObservable.notifyObservers(s),
                    e._engine._renderLoop(),
                    e._engine.framebufferDimensionsObject = null))
                }
            },
            this._xrNavigator.xr.native)
                this._rttProvider = this._xrNavigator.xr.getNativeRenderTargetProvider(this.session, this._createRenderTargetTexture.bind(this), this._destroyRenderTargetTexture.bind(this));
            else {
                var t, r, n, o;
                this._rttProvider = {
                    getRenderTargetForEye: function() {
                        var a = e._baseLayer;
                        return (a.framebufferWidth !== r || a.framebufferHeight !== n || a.framebuffer !== o) && (t = e._createRenderTargetTexture(a.framebufferWidth, a.framebufferHeight, a.framebuffer),
                        r = a.framebufferWidth,
                        n = a.framebufferHeight,
                        o = a.framebuffer),
                        t
                    }
                },
                this._engine.framebufferDimensionsObject = this._baseLayer
            }
            typeof window != "undefined" && window.cancelAnimationFrame && window.cancelAnimationFrame(this._engine._frameHandler),
            this._engine._renderLoop()
        }
    }
    ,
    i.prototype.setReferenceSpaceTypeAsync = function(e) {
        var t = this;
        return e === void 0 && (e = "local-floor"),
        this.session.requestReferenceSpace(e).then(function(r) {
            return r
        }, function(r) {
            return Logger$2.Error("XR.requestReferenceSpace failed for the following reason: "),
            Logger$2.Error(r),
            Logger$2.Log('Defaulting to universally-supported "viewer" reference space type.'),
            t.session.requestReferenceSpace("viewer").then(function(n) {
                var o = new XRRigidTransform({
                    x: 0,
                    y: -t.defaultHeightCompensation,
                    z: 0
                });
                return n.getOffsetReferenceSpace(o)
            }, function(n) {
                throw Logger$2.Error(n),
                'XR initialization failed: required "viewer" reference space type not supported.'
            })
        }).then(function(r) {
            return t.session.requestReferenceSpace("viewer").then(function(n) {
                return t.viewerReferenceSpace = n,
                r
            })
        }).then(function(r) {
            return t.referenceSpace = t.baseReferenceSpace = r,
            t.referenceSpace
        })
    }
    ,
    i.prototype.updateRenderStateAsync = function(e) {
        return e.baseLayer && (this._baseLayer = e.baseLayer),
        this.session.updateRenderState(e)
    }
    ,
    i.IsSessionSupportedAsync = function(e) {
        if (!navigator.xr)
            return Promise.resolve(!1);
        var t = navigator.xr.isSessionSupported || navigator.xr.supportsSession;
        return t ? t.call(navigator.xr, e).then(function(r) {
            var n = typeof r == "undefined" ? !0 : r;
            return Promise.resolve(n)
        }).catch(function(r) {
            return Logger$2.Warn(r),
            Promise.resolve(!1)
        }) : Promise.resolve(!1)
    }
    ,
    Object.defineProperty(i.prototype, "isNative", {
        get: function() {
            var e;
            return (e = this._xrNavigator.xr.native) !== null && e !== void 0 ? e : !1
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "currentFrameRate", {
        get: function() {
            var e;
            return (e = this.session) === null || e === void 0 ? void 0 : e.frameRate
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "supportedFrameRates", {
        get: function() {
            var e;
            return (e = this.session) === null || e === void 0 ? void 0 : e.supportedFrameRates
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.updateTargetFrameRate = function(e) {
        return this.session.updateTargetFrameRate(e)
    }
    ,
    Object.defineProperty(i.prototype, "isFixedFoveationSupported", {
        get: function() {
            var e;
            return !!(!((e = this._baseLayer) === null || e === void 0) && e.fixedFoveation) !== null
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "fixedFoveation", {
        get: function() {
            var e;
            return ((e = this._baseLayer) === null || e === void 0 ? void 0 : e.fixedFoveation) !== void 0 ? this._baseLayer.fixedFoveation : null
        },
        set: function(e) {
            var t, r = Math.max(0, Math.min(1, e || 0));
            ((t = this._baseLayer) === null || t === void 0 ? void 0 : t.fixedFoveation) !== void 0 && (this._baseLayer.fixedFoveation = r)
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype._createRenderTargetTexture = function(e, t, r) {
        if (!this._engine)
            throw new Error("Engine is disposed");
        var n = new InternalTexture(this._engine,InternalTextureSource.Unknown,!0);
        n.width = e,
        n.height = t;
        var o = new RenderTargetTexture("XR renderTargetTexture",{
            width: e,
            height: t
        },this.scene)
          , a = o.renderTarget;
        return a.setTexture(n, 0),
        a._framebuffer = r,
        o._texture = n,
        o.disableRescaling(),
        o.skipInitialClear = !0,
        this._renderTargetTextures.push(o),
        o
    }
    ,
    i.prototype._destroyRenderTargetTexture = function(e) {
        this._renderTargetTextures.splice(this._renderTargetTextures.indexOf(e), 1),
        e.dispose()
    }
    ,
    i
}(), WebXRState;
(function(i) {
    i[i.ENTERING_XR = 0] = "ENTERING_XR",
    i[i.EXITING_XR = 1] = "EXITING_XR",
    i[i.IN_XR = 2] = "IN_XR",
    i[i.NOT_IN_XR = 3] = "NOT_IN_XR"
}
)(WebXRState || (WebXRState = {}));
var WebXRTrackingState;
(function(i) {
    i[i.NOT_TRACKING = 0] = "NOT_TRACKING",
    i[i.TRACKING_LOST = 1] = "TRACKING_LOST",
    i[i.TRACKING = 2] = "TRACKING"
}
)(WebXRTrackingState || (WebXRTrackingState = {}));
var VRExperienceHelperGazer = function() {
    function i(e, t) {
        if (t === void 0 && (t = null),
        this.scene = e,
        this._pointerDownOnMeshAsked = !1,
        this._isActionableMesh = !1,
        this._teleportationRequestInitiated = !1,
        this._teleportationBackRequestInitiated = !1,
        this._rotationRightAsked = !1,
        this._rotationLeftAsked = !1,
        this._dpadPressed = !0,
        this._activePointer = !1,
        this._id = i._idCounter++,
        t)
            this._gazeTracker = t.clone("gazeTracker");
        else {
            this._gazeTracker = CreateTorus("gazeTracker", {
                diameter: .0035,
                thickness: .0025,
                tessellation: 20,
                updatable: !1
            }, e),
            this._gazeTracker.bakeCurrentTransformIntoVertices(),
            this._gazeTracker.isPickable = !1,
            this._gazeTracker.isVisible = !1;
            var r = new StandardMaterial("targetMat",e);
            r.specularColor = Color3.Black(),
            r.emissiveColor = new Color3(.7,.7,.7),
            r.backFaceCulling = !1,
            this._gazeTracker.material = r
        }
    }
    return i.prototype._getForwardRay = function(e) {
        return new Ray(Vector3.Zero(),new Vector3(0,0,e))
    }
    ,
    i.prototype._selectionPointerDown = function() {
        this._pointerDownOnMeshAsked = !0,
        this._currentHit && this.scene.simulatePointerDown(this._currentHit, {
            pointerId: this._id
        })
    }
    ,
    i.prototype._selectionPointerUp = function() {
        this._currentHit && this.scene.simulatePointerUp(this._currentHit, {
            pointerId: this._id
        }),
        this._pointerDownOnMeshAsked = !1
    }
    ,
    i.prototype._activatePointer = function() {
        this._activePointer = !0
    }
    ,
    i.prototype._deactivatePointer = function() {
        this._activePointer = !1
    }
    ,
    i.prototype._updatePointerDistance = function(e) {}
    ,
    i.prototype.dispose = function() {
        this._interactionsEnabled = !1,
        this._teleportationEnabled = !1,
        this._gazeTracker && this._gazeTracker.dispose()
    }
    ,
    i._idCounter = 0,
    i
}()
  , VRExperienceHelperControllerGazer = function(i) {
    __extends(e, i);
    function e(t, r, n) {
        var o = i.call(this, r, n) || this;
        o.webVRController = t,
        o._laserPointer = CreateCylinder("laserPointer", {
            updatable: !1,
            height: 1,
            diameterTop: .004,
            diameterBottom: 2e-4,
            tessellation: 20,
            subdivisions: 1
        }, r);
        var a = new StandardMaterial("laserPointerMat",r);
        if (a.emissiveColor = new Color3(.7,.7,.7),
        a.alpha = .6,
        o._laserPointer.material = a,
        o._laserPointer.rotation.x = Math.PI / 2,
        o._laserPointer.position.z = -.5,
        o._laserPointer.isVisible = !1,
        o._laserPointer.isPickable = !1,
        !t.mesh) {
            var s = new Mesh("preloadControllerMesh",r)
              , l = new Mesh(PoseEnabledController.POINTING_POSE,r);
            l.rotation.x = -.7,
            s.addChild(l),
            t.attachToMesh(s)
        }
        return o._setLaserPointerParent(t.mesh),
        o._meshAttachedObserver = t._meshAttachedObservable.add(function(u) {
            o._setLaserPointerParent(u)
        }),
        o
    }
    return e.prototype._getForwardRay = function(t) {
        return this.webVRController.getForwardRay(t)
    }
    ,
    e.prototype._activatePointer = function() {
        i.prototype._activatePointer.call(this),
        this._laserPointer.isVisible = !0
    }
    ,
    e.prototype._deactivatePointer = function() {
        i.prototype._deactivatePointer.call(this),
        this._laserPointer.isVisible = !1
    }
    ,
    e.prototype._setLaserPointerColor = function(t) {
        this._laserPointer.material.emissiveColor = t
    }
    ,
    e.prototype._setLaserPointerLightingDisabled = function(t) {
        this._laserPointer.material.disableLighting = t
    }
    ,
    e.prototype._setLaserPointerParent = function(t) {
        var r = function(s) {
            s.isPickable = !1,
            s.getChildMeshes().forEach(function(l) {
                r(l)
            })
        };
        r(t);
        var n = t.getChildren(void 0, !1)
          , o = t;
        this.webVRController._pointingPoseNode = null;
        for (var a = 0; a < n.length; a++)
            if (n[a].name && n[a].name.indexOf(PoseEnabledController.POINTING_POSE) >= 0) {
                o = n[a],
                this.webVRController._pointingPoseNode = o;
                break
            }
        this._laserPointer.parent = o
    }
    ,
    e.prototype._updatePointerDistance = function(t) {
        t === void 0 && (t = 100),
        this._laserPointer.scaling.y = t,
        this._laserPointer.position.z = -t / 2
    }
    ,
    e.prototype.dispose = function() {
        i.prototype.dispose.call(this),
        this._laserPointer.dispose(),
        this._meshAttachedObserver && this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver)
    }
    ,
    e
}(VRExperienceHelperGazer)
  , VRExperienceHelperCameraGazer = function(i) {
    __extends(e, i);
    function e(t, r) {
        var n = i.call(this, r) || this;
        return n.getCamera = t,
        n
    }
    return e.prototype._getForwardRay = function(t) {
        var r = this.getCamera();
        return r ? r.getForwardRay(t) : new Ray(Vector3.Zero(),Vector3.Forward())
    }
    ,
    e
}(VRExperienceHelperGazer)
  , VRExperienceHelper = function() {
    function i(e, t) {
        var r = this;
        t === void 0 && (t = {}),
        this.webVROptions = t,
        this._webVRsupported = !1,
        this._webVRready = !1,
        this._webVRrequesting = !1,
        this._webVRpresenting = !1,
        this._fullscreenVRpresenting = !1,
        this.enableGazeEvenWhenNoPointerLock = !1,
        this.exitVROnDoubleTap = !0,
        this.onEnteringVRObservable = new Observable,
        this.onAfterEnteringVRObservable = new Observable,
        this.onExitingVRObservable = new Observable,
        this.onControllerMeshLoadedObservable = new Observable,
        this._useCustomVRButton = !1,
        this._teleportationRequested = !1,
        this._teleportActive = !1,
        this._floorMeshesCollection = [],
        this._teleportationMode = i.TELEPORTATIONMODE_CONSTANTTIME,
        this._teleportationTime = 122,
        this._teleportationSpeed = 20,
        this._rotationAllowed = !0,
        this._teleportBackwardsVector = new Vector3(0,-1,-1),
        this._isDefaultTeleportationTarget = !0,
        this._teleportationFillColor = "#444444",
        this._teleportationBorderColor = "#FFFFFF",
        this._rotationAngle = 0,
        this._haloCenter = new Vector3(0,0,0),
        this._padSensibilityUp = .65,
        this._padSensibilityDown = .35,
        this._leftController = null,
        this._rightController = null,
        this._gazeColor = new Color3(.7,.7,.7),
        this._laserColor = new Color3(.7,.7,.7),
        this._pickedLaserColor = new Color3(.2,.2,1),
        this._pickedGazeColor = new Color3(0,0,1),
        this.onNewMeshSelected = new Observable,
        this.onMeshSelectedWithController = new Observable,
        this.onNewMeshPicked = new Observable,
        this.onBeforeCameraTeleport = new Observable,
        this.onAfterCameraTeleport = new Observable,
        this.onSelectedMeshUnselected = new Observable,
        this.teleportationEnabled = !0,
        this._teleportationInitialized = !1,
        this._interactionsEnabled = !1,
        this._interactionsRequested = !1,
        this._displayGaze = !0,
        this._displayLaserPointer = !0,
        this.updateGazeTrackerScale = !0,
        this.updateGazeTrackerColor = !0,
        this.updateControllerLaserColor = !0,
        this.requestPointerLockOnFullScreen = !0,
        this.xrTestDone = !1,
        this._onResize = function() {
            r.moveButtonToBottomRight(),
            r._fullscreenVRpresenting && r._webVRready && r.exitVR()
        }
        ,
        this._onFullscreenChange = function() {
            var a = document;
            a.fullscreen !== void 0 ? r._fullscreenVRpresenting = document.fullscreen : a.mozFullScreen !== void 0 ? r._fullscreenVRpresenting = a.mozFullScreen : a.webkitIsFullScreen !== void 0 ? r._fullscreenVRpresenting = a.webkitIsFullScreen : a.msIsFullScreen !== void 0 ? r._fullscreenVRpresenting = a.msIsFullScreen : document.msFullscreenElement !== void 0 && (r._fullscreenVRpresenting = document.msFullscreenElement),
            !r._fullscreenVRpresenting && r._inputElement && (r.exitVR(),
            !r._useCustomVRButton && r._btnVR && (r._btnVR.style.top = r._inputElement.offsetTop + r._inputElement.offsetHeight - 70 + "px",
            r._btnVR.style.left = r._inputElement.offsetLeft + r._inputElement.offsetWidth - 100 + "px",
            r.updateButtonVisibility()))
        }
        ,
        this._cachedAngularSensibility = {
            angularSensibilityX: null,
            angularSensibilityY: null,
            angularSensibility: null
        },
        this.beforeRender = function() {
            r._leftController && r._leftController._activePointer && r._castRayAndSelectObject(r._leftController),
            r._rightController && r._rightController._activePointer && r._castRayAndSelectObject(r._rightController),
            r._noControllerIsActive && (r._scene.getEngine().isPointerLock || r.enableGazeEvenWhenNoPointerLock) ? r._castRayAndSelectObject(r._cameraGazer) : r._cameraGazer._gazeTracker.isVisible = !1
        }
        ,
        this._onNewGamepadConnected = function(a) {
            if (a.type !== Gamepad.POSE_ENABLED)
                a.leftStick && a.onleftstickchanged(function(u) {
                    r._teleportationInitialized && r.teleportationEnabled && (!r._leftController && !r._rightController || r._leftController && !r._leftController._activePointer && r._rightController && !r._rightController._activePointer) && (r._checkTeleportWithRay(u, r._cameraGazer),
                    r._checkTeleportBackwards(u, r._cameraGazer))
                }),
                a.rightStick && a.onrightstickchanged(function(u) {
                    r._teleportationInitialized && r._checkRotate(u, r._cameraGazer)
                }),
                a.type === Gamepad.XBOX && (a.onbuttondown(function(u) {
                    r._interactionsEnabled && u === Xbox360Button.A && r._cameraGazer._selectionPointerDown()
                }),
                a.onbuttonup(function(u) {
                    r._interactionsEnabled && u === Xbox360Button.A && r._cameraGazer._selectionPointerUp()
                }));
            else {
                var s = a
                  , l = new VRExperienceHelperControllerGazer(s,r._scene,r._cameraGazer._gazeTracker);
                s.hand === "right" || r._leftController && r._leftController.webVRController != s ? r._rightController = l : r._leftController = l,
                r._tryEnableInteractionOnController(l)
            }
        }
        ,
        this._tryEnableInteractionOnController = function(a) {
            r._interactionsRequested && !a._interactionsEnabled && r._enableInteractionOnController(a),
            r._teleportationRequested && !a._teleportationEnabled && r._enableTeleportationOnController(a)
        }
        ,
        this._onNewGamepadDisconnected = function(a) {
            a instanceof WebVRController && (a.hand === "left" && r._leftController != null && (r._leftController.dispose(),
            r._leftController = null),
            a.hand === "right" && r._rightController != null && (r._rightController.dispose(),
            r._rightController = null))
        }
        ,
        this._workingVector = Vector3.Zero(),
        this._workingQuaternion = Quaternion.Identity(),
        this._workingMatrix = Matrix.Identity(),
        Logger$2.Warn("WebVR is deprecated. Please avoid using this experience helper and use the WebXR experience helper instead"),
        this._scene = e,
        this._inputElement = e.getEngine().getInputElement();
        var n = "getVRDisplays"in navigator;
        if (!n && t.useXR === void 0 && (t.useXR = !0),
        t.createFallbackVRDeviceOrientationFreeCamera === void 0 && (t.createFallbackVRDeviceOrientationFreeCamera = !0),
        t.createDeviceOrientationCamera === void 0 && (t.createDeviceOrientationCamera = !0),
        t.laserToggle === void 0 && (t.laserToggle = !0),
        t.defaultHeight === void 0 && (t.defaultHeight = 1.7),
        t.useCustomVRButton && (this._useCustomVRButton = !0,
        t.customVRButton && (this._btnVR = t.customVRButton)),
        t.rayLength && (this._rayLength = t.rayLength),
        this._defaultHeight = t.defaultHeight,
        t.positionScale && (this._rayLength *= t.positionScale,
        this._defaultHeight *= t.positionScale),
        this._hasEnteredVR = !1,
        this._scene.activeCamera ? this._position = this._scene.activeCamera.position.clone() : this._position = new Vector3(0,this._defaultHeight,0),
        t.createDeviceOrientationCamera || !this._scene.activeCamera) {
            if (this._deviceOrientationCamera = new DeviceOrientationCamera("deviceOrientationVRHelper",this._position.clone(),e),
            this._scene.activeCamera && (this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ,
            this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ,
            this._scene.activeCamera instanceof TargetCamera && this._scene.activeCamera.rotation)) {
                var o = this._scene.activeCamera;
                o.rotationQuaternion ? this._deviceOrientationCamera.rotationQuaternion.copyFrom(o.rotationQuaternion) : this._deviceOrientationCamera.rotationQuaternion.copyFrom(Quaternion.RotationYawPitchRoll(o.rotation.y, o.rotation.x, o.rotation.z)),
                this._deviceOrientationCamera.rotation = o.rotation.clone()
            }
            this._scene.activeCamera = this._deviceOrientationCamera,
            this._inputElement && this._scene.activeCamera.attachControl()
        } else
            this._existingCamera = this._scene.activeCamera;
        this.webVROptions.useXR && navigator.xr ? WebXRSessionManager.IsSessionSupportedAsync("immersive-vr").then(function(a) {
            a ? (Logger$2.Log("Using WebXR. It is recommended to use the WebXRDefaultExperience directly"),
            e.createDefaultXRExperienceAsync({
                floorMeshes: t.floorMeshes || []
            }).then(function(s) {
                r.xr = s,
                r.xrTestDone = !0,
                r._cameraGazer = new VRExperienceHelperCameraGazer(function() {
                    return r.xr.baseExperience.camera
                }
                ,e),
                r.xr.baseExperience.onStateChangedObservable.add(function(l) {
                    switch (l) {
                    case WebXRState.ENTERING_XR:
                        r.onEnteringVRObservable.notifyObservers(r),
                        r._interactionsEnabled || r.xr.pointerSelection.detach(),
                        r.xr.pointerSelection.displayLaserPointer = r._displayLaserPointer;
                        break;
                    case WebXRState.EXITING_XR:
                        r.onExitingVRObservable.notifyObservers(r),
                        r._scene.getEngine().resize();
                        break;
                    case WebXRState.IN_XR:
                        r._hasEnteredVR = !0;
                        break;
                    case WebXRState.NOT_IN_XR:
                        r._hasEnteredVR = !1;
                        break
                    }
                })
            })) : r.completeVRInit(e, t)
        }) : this.completeVRInit(e, t)
    }
    return Object.defineProperty(i.prototype, "onEnteringVR", {
        get: function() {
            return this.onEnteringVRObservable
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "onExitingVR", {
        get: function() {
            return this.onExitingVRObservable
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "onControllerMeshLoaded", {
        get: function() {
            return this.onControllerMeshLoadedObservable
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "teleportationTarget", {
        get: function() {
            return this._teleportationTarget
        },
        set: function(e) {
            e && (e.name = "teleportationTarget",
            this._isDefaultTeleportationTarget = !1,
            this._teleportationTarget = e)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "gazeTrackerMesh", {
        get: function() {
            return this._cameraGazer._gazeTracker
        },
        set: function(e) {
            e && (this._cameraGazer._gazeTracker && this._cameraGazer._gazeTracker.dispose(),
            this._leftController && this._leftController._gazeTracker && this._leftController._gazeTracker.dispose(),
            this._rightController && this._rightController._gazeTracker && this._rightController._gazeTracker.dispose(),
            this._cameraGazer._gazeTracker = e,
            this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices(),
            this._cameraGazer._gazeTracker.isPickable = !1,
            this._cameraGazer._gazeTracker.isVisible = !1,
            this._cameraGazer._gazeTracker.name = "gazeTracker",
            this._leftController && (this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker")),
            this._rightController && (this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker")))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "leftControllerGazeTrackerMesh", {
        get: function() {
            return this._leftController ? this._leftController._gazeTracker : null
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "rightControllerGazeTrackerMesh", {
        get: function() {
            return this._rightController ? this._rightController._gazeTracker : null
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "displayGaze", {
        get: function() {
            return this._displayGaze
        },
        set: function(e) {
            this._displayGaze = e,
            e || (this._cameraGazer._gazeTracker.isVisible = !1,
            this._leftController && (this._leftController._gazeTracker.isVisible = !1),
            this._rightController && (this._rightController._gazeTracker.isVisible = !1))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "displayLaserPointer", {
        get: function() {
            return this._displayLaserPointer
        },
        set: function(e) {
            this._displayLaserPointer = e,
            e ? (this._rightController && this._rightController._activatePointer(),
            this._leftController && this._leftController._activatePointer()) : (this._rightController && (this._rightController._deactivatePointer(),
            this._rightController._gazeTracker.isVisible = !1),
            this._leftController && (this._leftController._deactivatePointer(),
            this._leftController._gazeTracker.isVisible = !1))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "deviceOrientationCamera", {
        get: function() {
            return this._deviceOrientationCamera
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "currentVRCamera", {
        get: function() {
            return this._webVRready ? this._webVRCamera : this._scene.activeCamera
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "webVRCamera", {
        get: function() {
            return this._webVRCamera
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "vrDeviceOrientationCamera", {
        get: function() {
            return this._vrDeviceOrientationCamera
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "vrButton", {
        get: function() {
            return this._btnVR
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "_teleportationRequestInitiated", {
        get: function() {
            var e = this._cameraGazer._teleportationRequestInitiated || this._leftController !== null && this._leftController._teleportationRequestInitiated || this._rightController !== null && this._rightController._teleportationRequestInitiated;
            return e
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.completeVRInit = function(e, t) {
        var r = this;
        if (this.xrTestDone = !0,
        t.createFallbackVRDeviceOrientationFreeCamera && (t.useMultiview && (t.vrDeviceOrientationCameraMetrics || (t.vrDeviceOrientationCameraMetrics = VRCameraMetrics.GetDefault()),
        t.vrDeviceOrientationCameraMetrics.multiviewEnabled = !0),
        this._vrDeviceOrientationCamera = new VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper",this._position,this._scene,!0,t.vrDeviceOrientationCameraMetrics),
        this._vrDeviceOrientationCamera.angularSensibility = Number.MAX_VALUE),
        this._webVRCamera = new WebVRFreeCamera("WebVRHelper",this._position,this._scene,t),
        this._webVRCamera.useStandingMatrix(),
        this._cameraGazer = new VRExperienceHelperCameraGazer(function() {
            return r.currentVRCamera
        }
        ,e),
        !this._useCustomVRButton) {
            this._btnVR = document.createElement("BUTTON"),
            this._btnVR.className = "babylonVRicon",
            this._btnVR.id = "babylonVRiconbtn",
            this._btnVR.title = "Click to switch to VR";
            var n = window.SVGSVGElement ? "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" : "https://cdn.babylonjs.com/Assets/vrButton.png"
              , o = ".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url(" + n + "); 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) }";
            o += ".babylonVRicon.vrdisplaypresenting { display: none; }";
            var a = document.createElement("style");
            a.appendChild(document.createTextNode(o)),
            document.getElementsByTagName("head")[0].appendChild(a),
            this.moveButtonToBottomRight()
        }
        this._btnVR && this._btnVR.addEventListener("click", function() {
            r.isInVRMode ? r._scene.getEngine().disableVR() : r.enterVR()
        });
        var s = this._scene.getEngine().getHostWindow();
        !s || (s.addEventListener("resize", this._onResize),
        document.addEventListener("fullscreenchange", this._onFullscreenChange, !1),
        document.addEventListener("mozfullscreenchange", this._onFullscreenChange, !1),
        document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, !1),
        document.addEventListener("msfullscreenchange", this._onFullscreenChange, !1),
        document.onmsfullscreenchange = this._onFullscreenChange,
        t.createFallbackVRDeviceOrientationFreeCamera ? this.displayVRButton() : this._scene.getEngine().onVRDisplayChangedObservable.add(function(l) {
            l.vrDisplay && r.displayVRButton()
        }),
        this._onKeyDown = function(l) {
            l.keyCode === 27 && r.isInVRMode && r.exitVR()
        }
        ,
        document.addEventListener("keydown", this._onKeyDown),
        this._scene.onPrePointerObservable.add(function() {
            r._hasEnteredVR && r.exitVROnDoubleTap && (r.exitVR(),
            r._fullscreenVRpresenting && r._scene.getEngine().exitFullscreen())
        }, PointerEventTypes.POINTERDOUBLETAP, !1),
        this._onVRDisplayChanged = function(l) {
            return r.onVRDisplayChanged(l)
        }
        ,
        this._onVrDisplayPresentChange = function() {
            return r.onVrDisplayPresentChange()
        }
        ,
        this._onVRRequestPresentStart = function() {
            r._webVRrequesting = !0,
            r.updateButtonVisibility()
        }
        ,
        this._onVRRequestPresentComplete = function() {
            r._webVRrequesting = !1,
            r.updateButtonVisibility()
        }
        ,
        e.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged),
        e.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart),
        e.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete),
        s.addEventListener("vrdisplaypresentchange", this._onVrDisplayPresentChange),
        e.onDisposeObservable.add(function() {
            r.dispose()
        }),
        this._webVRCamera.onControllerMeshLoadedObservable.add(function(l) {
            return r._onDefaultMeshLoaded(l)
        }),
        this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected),
        this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected),
        this.updateButtonVisibility(),
        this._circleEase = new CircleEase,
        this._circleEase.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT),
        this._teleportationEasing = this._circleEase,
        e.onPointerObservable.add(function(l) {
            r._interactionsEnabled && e.activeCamera === r.vrDeviceOrientationCamera && l.event.pointerType === "mouse" && (l.type === PointerEventTypes.POINTERDOWN ? r._cameraGazer._selectionPointerDown() : l.type === PointerEventTypes.POINTERUP && r._cameraGazer._selectionPointerUp())
        }),
        this.webVROptions.floorMeshes && this.enableTeleportation({
            floorMeshes: this.webVROptions.floorMeshes
        }))
    }
    ,
    i.prototype._onDefaultMeshLoaded = function(e) {
        this._leftController && this._leftController.webVRController == e && e.mesh && this._leftController._setLaserPointerParent(e.mesh),
        this._rightController && this._rightController.webVRController == e && e.mesh && this._rightController._setLaserPointerParent(e.mesh);
        try {
            this.onControllerMeshLoadedObservable.notifyObservers(e)
        } catch (t) {
            Logger$2.Warn("Error in your custom logic onControllerMeshLoaded: " + t)
        }
    }
    ,
    Object.defineProperty(i.prototype, "isInVRMode", {
        get: function() {
            return this.xr && this.webVROptions.useXR && this.xr.baseExperience.state === WebXRState.IN_XR || this._webVRpresenting || this._fullscreenVRpresenting
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.onVrDisplayPresentChange = function() {
        var e = this._scene.getEngine().getVRDevice();
        if (e) {
            var t = this._webVRpresenting;
            this._webVRpresenting = e.isPresenting,
            t && !this._webVRpresenting && this.exitVR()
        } else
            Logger$2.Warn("Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?");
        this.updateButtonVisibility()
    }
    ,
    i.prototype.onVRDisplayChanged = function(e) {
        this._webVRsupported = e.vrSupported,
        this._webVRready = !!e.vrDisplay,
        this._webVRpresenting = e.vrDisplay && e.vrDisplay.isPresenting,
        this.updateButtonVisibility()
    }
    ,
    i.prototype.moveButtonToBottomRight = function() {
        if (this._inputElement && !this._useCustomVRButton && this._btnVR) {
            var e = this._inputElement.getBoundingClientRect();
            this._btnVR.style.top = e.top + e.height - 70 + "px",
            this._btnVR.style.left = e.left + e.width - 100 + "px"
        }
    }
    ,
    i.prototype.displayVRButton = function() {
        !this._useCustomVRButton && !this._btnVRDisplayed && this._btnVR && (document.body.appendChild(this._btnVR),
        this._btnVRDisplayed = !0)
    }
    ,
    i.prototype.updateButtonVisibility = function() {
        !this._btnVR || this._useCustomVRButton || (this._btnVR.className = "babylonVRicon",
        this.isInVRMode ? this._btnVR.className += " vrdisplaypresenting" : (this._webVRready && (this._btnVR.className += " vrdisplayready"),
        this._webVRsupported && (this._btnVR.className += " vrdisplaysupported"),
        this._webVRrequesting && (this._btnVR.className += " vrdisplayrequesting")))
    }
    ,
    i.prototype.enterVR = function() {
        var e = this;
        if (this.xr) {
            this.xr.baseExperience.enterXRAsync("immersive-vr", "local-floor", this.xr.renderTarget);
            return
        }
        if (this.onEnteringVRObservable)
            try {
                this.onEnteringVRObservable.notifyObservers(this)
            } catch (a) {
                Logger$2.Warn("Error in your custom logic onEnteringVR: " + a)
            }
        if (this._scene.activeCamera) {
            if (this._position = this._scene.activeCamera.position.clone(),
            this.vrDeviceOrientationCamera && (this.vrDeviceOrientationCamera.rotation = Quaternion.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles(),
            this.vrDeviceOrientationCamera.angularSensibility = 2e3),
            this.webVRCamera) {
                var t = this.webVRCamera.deviceRotationQuaternion.toEulerAngles().y
                  , r = Quaternion.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles().y
                  , n = r - t
                  , o = this.webVRCamera.rotationQuaternion.toEulerAngles().y;
                this.webVRCamera.rotationQuaternion = Quaternion.FromEulerAngles(0, o + n, 0)
            }
            this._existingCamera = this._scene.activeCamera,
            this._existingCamera.angularSensibilityX && (this._cachedAngularSensibility.angularSensibilityX = this._existingCamera.angularSensibilityX,
            this._existingCamera.angularSensibilityX = Number.MAX_VALUE),
            this._existingCamera.angularSensibilityY && (this._cachedAngularSensibility.angularSensibilityY = this._existingCamera.angularSensibilityY,
            this._existingCamera.angularSensibilityY = Number.MAX_VALUE),
            this._existingCamera.angularSensibility && (this._cachedAngularSensibility.angularSensibility = this._existingCamera.angularSensibility,
            this._existingCamera.angularSensibility = Number.MAX_VALUE)
        }
        this._webVRrequesting || (this._webVRready ? this._webVRpresenting || (this._scene.getEngine().onVRRequestPresentComplete.addOnce(function(a) {
            e.onAfterEnteringVRObservable.notifyObservers({
                success: a
            })
        }),
        this._webVRCamera.position = this._position,
        this._scene.activeCamera = this._webVRCamera) : this._vrDeviceOrientationCamera && (this._vrDeviceOrientationCamera.position = this._position,
        this._scene.activeCamera && (this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ),
        this._scene.activeCamera = this._vrDeviceOrientationCamera,
        this._scene.getEngine().enterFullscreen(this.requestPointerLockOnFullScreen),
        this.updateButtonVisibility(),
        this._vrDeviceOrientationCamera.onViewMatrixChangedObservable.addOnce(function() {
            e.onAfterEnteringVRObservable.notifyObservers({
                success: !0
            })
        })),
        this._scene.activeCamera && this._inputElement && this._scene.activeCamera.attachControl(),
        this._interactionsEnabled && this._scene.registerBeforeRender(this.beforeRender),
        this._displayLaserPointer && [this._leftController, this._rightController].forEach(function(a) {
            a && a._activatePointer()
        }),
        this._hasEnteredVR = !0)
    }
    ,
    i.prototype.exitVR = function() {
        if (this.xr) {
            this.xr.baseExperience.exitXRAsync();
            return
        }
        if (this._hasEnteredVR) {
            if (this.onExitingVRObservable)
                try {
                    this.onExitingVRObservable.notifyObservers(this)
                } catch (t) {
                    Logger$2.Warn("Error in your custom logic onExitingVR: " + t)
                }
            this._webVRpresenting && this._scene.getEngine().disableVR(),
            this._scene.activeCamera && (this._position = this._scene.activeCamera.position.clone()),
            this.vrDeviceOrientationCamera && (this.vrDeviceOrientationCamera.angularSensibility = Number.MAX_VALUE),
            this._deviceOrientationCamera ? (this._deviceOrientationCamera.position = this._position,
            this._scene.activeCamera = this._deviceOrientationCamera,
            this._cachedAngularSensibility.angularSensibilityX && (this._deviceOrientationCamera.angularSensibilityX = this._cachedAngularSensibility.angularSensibilityX,
            this._cachedAngularSensibility.angularSensibilityX = null),
            this._cachedAngularSensibility.angularSensibilityY && (this._deviceOrientationCamera.angularSensibilityY = this._cachedAngularSensibility.angularSensibilityY,
            this._cachedAngularSensibility.angularSensibilityY = null),
            this._cachedAngularSensibility.angularSensibility && (this._deviceOrientationCamera.angularSensibility = this._cachedAngularSensibility.angularSensibility,
            this._cachedAngularSensibility.angularSensibility = null)) : this._existingCamera && (this._existingCamera.position = this._position,
            this._scene.activeCamera = this._existingCamera,
            this._inputElement && this._scene.activeCamera.attachControl(),
            this._cachedAngularSensibility.angularSensibilityX && (this._existingCamera.angularSensibilityX = this._cachedAngularSensibility.angularSensibilityX,
            this._cachedAngularSensibility.angularSensibilityX = null),
            this._cachedAngularSensibility.angularSensibilityY && (this._existingCamera.angularSensibilityY = this._cachedAngularSensibility.angularSensibilityY,
            this._cachedAngularSensibility.angularSensibilityY = null),
            this._cachedAngularSensibility.angularSensibility && (this._existingCamera.angularSensibility = this._cachedAngularSensibility.angularSensibility,
            this._cachedAngularSensibility.angularSensibility = null)),
            this.updateButtonVisibility(),
            this._interactionsEnabled && (this._scene.unregisterBeforeRender(this.beforeRender),
            this._cameraGazer._gazeTracker.isVisible = !1,
            this._leftController && (this._leftController._gazeTracker.isVisible = !1),
            this._rightController && (this._rightController._gazeTracker.isVisible = !1)),
            this._scene.getEngine().resize(),
            [this._leftController, this._rightController].forEach(function(t) {
                t && t._deactivatePointer()
            }),
            this._hasEnteredVR = !1;
            var e = this._scene.getEngine();
            e._onVrDisplayPresentChange && e._onVrDisplayPresentChange()
        }
    }
    ,
    Object.defineProperty(i.prototype, "position", {
        get: function() {
            return this._position
        },
        set: function(e) {
            this._position = e,
            this._scene.activeCamera && (this._scene.activeCamera.position = e)
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.enableInteractions = function() {
        var e = this;
        if (!this._interactionsEnabled) {
            if (this._interactionsRequested = !0,
            this.xr) {
                this.xr.baseExperience.state === WebXRState.IN_XR && this.xr.pointerSelection.attach();
                return
            }
            this._leftController && this._enableInteractionOnController(this._leftController),
            this._rightController && this._enableInteractionOnController(this._rightController),
            this.raySelectionPredicate = function(t) {
                return t.isVisible && (t.isPickable || t.name === e._floorMeshName)
            }
            ,
            this.meshSelectionPredicate = function() {
                return !0
            }
            ,
            this._raySelectionPredicate = function(t) {
                return e._isTeleportationFloor(t) || t.name.indexOf("gazeTracker") === -1 && t.name.indexOf("teleportationTarget") === -1 && t.name.indexOf("torusTeleportation") === -1 ? e.raySelectionPredicate(t) : !1
            }
            ,
            this._interactionsEnabled = !0
        }
    }
    ,
    Object.defineProperty(i.prototype, "_noControllerIsActive", {
        get: function() {
            return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer)
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype._isTeleportationFloor = function(e) {
        for (var t = 0; t < this._floorMeshesCollection.length; t++)
            if (this._floorMeshesCollection[t].id === e.id)
                return !0;
        return !!(this._floorMeshName && e.name === this._floorMeshName)
    }
    ,
    i.prototype.addFloorMesh = function(e) {
        !this._floorMeshesCollection || this._floorMeshesCollection.indexOf(e) > -1 || this._floorMeshesCollection.push(e)
    }
    ,
    i.prototype.removeFloorMesh = function(e) {
        if (!!this._floorMeshesCollection) {
            var t = this._floorMeshesCollection.indexOf(e);
            t !== -1 && this._floorMeshesCollection.splice(t, 1)
        }
    }
    ,
    i.prototype.enableTeleportation = function(e) {
        var t = this;
        if (e === void 0 && (e = {}),
        !this._teleportationInitialized) {
            if (this._teleportationRequested = !0,
            this.enableInteractions(),
            this.webVROptions.useXR && (e.floorMeshes || e.floorMeshName)) {
                var r = e.floorMeshes || [];
                if (!r.length) {
                    var n = this._scene.getMeshByName(e.floorMeshName);
                    n && r.push(n)
                }
                if (this.xr) {
                    r.forEach(function(s) {
                        t.xr.teleportation.addFloorMesh(s)
                    }),
                    this.xr.teleportation.attached || this.xr.teleportation.attach();
                    return
                } else if (!this.xrTestDone) {
                    var o = function() {
                        t.xrTestDone && (t._scene.unregisterBeforeRender(o),
                        t.xr ? t.xr.teleportation.attached || t.xr.teleportation.attach() : t.enableTeleportation(e))
                    };
                    this._scene.registerBeforeRender(o);
                    return
                }
            }
            e.floorMeshName && (this._floorMeshName = e.floorMeshName),
            e.floorMeshes && (this._floorMeshesCollection = e.floorMeshes),
            e.teleportationMode && (this._teleportationMode = e.teleportationMode),
            e.teleportationTime && e.teleportationTime > 0 && (this._teleportationTime = e.teleportationTime),
            e.teleportationSpeed && e.teleportationSpeed > 0 && (this._teleportationSpeed = e.teleportationSpeed),
            e.easingFunction !== void 0 && (this._teleportationEasing = e.easingFunction),
            this._leftController != null && this._enableTeleportationOnController(this._leftController),
            this._rightController != null && this._enableTeleportationOnController(this._rightController);
            var a = new ImageProcessingConfiguration;
            a.vignetteColor = new Color4(0,0,0,0),
            a.vignetteEnabled = !0,
            this._postProcessMove = new ImageProcessingPostProcess("postProcessMove",1,this._webVRCamera,void 0,void 0,void 0,void 0,a),
            this._webVRCamera.detachPostProcess(this._postProcessMove),
            this._teleportationInitialized = !0,
            this._isDefaultTeleportationTarget && (this._createTeleportationCircles(),
            this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor))
        }
    }
    ,
    i.prototype._enableInteractionOnController = function(e) {
        var t = this
          , r = e.webVRController.mesh;
        r && (e._interactionsEnabled = !0,
        this.isInVRMode && this._displayLaserPointer && e._activatePointer(),
        this.webVROptions.laserToggle && e.webVRController.onMainButtonStateChangedObservable.add(function(n) {
            t._displayLaserPointer && n.value === 1 && (e._activePointer ? e._deactivatePointer() : e._activatePointer(),
            t.displayGaze && (e._gazeTracker.isVisible = e._activePointer))
        }),
        e.webVRController.onTriggerStateChangedObservable.add(function(n) {
            var o = e;
            t._noControllerIsActive && (o = t._cameraGazer),
            o._pointerDownOnMeshAsked ? n.value < t._padSensibilityDown && o._selectionPointerUp() : n.value > t._padSensibilityUp && o._selectionPointerDown()
        }))
    }
    ,
    i.prototype._checkTeleportWithRay = function(e, t) {
        this._teleportationRequestInitiated && !t._teleportationRequestInitiated || (t._teleportationRequestInitiated ? Math.sqrt(e.y * e.y + e.x * e.x) < this._padSensibilityDown && (this._teleportActive && this.teleportCamera(this._haloCenter),
        t._teleportationRequestInitiated = !1) : e.y < -this._padSensibilityUp && t._dpadPressed && (t._activatePointer(),
        t._teleportationRequestInitiated = !0))
    }
    ,
    i.prototype._checkRotate = function(e, t) {
        t._teleportationRequestInitiated || (t._rotationLeftAsked ? e.x > -this._padSensibilityDown && (t._rotationLeftAsked = !1) : e.x < -this._padSensibilityUp && t._dpadPressed && (t._rotationLeftAsked = !0,
        this._rotationAllowed && this._rotateCamera(!1)),
        t._rotationRightAsked ? e.x < this._padSensibilityDown && (t._rotationRightAsked = !1) : e.x > this._padSensibilityUp && t._dpadPressed && (t._rotationRightAsked = !0,
        this._rotationAllowed && this._rotateCamera(!0)))
    }
    ,
    i.prototype._checkTeleportBackwards = function(e, t) {
        if (!t._teleportationRequestInitiated)
            if (e.y > this._padSensibilityUp && t._dpadPressed) {
                if (!t._teleportationBackRequestInitiated) {
                    if (!this.currentVRCamera)
                        return;
                    var r = Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix())
                      , n = this.currentVRCamera.position;
                    this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion && (r = this.currentVRCamera.deviceRotationQuaternion,
                    n = this.currentVRCamera.devicePosition),
                    r.toEulerAnglesToRef(this._workingVector),
                    this._workingVector.z = 0,
                    this._workingVector.x = 0,
                    Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion),
                    this._workingQuaternion.toRotationMatrix(this._workingMatrix),
                    Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
                    var o = new Ray(n,this._workingVector)
                      , a = this._scene.pickWithRay(o, this._raySelectionPredicate);
                    a && a.pickedPoint && a.pickedMesh && this._isTeleportationFloor(a.pickedMesh) && a.distance < 5 && this.teleportCamera(a.pickedPoint),
                    t._teleportationBackRequestInitiated = !0
                }
            } else
                t._teleportationBackRequestInitiated = !1
    }
    ,
    i.prototype._enableTeleportationOnController = function(e) {
        var t = this
          , r = e.webVRController.mesh;
        r && (e._interactionsEnabled || this._enableInteractionOnController(e),
        e._interactionsEnabled = !0,
        e._teleportationEnabled = !0,
        e.webVRController.controllerType === PoseEnabledControllerType.VIVE && (e._dpadPressed = !1,
        e.webVRController.onPadStateChangedObservable.add(function(n) {
            e._dpadPressed = n.pressed,
            e._dpadPressed || (e._rotationLeftAsked = !1,
            e._rotationRightAsked = !1,
            e._teleportationBackRequestInitiated = !1)
        })),
        e.webVRController.onPadValuesChangedObservable.add(function(n) {
            t.teleportationEnabled && (t._checkTeleportBackwards(n, e),
            t._checkTeleportWithRay(n, e)),
            t._checkRotate(n, e)
        }))
    }
    ,
    i.prototype._createTeleportationCircles = function() {
        this._teleportationTarget = CreateGround("teleportationTarget", {
            width: 2,
            height: 2,
            subdivisions: 2
        }, this._scene),
        this._teleportationTarget.isPickable = !1;
        var e = 512
          , t = new DynamicTexture("DynamicTexture",e,this._scene,!0);
        t.hasAlpha = !0;
        var r = t.getContext()
          , n = e / 2
          , o = e / 2
          , a = 200;
        r.beginPath(),
        r.arc(n, o, a, 0, 2 * Math.PI, !1),
        r.fillStyle = this._teleportationFillColor,
        r.fill(),
        r.lineWidth = 10,
        r.strokeStyle = this._teleportationBorderColor,
        r.stroke(),
        r.closePath(),
        t.update();
        var s = new StandardMaterial("TextPlaneMaterial",this._scene);
        s.diffuseTexture = t,
        this._teleportationTarget.material = s;
        var l = CreateTorus("torusTeleportation", {
            diameter: .75,
            thickness: .1,
            tessellation: 25,
            updatable: !1
        }, this._scene);
        l.isPickable = !1,
        l.parent = this._teleportationTarget;
        var u = new Animation("animationInnerCircle","position.y",30,Animation.ANIMATIONTYPE_FLOAT,Animation.ANIMATIONLOOPMODE_CYCLE)
          , c = [];
        c.push({
            frame: 0,
            value: 0
        }),
        c.push({
            frame: 30,
            value: .4
        }),
        c.push({
            frame: 60,
            value: 0
        }),
        u.setKeys(c);
        var h = new SineEase;
        h.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT),
        u.setEasingFunction(h),
        l.animations = [],
        l.animations.push(u),
        this._scene.beginAnimation(l, 0, 60, !0),
        this._hideTeleportationTarget()
    }
    ,
    i.prototype._displayTeleportationTarget = function() {
        this._teleportActive = !0,
        this._teleportationInitialized && (this._teleportationTarget.isVisible = !0,
        this._isDefaultTeleportationTarget && (this._teleportationTarget.getChildren()[0].isVisible = !0))
    }
    ,
    i.prototype._hideTeleportationTarget = function() {
        this._teleportActive = !1,
        this._teleportationInitialized && (this._teleportationTarget.isVisible = !1,
        this._isDefaultTeleportationTarget && (this._teleportationTarget.getChildren()[0].isVisible = !1))
    }
    ,
    i.prototype._rotateCamera = function(e) {
        var t = this;
        if (this.currentVRCamera instanceof FreeCamera) {
            e ? this._rotationAngle++ : this._rotationAngle--,
            this.currentVRCamera.animations = [];
            var r = Quaternion.FromRotationMatrix(Matrix.RotationY(Math.PI / 4 * this._rotationAngle))
              , n = new Animation("animationRotation","rotationQuaternion",90,Animation.ANIMATIONTYPE_QUATERNION,Animation.ANIMATIONLOOPMODE_CONSTANT)
              , o = [];
            o.push({
                frame: 0,
                value: this.currentVRCamera.rotationQuaternion
            }),
            o.push({
                frame: 6,
                value: r
            }),
            n.setKeys(o),
            n.setEasingFunction(this._circleEase),
            this.currentVRCamera.animations.push(n),
            this._postProcessMove.animations = [];
            var a = new Animation("animationPP","vignetteWeight",90,Animation.ANIMATIONTYPE_FLOAT,Animation.ANIMATIONLOOPMODE_CONSTANT)
              , s = [];
            s.push({
                frame: 0,
                value: 0
            }),
            s.push({
                frame: 3,
                value: 4
            }),
            s.push({
                frame: 6,
                value: 0
            }),
            a.setKeys(s),
            a.setEasingFunction(this._circleEase),
            this._postProcessMove.animations.push(a);
            var l = new Animation("animationPP2","vignetteStretch",90,Animation.ANIMATIONTYPE_FLOAT,Animation.ANIMATIONLOOPMODE_CONSTANT)
              , u = [];
            u.push({
                frame: 0,
                value: 0
            }),
            u.push({
                frame: 3,
                value: 10
            }),
            u.push({
                frame: 6,
                value: 0
            }),
            l.setKeys(u),
            l.setEasingFunction(this._circleEase),
            this._postProcessMove.animations.push(l),
            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, !1, 1, function() {
                t._webVRCamera.detachPostProcess(t._postProcessMove)
            }),
            this._scene.beginAnimation(this.currentVRCamera, 0, 6, !1, 1)
        }
    }
    ,
    i.prototype._moveTeleportationSelectorTo = function(e, t, r) {
        if (e.pickedPoint) {
            t._teleportationRequestInitiated && (this._displayTeleportationTarget(),
            this._haloCenter.copyFrom(e.pickedPoint),
            this._teleportationTarget.position.copyFrom(e.pickedPoint));
            var n = this._convertNormalToDirectionOfRay(e.getNormal(!0, !1), r);
            if (n) {
                var o = Vector3.Cross(Axis.Y, n)
                  , a = Vector3.Cross(n, o);
                Vector3.RotationFromAxisToRef(a, n, o, this._teleportationTarget.rotation)
            }
            this._teleportationTarget.position.y += .1
        }
    }
    ,
    i.prototype.teleportCamera = function(e) {
        var t = this;
        if (this.currentVRCamera instanceof FreeCamera) {
            this.webVRCamera.leftCamera ? (this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition),
            this._workingVector.subtractInPlace(this.webVRCamera.position),
            e.subtractToRef(this._workingVector, this._workingVector)) : this._workingVector.copyFrom(e),
            this.isInVRMode ? this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor : this._workingVector.y += this._defaultHeight,
            this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
            var r = 90, n, o;
            if (this._teleportationMode == i.TELEPORTATIONMODE_CONSTANTSPEED) {
                o = r;
                var a = Vector3.Distance(this.currentVRCamera.position, this._workingVector);
                n = this._teleportationSpeed / a
            } else
                o = Math.round(this._teleportationTime * r / 1e3),
                n = 1;
            this.currentVRCamera.animations = [];
            var s = new Animation("animationCameraTeleportation","position",r,Animation.ANIMATIONTYPE_VECTOR3,Animation.ANIMATIONLOOPMODE_CONSTANT)
              , l = [{
                frame: 0,
                value: this.currentVRCamera.position
            }, {
                frame: o,
                value: this._workingVector
            }];
            s.setKeys(l),
            s.setEasingFunction(this._teleportationEasing),
            this.currentVRCamera.animations.push(s),
            this._postProcessMove.animations = [];
            var u = Math.round(o / 2)
              , c = new Animation("animationPP","vignetteWeight",r,Animation.ANIMATIONTYPE_FLOAT,Animation.ANIMATIONLOOPMODE_CONSTANT)
              , h = [];
            h.push({
                frame: 0,
                value: 0
            }),
            h.push({
                frame: u,
                value: 8
            }),
            h.push({
                frame: o,
                value: 0
            }),
            c.setKeys(h),
            this._postProcessMove.animations.push(c);
            var f = new Animation("animationPP2","vignetteStretch",r,Animation.ANIMATIONTYPE_FLOAT,Animation.ANIMATIONLOOPMODE_CONSTANT)
              , d = [];
            d.push({
                frame: 0,
                value: 0
            }),
            d.push({
                frame: u,
                value: 10
            }),
            d.push({
                frame: o,
                value: 0
            }),
            f.setKeys(d),
            this._postProcessMove.animations.push(f),
            this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0,
            this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0,
            this._webVRCamera.attachPostProcess(this._postProcessMove),
            this._scene.beginAnimation(this._postProcessMove, 0, o, !1, n, function() {
                t._webVRCamera.detachPostProcess(t._postProcessMove)
            }),
            this._scene.beginAnimation(this.currentVRCamera, 0, o, !1, n, function() {
                t.onAfterCameraTeleport.notifyObservers(t._workingVector)
            }),
            this._hideTeleportationTarget()
        }
    }
    ,
    i.prototype._convertNormalToDirectionOfRay = function(e, t) {
        if (e) {
            var r = Math.acos(Vector3.Dot(e, t.direction));
            r < Math.PI / 2 && e.scaleInPlace(-1)
        }
        return e
    }
    ,
    i.prototype._castRayAndSelectObject = function(e) {
        if (this.currentVRCamera instanceof FreeCamera) {
            var t = e._getForwardRay(this._rayLength)
              , r = this._scene.pickWithRay(t, this._raySelectionPredicate);
            if (r && this._scene.simulatePointerMove(r, {
                pointerId: e._id
            }),
            e._currentHit = r,
            r && r.pickedPoint) {
                if (this._displayGaze) {
                    var n = 1;
                    e._gazeTracker.isVisible = !0,
                    e._isActionableMesh && (n = 3),
                    this.updateGazeTrackerScale && (e._gazeTracker.scaling.x = r.distance * n,
                    e._gazeTracker.scaling.y = r.distance * n,
                    e._gazeTracker.scaling.z = r.distance * n);
                    var o = this._convertNormalToDirectionOfRay(r.getNormal(), t)
                      , a = .002;
                    if (o) {
                        var s = Vector3.Cross(Axis.Y, o)
                          , l = Vector3.Cross(o, s);
                        Vector3.RotationFromAxisToRef(l, o, s, e._gazeTracker.rotation)
                    }
                    e._gazeTracker.position.copyFrom(r.pickedPoint),
                    e._gazeTracker.position.x < 0 ? e._gazeTracker.position.x += a : e._gazeTracker.position.x -= a,
                    e._gazeTracker.position.y < 0 ? e._gazeTracker.position.y += a : e._gazeTracker.position.y -= a,
                    e._gazeTracker.position.z < 0 ? e._gazeTracker.position.z += a : e._gazeTracker.position.z -= a
                }
                e._updatePointerDistance(r.distance)
            } else
                e._updatePointerDistance(),
                e._gazeTracker.isVisible = !1;
            if (r && r.pickedMesh) {
                if (this._teleportationInitialized && this._isTeleportationFloor(r.pickedMesh) && r.pickedPoint) {
                    e._currentMeshSelected && !this._isTeleportationFloor(e._currentMeshSelected) && this._notifySelectedMeshUnselected(e._currentMeshSelected),
                    e._currentMeshSelected = null,
                    e._teleportationRequestInitiated && this._moveTeleportationSelectorTo(r, e, t);
                    return
                }
                if (r.pickedMesh !== e._currentMeshSelected)
                    if (this.meshSelectionPredicate(r.pickedMesh)) {
                        this.onNewMeshPicked.notifyObservers(r),
                        e._currentMeshSelected = r.pickedMesh,
                        r.pickedMesh.isPickable && r.pickedMesh.actionManager ? (this.changeGazeColor(this._pickedGazeColor),
                        this.changeLaserColor(this._pickedLaserColor),
                        e._isActionableMesh = !0) : (this.changeGazeColor(this._gazeColor),
                        this.changeLaserColor(this._laserColor),
                        e._isActionableMesh = !1);
                        try {
                            this.onNewMeshSelected.notifyObservers(r.pickedMesh);
                            var u = e;
                            u.webVRController && this.onMeshSelectedWithController.notifyObservers({
                                mesh: r.pickedMesh,
                                controller: u.webVRController
                            })
                        } catch (c) {
                            Logger$2.Warn("Error while raising onNewMeshSelected or onMeshSelectedWithController: " + c)
                        }
                    } else
                        this._notifySelectedMeshUnselected(e._currentMeshSelected),
                        e._currentMeshSelected = null,
                        this.changeGazeColor(this._gazeColor),
                        this.changeLaserColor(this._laserColor)
            } else
                this._notifySelectedMeshUnselected(e._currentMeshSelected),
                e._currentMeshSelected = null,
                this.changeGazeColor(this._gazeColor),
                this.changeLaserColor(this._laserColor)
        }
    }
    ,
    i.prototype._notifySelectedMeshUnselected = function(e) {
        e && this.onSelectedMeshUnselected.notifyObservers(e)
    }
    ,
    i.prototype.setLaserColor = function(e, t) {
        t === void 0 && (t = this._pickedLaserColor),
        this._laserColor = e,
        this._pickedLaserColor = t
    }
    ,
    i.prototype.setLaserLightingState = function(e) {
        e === void 0 && (e = !0),
        this._leftController && this._leftController._setLaserPointerLightingDisabled(!e),
        this._rightController && this._rightController._setLaserPointerLightingDisabled(!e)
    }
    ,
    i.prototype.setGazeColor = function(e, t) {
        t === void 0 && (t = this._pickedGazeColor),
        this._gazeColor = e,
        this._pickedGazeColor = t
    }
    ,
    i.prototype.changeLaserColor = function(e) {
        !this.updateControllerLaserColor || (this._leftController && this._leftController._setLaserPointerColor(e),
        this._rightController && this._rightController._setLaserPointerColor(e))
    }
    ,
    i.prototype.changeGazeColor = function(e) {
        !this.updateGazeTrackerColor || !this._cameraGazer._gazeTracker.material || (this._cameraGazer._gazeTracker.material.emissiveColor = e,
        this._leftController && (this._leftController._gazeTracker.material.emissiveColor = e),
        this._rightController && (this._rightController._gazeTracker.material.emissiveColor = e))
    }
    ,
    i.prototype.dispose = function() {
        this.isInVRMode && this.exitVR(),
        this._postProcessMove && this._postProcessMove.dispose(),
        this._webVRCamera && this._webVRCamera.dispose(),
        this._vrDeviceOrientationCamera && this._vrDeviceOrientationCamera.dispose(),
        !this._useCustomVRButton && this._btnVR && this._btnVR.parentNode && document.body.removeChild(this._btnVR),
        this._deviceOrientationCamera && this._scene.activeCamera != this._deviceOrientationCamera && this._deviceOrientationCamera.dispose(),
        this._cameraGazer && this._cameraGazer.dispose(),
        this._leftController && this._leftController.dispose(),
        this._rightController && this._rightController.dispose(),
        this._teleportationTarget && this._teleportationTarget.dispose(),
        this.xr && this.xr.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)
    }
    ,
    i.prototype.getClassName = function() {
        return "VRExperienceHelper"
    }
    ,
    i.TELEPORTATIONMODE_CONSTANTTIME = 0,
    i.TELEPORTATIONMODE_CONSTANTSPEED = 1,
    i
}()
  , _ENVTextureLoader = function() {
    function i() {
        this.supportCascades = !1
    }
    return i.prototype.canLoad = function(e) {
        return EndsWith(e, ".env")
    }
    ,
    i.prototype.loadCubeData = function(e, t, r, n, o) {
        if (!Array.isArray(e)) {
            var a = GetEnvInfo(e);
            if (a) {
                t.width = a.width,
                t.height = a.width;
                try {
                    UploadEnvSpherical(t, a),
                    UploadEnvLevelsAsync(t, e, a).then(function() {
                        t.isReady = !0,
                        t.onLoadedObservable.notifyObservers(t),
                        t.onLoadedObservable.clear(),
                        n && n()
                    }, function(s) {
                        o == null || o("Can not upload environment levels", s)
                    })
                } catch (s) {
                    o == null || o("Can not upload environment file", s)
                }
            } else
                o && o("Can not parse the environment file", null)
        }
    }
    ,
    i.prototype.loadData = function(e, t, r) {
        throw ".env not supported in 2d."
    }
    ,
    i
}();
Engine._TextureLoaders.push(new _ENVTextureLoader);
var KhronosTextureContainer = function() {
    function i(e, t, r, n) {
        if (this.data = e,
        this.isInvalid = !1,
        !i.IsValid(e)) {
            this.isInvalid = !0,
            Logger$2.Error("texture missing KTX identifier");
            return
        }
        var o = Uint32Array.BYTES_PER_ELEMENT
          , a = new DataView(this.data.buffer,this.data.byteOffset + 12,13 * o)
          , s = a.getUint32(0, !0)
          , l = s === 67305985;
        if (this.glType = a.getUint32(1 * o, l),
        this.glTypeSize = a.getUint32(2 * o, l),
        this.glFormat = a.getUint32(3 * o, l),
        this.glInternalFormat = a.getUint32(4 * o, l),
        this.glBaseInternalFormat = a.getUint32(5 * o, l),
        this.pixelWidth = a.getUint32(6 * o, l),
        this.pixelHeight = a.getUint32(7 * o, l),
        this.pixelDepth = a.getUint32(8 * o, l),
        this.numberOfArrayElements = a.getUint32(9 * o, l),
        this.numberOfFaces = a.getUint32(10 * o, l),
        this.numberOfMipmapLevels = a.getUint32(11 * o, l),
        this.bytesOfKeyValueData = a.getUint32(12 * o, l),
        this.glType !== 0) {
            Logger$2.Error("only compressed formats currently supported");
            return
        } else
            this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
        if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
            Logger$2.Error("only 2D textures currently supported");
            return
        }
        if (this.numberOfArrayElements !== 0) {
            Logger$2.Error("texture arrays not currently supported");
            return
        }
        if (this.numberOfFaces !== t) {
            Logger$2.Error("number of faces expected" + t + ", but found " + this.numberOfFaces);
            return
        }
        this.loadType = i.COMPRESSED_2D
    }
    return i.prototype.uploadLevels = function(e, t) {
        switch (this.loadType) {
        case i.COMPRESSED_2D:
            this._upload2DCompressedLevels(e, t);
            break
        }
    }
    ,
    i.prototype._upload2DCompressedLevels = function(e, t) {
        for (var r = i.HEADER_LEN + this.bytesOfKeyValueData, n = this.pixelWidth, o = this.pixelHeight, a = t ? this.numberOfMipmapLevels : 1, s = 0; s < a; s++) {
            var l = new Int32Array(this.data.buffer,this.data.byteOffset + r,1)[0];
            r += 4;
            for (var u = 0; u < this.numberOfFaces; u++) {
                var c = new Uint8Array(this.data.buffer,this.data.byteOffset + r,l)
                  , h = e.getEngine();
                h._uploadCompressedDataToTextureDirectly(e, this.glInternalFormat, n, o, c, u, s),
                r += l,
                r += 3 - (l + 3) % 4
            }
            n = Math.max(1, n * .5),
            o = Math.max(1, o * .5)
        }
    }
    ,
    i.IsValid = function(e) {
        if (e.byteLength >= 12) {
            var t = new Uint8Array(e.buffer,e.byteOffset,12);
            if (t[0] === 171 && t[1] === 75 && t[2] === 84 && t[3] === 88 && t[4] === 32 && t[5] === 49 && t[6] === 49 && t[7] === 187 && t[8] === 13 && t[9] === 10 && t[10] === 26 && t[11] === 10)
                return !0
        }
        return !1
    }
    ,
    i.HEADER_LEN = 12 + 13 * 4,
    i.COMPRESSED_2D = 0,
    i.COMPRESSED_3D = 1,
    i.TEX_2D = 2,
    i.TEX_3D = 3,
    i
}()
  , KhronosTextureContainer2 = function() {
    function i(e, t) {
        t === void 0 && (t = i.DefaultNumWorkers),
        this._engine = e,
        i._Initialized || i._CreateWorkerPool(t)
    }
    return i.GetDefaultNumWorkers = function() {
        return typeof navigator != "object" || !navigator.hardwareConcurrency ? 1 : Math.min(Math.floor(navigator.hardwareConcurrency * .5), 4)
    }
    ,
    i._CreateWorkerPool = function(e) {
        this._Initialized = !0,
        e && typeof Worker == "function" ? i._WorkerPoolPromise = new Promise(function(t) {
            for (var r = "(" + workerFunc + ")()", n = URL.createObjectURL(new Blob([r],{
                type: "application/javascript"
            })), o = new Array(e), a = 0; a < o.length; a++)
                o[a] = new Promise(function(s, l) {
                    var u = new Worker(n)
                      , c = function(f) {
                        u.removeEventListener("error", c),
                        u.removeEventListener("message", h),
                        l(f)
                    }
                      , h = function(f) {
                        f.data.action === "init" && (u.removeEventListener("error", c),
                        u.removeEventListener("message", h),
                        s(u))
                    };
                    u.addEventListener("error", c),
                    u.addEventListener("message", h),
                    u.postMessage({
                        action: "init",
                        urls: i.URLConfig
                    })
                }
                );
            Promise.all(o).then(function(s) {
                t(new WorkerPool(s))
            })
        }
        ) : typeof KTX2DECODER == "undefined" ? i._NoWorkerPromise = Tools.LoadScriptAsync(i.URLConfig.jsDecoderModule).then(function() {
            KTX2DECODER.MSCTranscoder.UseFromWorkerThread = !1,
            KTX2DECODER.WASMMemoryManager.LoadBinariesFromCurrentThread = !0;
            var t = i.URLConfig;
            t.wasmUASTCToASTC !== null && (KTX2DECODER.LiteTranscoder_UASTC_ASTC.WasmModuleURL = t.wasmUASTCToASTC),
            t.wasmUASTCToBC7 !== null && (KTX2DECODER.LiteTranscoder_UASTC_BC7.WasmModuleURL = t.wasmUASTCToBC7),
            t.wasmUASTCToRGBA_UNORM !== null && (KTX2DECODER.LiteTranscoder_UASTC_RGBA_UNORM.WasmModuleURL = t.wasmUASTCToRGBA_UNORM),
            t.wasmUASTCToRGBA_SRGB !== null && (KTX2DECODER.LiteTranscoder_UASTC_RGBA_SRGB.WasmModuleURL = t.wasmUASTCToRGBA_SRGB),
            t.jsMSCTranscoder !== null && (KTX2DECODER.MSCTranscoder.JSModuleURL = t.jsMSCTranscoder),
            t.wasmMSCTranscoder !== null && (KTX2DECODER.MSCTranscoder.WasmModuleURL = t.wasmMSCTranscoder),
            t.wasmZSTDDecoder !== null && (KTX2DECODER.ZSTDDecoder.WasmModuleURL = t.wasmZSTDDecoder)
        }) : (KTX2DECODER.MSCTranscoder.UseFromWorkerThread = !1,
        KTX2DECODER.WASMMemoryManager.LoadBinariesFromCurrentThread = !0)
    }
    ,
    i.prototype.uploadAsync = function(e, t, r) {
        var n = this
          , o = this._engine.getCaps()
          , a = {
            astc: !!o.astc,
            bptc: !!o.bptc,
            s3tc: !!o.s3tc,
            pvrtc: !!o.pvrtc,
            etc2: !!o.etc2,
            etc1: !!o.etc1
        };
        return i._WorkerPoolPromise ? i._WorkerPoolPromise.then(function(s) {
            return new Promise(function(l, u) {
                s.push(function(c, h) {
                    var f = function(_) {
                        c.removeEventListener("error", f),
                        c.removeEventListener("message", d),
                        u(_),
                        h()
                    }
                      , d = function(_) {
                        if (_.data.action === "decoded") {
                            if (c.removeEventListener("error", f),
                            c.removeEventListener("message", d),
                            !_.data.success)
                                u({
                                    message: _.data.msg
                                });
                            else
                                try {
                                    n._createTexture(_.data.decodedData, t, r),
                                    l()
                                } catch (g) {
                                    u({
                                        message: g
                                    })
                                }
                            h()
                        }
                    };
                    c.addEventListener("error", f),
                    c.addEventListener("message", d),
                    c.postMessage({
                        action: "decode",
                        data: e,
                        caps: a,
                        options: r
                    })
                })
            }
            )
        }) : i._NoWorkerPromise ? i._NoWorkerPromise.then(function() {
            return new Promise(function(s, l) {
                i._Ktx2Decoder || (i._Ktx2Decoder = new KTX2DECODER.KTX2Decoder),
                i._Ktx2Decoder.decode(e, o).then(function(u) {
                    n._createTexture(u, t),
                    s()
                }).catch(function(u) {
                    l({
                        message: u
                    })
                })
            }
            )
        }) : new Promise(function(s, l) {
            i._Ktx2Decoder || (i._Ktx2Decoder = new KTX2DECODER.KTX2Decoder),
            i._Ktx2Decoder.decode(e, o).then(function(u) {
                n._createTexture(u, t),
                s()
            }).catch(function(u) {
                l({
                    message: u
                })
            })
        }
        )
    }
    ,
    i.prototype.dispose = function() {
        i._WorkerPoolPromise && i._WorkerPoolPromise.then(function(e) {
            e.dispose()
        }),
        delete i._WorkerPoolPromise,
        delete i._NoWorkerPromise
    }
    ,
    i.prototype._createTexture = function(e, t, r) {
        var n = 3553;
        if (this._engine._bindTextureDirectly(n, t),
        r && (r.transcodedFormat = e.transcodedFormat,
        r.isInGammaSpace = e.isInGammaSpace,
        r.hasAlpha = e.hasAlpha,
        r.transcoderName = e.transcoderName),
        e.transcodedFormat === 32856 ? (t.type = 0,
        t.format = 5) : t.format = e.transcodedFormat,
        t._gammaSpace = e.isInGammaSpace,
        t.generateMipMaps = e.mipmaps.length > 1,
        e.errors)
            throw new Error("KTX2 container - could not transcode the data. " + e.errors);
        for (var o = 0; o < e.mipmaps.length; ++o) {
            var a = e.mipmaps[o];
            if (!a || !a.data)
                throw new Error("KTX2 container - could not transcode one of the image");
            e.transcodedFormat === 32856 ? (t.width = a.width,
            t.height = a.height,
            this._engine._uploadDataToTextureDirectly(t, a.data, 0, o, void 0, !0)) : this._engine._uploadCompressedDataToTextureDirectly(t, e.transcodedFormat, a.width, a.height, a.data, 0, o)
        }
        t._extension = ".ktx2",
        t.width = e.mipmaps[0].width,
        t.height = e.mipmaps[0].height,
        t.isReady = !0,
        this._engine._bindTextureDirectly(n, null)
    }
    ,
    i.IsValid = function(e) {
        if (e.byteLength >= 12) {
            var t = new Uint8Array(e.buffer,e.byteOffset,12);
            if (t[0] === 171 && t[1] === 75 && t[2] === 84 && t[3] === 88 && t[4] === 32 && t[5] === 50 && t[6] === 48 && t[7] === 187 && t[8] === 13 && t[9] === 10 && t[10] === 26 && t[11] === 10)
                return !0
        }
        return !1
    }
    ,
    i.URLConfig = {
        jsDecoderModule: "https://preview.babylonjs.com/babylon.ktx2Decoder.js",
        wasmUASTCToASTC: null,
        wasmUASTCToBC7: null,
        wasmUASTCToRGBA_UNORM: null,
        wasmUASTCToRGBA_SRGB: null,
        jsMSCTranscoder: null,
        wasmMSCTranscoder: null,
        wasmZSTDDecoder: null
    },
    i.DefaultNumWorkers = i.GetDefaultNumWorkers(),
    i
}();
function workerFunc() {
    var i;
    onmessage = function(e) {
        if (!!e.data)
            switch (e.data.action) {
            case "init":
                var t = e.data.urls;
                importScripts(t.jsDecoderModule),
                t.wasmUASTCToASTC !== null && (KTX2DECODER.LiteTranscoder_UASTC_ASTC.WasmModuleURL = t.wasmUASTCToASTC),
                t.wasmUASTCToBC7 !== null && (KTX2DECODER.LiteTranscoder_UASTC_BC7.WasmModuleURL = t.wasmUASTCToBC7),
                t.wasmUASTCToRGBA_UNORM !== null && (KTX2DECODER.LiteTranscoder_UASTC_RGBA_UNORM.WasmModuleURL = t.wasmUASTCToRGBA_UNORM),
                t.wasmUASTCToRGBA_SRGB !== null && (KTX2DECODER.LiteTranscoder_UASTC_RGBA_SRGB.WasmModuleURL = t.wasmUASTCToRGBA_SRGB),
                t.jsMSCTranscoder !== null && (KTX2DECODER.MSCTranscoder.JSModuleURL = t.jsMSCTranscoder),
                t.wasmMSCTranscoder !== null && (KTX2DECODER.MSCTranscoder.WasmModuleURL = t.wasmMSCTranscoder),
                t.wasmZSTDDecoder !== null && (KTX2DECODER.ZSTDDecoder.WasmModuleURL = t.wasmZSTDDecoder),
                i = new KTX2DECODER.KTX2Decoder,
                postMessage({
                    action: "init"
                });
                break;
            case "decode":
                i.decode(e.data.data, e.data.caps, e.data.options).then(function(r) {
                    for (var n = [], o = 0; o < r.mipmaps.length; ++o) {
                        var a = r.mipmaps[o];
                        a && a.data && n.push(a.data.buffer)
                    }
                    postMessage({
                        action: "decoded",
                        success: !0,
                        decodedData: r
                    }, n)
                }).catch(function(r) {
                    postMessage({
                        action: "decoded",
                        success: !1,
                        msg: r
                    })
                });
                break
            }
    }
}
var _KTXTextureLoader = function() {
    function i() {
        this.supportCascades = !1
    }
    return i.prototype.canLoad = function(e, t) {
        return EndsWith(e, ".ktx") || EndsWith(e, ".ktx2") || t === "image/ktx" || t === "image/ktx2"
    }
    ,
    i.prototype.loadCubeData = function(e, t, r, n, o) {
        if (!Array.isArray(e)) {
            t._invertVScale = !t.invertY;
            var a = t.getEngine()
              , s = new KhronosTextureContainer(e,6)
              , l = s.numberOfMipmapLevels > 1 && t.generateMipMaps;
            a._unpackFlipY(!0),
            s.uploadLevels(t, t.generateMipMaps),
            t.width = s.pixelWidth,
            t.height = s.pixelHeight,
            a._setCubeMapTextureParams(t, l),
            t.isReady = !0,
            t.onLoadedObservable.notifyObservers(t),
            t.onLoadedObservable.clear(),
            n && n()
        }
    }
    ,
    i.prototype.loadData = function(e, t, r, n) {
        if (KhronosTextureContainer.IsValid(e)) {
            t._invertVScale = !t.invertY;
            var o = new KhronosTextureContainer(e,1);
            r(o.pixelWidth, o.pixelHeight, t.generateMipMaps, !0, function() {
                o.uploadLevels(t, t.generateMipMaps)
            }, o.isInvalid)
        } else if (KhronosTextureContainer2.IsValid(e)) {
            var a = new KhronosTextureContainer2(t.getEngine());
            a.uploadAsync(e, t, n).then(function() {
                r(t.width, t.height, t.generateMipMaps, !0, function() {}, !1)
            }, function(s) {
                Logger$2.Warn("Failed to load KTX2 texture data: " + s.message),
                r(0, 0, !1, !1, function() {}, !0)
            })
        } else
            Logger$2.Error("texture missing KTX identifier"),
            r(0, 0, !1, !1, function() {}, !0)
    }
    ,
    i
}();
Engine._TextureLoaders.unshift(new _KTXTextureLoader);
var WebXRCamera = function(i) {
    __extends(e, i);
    function e(t, r, n) {
        var o = i.call(this, t, Vector3.Zero(), r) || this;
        return o._xrSessionManager = n,
        o._firstFrame = !1,
        o._referenceQuaternion = Quaternion.Identity(),
        o._referencedPosition = new Vector3,
        o._trackingState = WebXRTrackingState.NOT_TRACKING,
        o.onBeforeCameraTeleport = new Observable,
        o.onAfterCameraTeleport = new Observable,
        o.onTrackingStateChanged = new Observable,
        o.compensateOnFirstFrame = !0,
        o._rotate180 = new Quaternion(0,1,0,0),
        o.minZ = .1,
        o.rotationQuaternion = new Quaternion,
        o.cameraRigMode = Camera$1.RIG_MODE_CUSTOM,
        o.updateUpVectorFromRotation = !0,
        o._updateNumberOfRigCameras(1),
        o.freezeProjectionMatrix(),
        o._xrSessionManager.onXRSessionInit.add(function() {
            o._referencedPosition.copyFromFloats(0, 0, 0),
            o._referenceQuaternion.copyFromFloats(0, 0, 0, 1),
            o._firstFrame = o.compensateOnFirstFrame
        }),
        o._xrSessionManager.onXRFrameObservable.add(function(a) {
            o._firstFrame && o._updateFromXRSession(),
            o._updateReferenceSpace(),
            o._updateFromXRSession()
        }, void 0, !0),
        o
    }
    return Object.defineProperty(e.prototype, "trackingState", {
        get: function() {
            return this._trackingState
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._setTrackingState = function(t) {
        this._trackingState !== t && (this._trackingState = t,
        this.onTrackingStateChanged.notifyObservers(t))
    }
    ,
    Object.defineProperty(e.prototype, "realWorldHeight", {
        get: function() {
            var t = this._xrSessionManager.currentFrame && this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.baseReferenceSpace);
            return t && t.transform ? t.transform.position.y : 0
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._updateForDualEyeDebugging = function() {
        this._updateNumberOfRigCameras(2),
        this.rigCameras[0].viewport = new Viewport(0,0,.5,1),
        this.rigCameras[0].outputRenderTarget = null,
        this.rigCameras[1].viewport = new Viewport(.5,0,.5,1),
        this.rigCameras[1].outputRenderTarget = null
    }
    ,
    e.prototype.setTransformationFromNonVRCamera = function(t, r) {
        if (t === void 0 && (t = this.getScene().activeCamera),
        r === void 0 && (r = !0),
        !(!t || t === this)) {
            var n = t.computeWorldMatrix();
            n.decompose(void 0, this.rotationQuaternion, this.position),
            this.position.y = 0,
            Quaternion.FromEulerAnglesToRef(0, this.rotationQuaternion.toEulerAngles().y, 0, this.rotationQuaternion),
            this._firstFrame = !0,
            r && this._xrSessionManager.resetReferenceSpace()
        }
    }
    ,
    e.prototype.getClassName = function() {
        return "WebXRCamera"
    }
    ,
    e.prototype.dispose = function() {
        i.prototype.dispose.call(this),
        this._lastXRViewerPose = void 0
    }
    ,
    e.prototype._updateFromXRSession = function() {
        var t = this
          , r = this._xrSessionManager.currentFrame && this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.referenceSpace);
        if (this._lastXRViewerPose = r || void 0,
        !r) {
            this._setTrackingState(WebXRTrackingState.NOT_TRACKING);
            return
        }
        var n = r.emulatedPosition ? WebXRTrackingState.TRACKING_LOST : WebXRTrackingState.TRACKING;
        if (this._setTrackingState(n),
        r.transform) {
            var o = r.transform.orientation;
            if (r.transform.orientation.x === void 0)
                return;
            var a = r.transform.position;
            this._referencedPosition.set(a.x, a.y, a.z),
            this._referenceQuaternion.set(o.x, o.y, o.z, o.w),
            this._scene.useRightHandedSystem || (this._referencedPosition.z *= -1,
            this._referenceQuaternion.z *= -1,
            this._referenceQuaternion.w *= -1),
            this._firstFrame ? (this._firstFrame = !1,
            this.position.y += this._referencedPosition.y,
            this._referenceQuaternion.copyFromFloats(0, 0, 0, 1)) : (this.rotationQuaternion.copyFrom(this._referenceQuaternion),
            this.position.copyFrom(this._referencedPosition))
        }
        this.rigCameras.length !== r.views.length && this._updateNumberOfRigCameras(r.views.length),
        r.views.forEach(function(s, l) {
            var u = t.rigCameras[l];
            !u.isLeftCamera && !u.isRightCamera && (s.eye === "right" ? u._isRightCamera = !0 : s.eye === "left" && (u._isLeftCamera = !0));
            var c = s.transform.position
              , h = s.transform.orientation;
            if (u.parent = t.parent,
            u.position.set(c.x, c.y, c.z),
            u.rotationQuaternion.set(h.x, h.y, h.z, h.w),
            t._scene.useRightHandedSystem ? u.rotationQuaternion.multiplyInPlace(t._rotate180) : (u.position.z *= -1,
            u.rotationQuaternion.z *= -1,
            u.rotationQuaternion.w *= -1),
            Matrix.FromFloat32ArrayToRefScaled(s.projectionMatrix, 0, 1, u._projectionMatrix),
            t._scene.useRightHandedSystem || u._projectionMatrix.toggleProjectionMatrixHandInPlace(),
            l === 0 && t._projectionMatrix.copyFrom(u._projectionMatrix),
            t._xrSessionManager.session.renderState.baseLayer) {
                var f = t._xrSessionManager.session.renderState.baseLayer.getViewport(s)
                  , d = t._xrSessionManager.session.renderState.baseLayer.framebufferWidth
                  , _ = t._xrSessionManager.session.renderState.baseLayer.framebufferHeight;
                u.viewport.width = f.width / d,
                u.viewport.height = f.height / _,
                u.viewport.x = f.x / d,
                u.viewport.y = f.y / _
            }
            u.outputRenderTarget = t._xrSessionManager.getRenderTargetTextureForEye(s.eye)
        })
    }
    ,
    e.prototype._updateNumberOfRigCameras = function(t) {
        for (t === void 0 && (t = 1); this.rigCameras.length < t; ) {
            var r = new TargetCamera("XR-RigCamera: " + this.rigCameras.length,Vector3.Zero(),this.getScene());
            r.minZ = .1,
            r.rotationQuaternion = new Quaternion,
            r.updateUpVectorFromRotation = !0,
            r.isRigCamera = !0,
            r.rigParent = this,
            r.freezeProjectionMatrix(),
            this.rigCameras.push(r)
        }
        for (; this.rigCameras.length > t; ) {
            var n = this.rigCameras.pop();
            n && n.dispose()
        }
    }
    ,
    e.prototype._updateReferenceSpace = function() {
        if (!this.position.equals(this._referencedPosition) || !this.rotationQuaternion.equals(this._referenceQuaternion)) {
            var t = TmpVectors.Matrix[0]
              , r = TmpVectors.Matrix[1]
              , n = TmpVectors.Matrix[2];
            Matrix.ComposeToRef(e._ScaleReadOnly, this._referenceQuaternion, this._referencedPosition, t),
            Matrix.ComposeToRef(e._ScaleReadOnly, this.rotationQuaternion, this.position, r),
            t.invert().multiplyToRef(r, n),
            n.invert(),
            this._scene.useRightHandedSystem || n.toggleModelMatrixHandInPlace(),
            n.decompose(void 0, this._referenceQuaternion, this._referencedPosition);
            var o = new XRRigidTransform({
                x: this._referencedPosition.x,
                y: this._referencedPosition.y,
                z: this._referencedPosition.z
            },{
                x: this._referenceQuaternion.x,
                y: this._referenceQuaternion.y,
                z: this._referenceQuaternion.z,
                w: this._referenceQuaternion.w
            });
            this._xrSessionManager.referenceSpace = this._xrSessionManager.referenceSpace.getOffsetReferenceSpace(o)
        }
    }
    ,
    e._ScaleReadOnly = Vector3.One(),
    e
}(FreeCamera), _a, WebXRFeatureName = function() {
    function i() {}
    return i.ANCHOR_SYSTEM = "xr-anchor-system",
    i.BACKGROUND_REMOVER = "xr-background-remover",
    i.HIT_TEST = "xr-hit-test",
    i.MESH_DETECTION = "xr-mesh-detection",
    i.PHYSICS_CONTROLLERS = "xr-physics-controller",
    i.PLANE_DETECTION = "xr-plane-detection",
    i.POINTER_SELECTION = "xr-controller-pointer-selection",
    i.TELEPORTATION = "xr-controller-teleportation",
    i.FEATURE_POINTS = "xr-feature-points",
    i.HAND_TRACKING = "xr-hand-tracking",
    i.IMAGE_TRACKING = "xr-image-tracking",
    i.NEAR_INTERACTION = "xr-near-interaction",
    i.DOM_OVERLAY = "xr-dom-overlay",
    i.MOVEMENT = "xr-controller-movement",
    i.LIGHT_ESTIMATION = "xr-light-estimation",
    i.EYE_TRACKING = "xr-eye-tracking",
    i.WALKING_LOCOMOTION = "xr-walking-locomotion",
    i
}(), WebXRFeaturesManager = function() {
    function i(e) {
        var t = this;
        this._xrSessionManager = e,
        this._features = {},
        this._xrSessionManager.onXRSessionInit.add(function() {
            t.getEnabledFeatures().forEach(function(r) {
                var n = t._features[r];
                n.enabled && !n.featureImplementation.attached && !n.featureImplementation.disableAutoAttach && t.attachFeature(r)
            })
        }),
        this._xrSessionManager.onXRSessionEnded.add(function() {
            t.getEnabledFeatures().forEach(function(r) {
                var n = t._features[r];
                n.enabled && n.featureImplementation.attached && t.detachFeature(r)
            })
        })
    }
    return i.AddWebXRFeature = function(e, t, r, n) {
        r === void 0 && (r = 1),
        n === void 0 && (n = !1),
        this._AvailableFeatures[e] = this._AvailableFeatures[e] || {
            latest: r
        },
        r > this._AvailableFeatures[e].latest && (this._AvailableFeatures[e].latest = r),
        n && (this._AvailableFeatures[e].stable = r),
        this._AvailableFeatures[e][r] = t
    }
    ,
    i.ConstructFeature = function(e, t, r, n) {
        t === void 0 && (t = 1);
        var o = this._AvailableFeatures[e][t];
        if (!o)
            throw new Error("feature not found");
        return o(r, n)
    }
    ,
    i.GetAvailableFeatures = function() {
        return Object.keys(this._AvailableFeatures)
    }
    ,
    i.GetAvailableVersions = function(e) {
        return Object.keys(this._AvailableFeatures[e])
    }
    ,
    i.GetLatestVersionOfFeature = function(e) {
        return this._AvailableFeatures[e] && this._AvailableFeatures[e].latest || -1
    }
    ,
    i.GetStableVersionOfFeature = function(e) {
        return this._AvailableFeatures[e] && this._AvailableFeatures[e].stable || -1
    }
    ,
    i.prototype.attachFeature = function(e) {
        var t = this._features[e];
        t && t.enabled && !t.featureImplementation.attached && t.featureImplementation.attach()
    }
    ,
    i.prototype.detachFeature = function(e) {
        var t = this._features[e];
        t && t.featureImplementation.attached && t.featureImplementation.detach()
    }
    ,
    i.prototype.disableFeature = function(e) {
        var t = typeof e == "string" ? e : e.Name
          , r = this._features[t];
        return r && r.enabled ? (r.enabled = !1,
        this.detachFeature(t),
        r.featureImplementation.dispose(),
        delete this._features[t],
        !0) : !1
    }
    ,
    i.prototype.dispose = function() {
        var e = this;
        this.getEnabledFeatures().forEach(function(t) {
            e.disableFeature(t)
        })
    }
    ,
    i.prototype.enableFeature = function(e, t, r, n, o) {
        var a = this;
        t === void 0 && (t = "latest"),
        r === void 0 && (r = {}),
        n === void 0 && (n = !0),
        o === void 0 && (o = !0);
        var s = typeof e == "string" ? e : e.Name
          , l = 0;
        if (typeof t == "string") {
            if (!t)
                throw new Error("Error in provided version - " + s + " (" + t + ")");
            if (t === "stable" ? l = i.GetStableVersionOfFeature(s) : t === "latest" ? l = i.GetLatestVersionOfFeature(s) : l = +t,
            l === -1 || isNaN(l))
                throw new Error("feature not found - " + s + " (" + t + ")")
        } else
            l = t;
        var u = i._ConflictingFeatures[s];
        if (u !== void 0 && this.getEnabledFeatures().indexOf(u) !== -1)
            throw new Error("Feature " + s + " cannot be enabled while " + u + " is enabled.");
        var c = this._features[s]
          , h = i.ConstructFeature(s, l, this._xrSessionManager, r);
        if (!h)
            throw new Error("feature not found - " + s);
        c && this.disableFeature(s);
        var f = h();
        if (f.dependsOn) {
            var d = f.dependsOn.every(function(_) {
                return !!a._features[_]
            });
            if (!d)
                throw new Error("Dependant features missing. Make sure the following features are enabled - " + f.dependsOn.join(", "))
        }
        if (f.isCompatible())
            return this._features[s] = {
                featureImplementation: f,
                enabled: !0,
                version: l,
                required: o
            },
            n ? this._xrSessionManager.session && !this._features[s].featureImplementation.attached && this.attachFeature(s) : this._features[s].featureImplementation.disableAutoAttach = !0,
            this._features[s].featureImplementation;
        if (o)
            throw new Error("required feature not compatible");
        return Tools.Warn("Feature " + s + " not compatible with the current environment/browser and was not enabled."),
        f
    }
    ,
    i.prototype.getEnabledFeature = function(e) {
        return this._features[e] && this._features[e].featureImplementation
    }
    ,
    i.prototype.getEnabledFeatures = function() {
        return Object.keys(this._features)
    }
    ,
    i.prototype._extendXRSessionInitObject = function(e) {
        return __awaiter(this, void 0, void 0, function() {
            var t, r, n, o, a, s, l;
            return __generator(this, function(u) {
                switch (u.label) {
                case 0:
                    t = this.getEnabledFeatures(),
                    r = 0,
                    n = t,
                    u.label = 1;
                case 1:
                    return r < n.length ? (o = n[r],
                    a = this._features[o],
                    s = a.featureImplementation.xrNativeFeatureName,
                    s && (a.required ? (e.requiredFeatures = e.requiredFeatures || [],
                    e.requiredFeatures.indexOf(s) === -1 && e.requiredFeatures.push(s)) : (e.optionalFeatures = e.optionalFeatures || [],
                    e.optionalFeatures.indexOf(s) === -1 && e.optionalFeatures.push(s))),
                    a.featureImplementation.getXRSessionInitExtension ? [4, a.featureImplementation.getXRSessionInitExtension()] : [3, 3]) : [3, 4];
                case 2:
                    l = u.sent(),
                    e = __assign(__assign({}, e), l),
                    u.label = 3;
                case 3:
                    return r++,
                    [3, 1];
                case 4:
                    return [2, e]
                }
            })
        })
    }
    ,
    i._AvailableFeatures = {},
    i._ConflictingFeatures = (_a = {},
    _a[WebXRFeatureName.TELEPORTATION] = WebXRFeatureName.MOVEMENT,
    _a[WebXRFeatureName.MOVEMENT] = WebXRFeatureName.TELEPORTATION,
    _a),
    i
}();
Node$2.AddNodeConstructor("TouchCamera", function(i, e) {
    return function() {
        return new TouchCamera(i,Vector3.Zero(),e)
    }
});
var TouchCamera = function(i) {
    __extends(e, i);
    function e(t, r, n) {
        var o = i.call(this, t, r, n) || this;
        return o.inputs.addTouch(),
        o._setupInputs(),
        o
    }
    return Object.defineProperty(e.prototype, "touchAngularSensibility", {
        get: function() {
            var t = this.inputs.attached.touch;
            return t ? t.touchAngularSensibility : 0
        },
        set: function(t) {
            var r = this.inputs.attached.touch;
            r && (r.touchAngularSensibility = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "touchMoveSensibility", {
        get: function() {
            var t = this.inputs.attached.touch;
            return t ? t.touchMoveSensibility : 0
        },
        set: function(t) {
            var r = this.inputs.attached.touch;
            r && (r.touchMoveSensibility = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getClassName = function() {
        return "TouchCamera"
    }
    ,
    e.prototype._setupInputs = function() {
        var t = this.inputs.attached.touch
          , r = this.inputs.attached.mouse;
        r ? r.touchEnabled = !1 : t.allowMouse = !0
    }
    ,
    e
}(FreeCamera);
Node$2.AddNodeConstructor("FreeCamera", function(i, e) {
    return function() {
        return new UniversalCamera(i,Vector3.Zero(),e)
    }
});
var UniversalCamera = function(i) {
    __extends(e, i);
    function e(t, r, n) {
        var o = i.call(this, t, r, n) || this;
        return o.inputs.addGamepad(),
        o
    }
    return Object.defineProperty(e.prototype, "gamepadAngularSensibility", {
        get: function() {
            var t = this.inputs.attached.gamepad;
            return t ? t.gamepadAngularSensibility : 0
        },
        set: function(t) {
            var r = this.inputs.attached.gamepad;
            r && (r.gamepadAngularSensibility = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "gamepadMoveSensibility", {
        get: function() {
            var t = this.inputs.attached.gamepad;
            return t ? t.gamepadMoveSensibility : 0
        },
        set: function(t) {
            var r = this.inputs.attached.gamepad;
            r && (r.gamepadMoveSensibility = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getClassName = function() {
        return "UniversalCamera"
    }
    ,
    e
}(TouchCamera);
Camera$1._createDefaultParsedCamera = function(i, e) {
    return new UniversalCamera(i,Vector3.Zero(),e)
}
;
var WebXRExperienceHelper = function() {
    function i(e) {
        var t = this;
        this.scene = e,
        this._nonVRCamera = null,
        this._attachedToElement = !1,
        this._spectatorCamera = null,
        this._originalSceneAutoClear = !0,
        this._supported = !1,
        this._spectatorMode = !1,
        this.onInitialXRPoseSetObservable = new Observable,
        this.onStateChangedObservable = new Observable,
        this.state = WebXRState.NOT_IN_XR,
        this.sessionManager = new WebXRSessionManager(e),
        this.camera = new WebXRCamera("webxr",e,this.sessionManager),
        this.featuresManager = new WebXRFeaturesManager(this.sessionManager),
        e.onDisposeObservable.add(function() {
            t.exitXRAsync()
        })
    }
    return i.CreateAsync = function(e) {
        var t = new i(e);
        return t.sessionManager.initializeAsync().then(function() {
            return t._supported = !0,
            t
        }).catch(function(r) {
            throw t._setState(WebXRState.NOT_IN_XR),
            t.dispose(),
            r
        })
    }
    ,
    i.prototype.dispose = function() {
        var e;
        this.camera.dispose(),
        this.onStateChangedObservable.clear(),
        this.onInitialXRPoseSetObservable.clear(),
        this.sessionManager.dispose(),
        (e = this._spectatorCamera) === null || e === void 0 || e.dispose(),
        this._nonVRCamera && (this.scene.activeCamera = this._nonVRCamera)
    }
    ,
    i.prototype.enterXRAsync = function(e, t, r, n) {
        var o, a;
        return r === void 0 && (r = this.sessionManager.getWebXRRenderTarget()),
        n === void 0 && (n = {}),
        __awaiter(this, void 0, void 0, function() {
            var s, l = this;
            return __generator(this, function(u) {
                switch (u.label) {
                case 0:
                    if (!this._supported)
                        throw "WebXR not supported in this browser or environment";
                    return this._setState(WebXRState.ENTERING_XR),
                    t !== "viewer" && t !== "local" && (n.optionalFeatures = n.optionalFeatures || [],
                    n.optionalFeatures.push(t)),
                    [4, this.featuresManager._extendXRSessionInitObject(n)];
                case 1:
                    n = u.sent(),
                    e === "immersive-ar" && t !== "unbounded" && Logger$2.Warn("We recommend using 'unbounded' reference space type when using 'immersive-ar' session mode"),
                    u.label = 2;
                case 2:
                    return u.trys.push([2, 7, , 8]),
                    [4, this.sessionManager.initializeSessionAsync(e, n)];
                case 3:
                    return u.sent(),
                    [4, this.sessionManager.setReferenceSpaceTypeAsync(t)];
                case 4:
                    return u.sent(),
                    [4, r.initializeXRLayerAsync(this.sessionManager.session)];
                case 5:
                    return u.sent(),
                    [4, this.sessionManager.updateRenderStateAsync({
                        depthFar: this.camera.maxZ,
                        depthNear: this.camera.minZ,
                        baseLayer: r.xrLayer
                    })];
                case 6:
                    return u.sent(),
                    this.sessionManager.runXRRenderLoop(),
                    this._originalSceneAutoClear = this.scene.autoClear,
                    this._nonVRCamera = this.scene.activeCamera,
                    this._attachedToElement = !!(!((o = this._nonVRCamera) === null || o === void 0) && o.inputs.attachedToElement),
                    (a = this._nonVRCamera) === null || a === void 0 || a.detachControl(),
                    this.scene.activeCamera = this.camera,
                    e !== "immersive-ar" ? this._nonXRToXRCamera() : (this.scene.autoClear = !1,
                    this.camera.compensateOnFirstFrame = !1),
                    this.sessionManager.onXRSessionEnded.addOnce(function() {
                        l.camera.rigCameras.forEach(function(c) {
                            c.outputRenderTarget = null
                        }),
                        l.scene.autoClear = l._originalSceneAutoClear,
                        l.scene.activeCamera = l._nonVRCamera,
                        l._attachedToElement && l._nonVRCamera && l._nonVRCamera.attachControl(!!l._nonVRCamera.inputs.noPreventDefault),
                        e !== "immersive-ar" && l.camera.compensateOnFirstFrame && (l._nonVRCamera.setPosition ? l._nonVRCamera.setPosition(l.camera.position) : l._nonVRCamera.position.copyFrom(l.camera.position)),
                        l._setState(WebXRState.NOT_IN_XR)
                    }),
                    this.sessionManager.onXRFrameObservable.addOnce(function() {
                        l._setState(WebXRState.IN_XR)
                    }),
                    [2, this.sessionManager];
                case 7:
                    throw s = u.sent(),
                    console.log(s),
                    console.log(s.message),
                    this._setState(WebXRState.NOT_IN_XR),
                    s;
                case 8:
                    return [2]
                }
            })
        })
    }
    ,
    i.prototype.exitXRAsync = function() {
        return this.state !== WebXRState.IN_XR ? Promise.resolve() : (this._setState(WebXRState.EXITING_XR),
        this.sessionManager.exitXRAsync())
    }
    ,
    i.prototype.enableSpectatorMode = function() {
        var e = this;
        if (!this._spectatorMode) {
            var t = function() {
                e._spectatorCamera && (e._spectatorCamera.position.copyFrom(e.camera.rigCameras[0].globalPosition),
                e._spectatorCamera.rotationQuaternion.copyFrom(e.camera.rigCameras[0].absoluteRotation))
            }
              , r = function() {
                e.state === WebXRState.IN_XR ? (e._spectatorCamera = new UniversalCamera("webxr-spectator",Vector3.Zero(),e.scene),
                e._spectatorCamera.rotationQuaternion = new Quaternion,
                e.scene.activeCameras = [e.camera, e._spectatorCamera],
                e.sessionManager.onXRFrameObservable.add(t),
                e.scene.onAfterRenderCameraObservable.add(function(n) {
                    n === e.camera && (e.scene.getEngine().framebufferDimensionsObject = null)
                })) : e.state === WebXRState.EXITING_XR && (e.sessionManager.onXRFrameObservable.removeCallback(t),
                e.scene.activeCameras = null)
            };
            this._spectatorMode = !0,
            this.onStateChangedObservable.add(r),
            r()
        }
    }
    ,
    i.prototype._nonXRToXRCamera = function() {
        this.camera.setTransformationFromNonVRCamera(this._nonVRCamera),
        this.onInitialXRPoseSetObservable.notifyObservers(this.camera)
    }
    ,
    i.prototype._setState = function(e) {
        this.state !== e && (this.state = e,
        this.onStateChangedObservable.notifyObservers(this.state))
    }
    ,
    i
}()
  , WebXRControllerComponent = function() {
    function i(e, t, r, n) {
        r === void 0 && (r = -1),
        n === void 0 && (n = []),
        this.id = e,
        this.type = t,
        this._buttonIndex = r,
        this._axesIndices = n,
        this._axes = {
            x: 0,
            y: 0
        },
        this._changes = {},
        this._currentValue = 0,
        this._hasChanges = !1,
        this._pressed = !1,
        this._touched = !1,
        this.onAxisValueChangedObservable = new Observable,
        this.onButtonStateChangedObservable = new Observable
    }
    return Object.defineProperty(i.prototype, "axes", {
        get: function() {
            return this._axes
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "changes", {
        get: function() {
            return this._changes
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "hasChanges", {
        get: function() {
            return this._hasChanges
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "pressed", {
        get: function() {
            return this._pressed
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "touched", {
        get: function() {
            return this._touched
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "value", {
        get: function() {
            return this._currentValue
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.dispose = function() {
        this.onAxisValueChangedObservable.clear(),
        this.onButtonStateChangedObservable.clear()
    }
    ,
    i.prototype.isAxes = function() {
        return this._axesIndices.length !== 0
    }
    ,
    i.prototype.isButton = function() {
        return this._buttonIndex !== -1
    }
    ,
    i.prototype.update = function(e) {
        var t = !1
          , r = !1;
        if (this._hasChanges = !1,
        this._changes = {},
        this.isButton()) {
            var n = e.buttons[this._buttonIndex];
            if (!n)
                return;
            this._currentValue !== n.value && (this.changes.value = {
                current: n.value,
                previous: this._currentValue
            },
            t = !0,
            this._currentValue = n.value),
            this._touched !== n.touched && (this.changes.touched = {
                current: n.touched,
                previous: this._touched
            },
            t = !0,
            this._touched = n.touched),
            this._pressed !== n.pressed && (this.changes.pressed = {
                current: n.pressed,
                previous: this._pressed
            },
            t = !0,
            this._pressed = n.pressed)
        }
        this.isAxes() && (this._axes.x !== e.axes[this._axesIndices[0]] && (this.changes.axes = {
            current: {
                x: e.axes[this._axesIndices[0]],
                y: this._axes.y
            },
            previous: {
                x: this._axes.x,
                y: this._axes.y
            }
        },
        this._axes.x = e.axes[this._axesIndices[0]],
        r = !0),
        this._axes.y !== e.axes[this._axesIndices[1]] && (this.changes.axes ? this.changes.axes.current.y = e.axes[this._axesIndices[1]] : this.changes.axes = {
            current: {
                x: this._axes.x,
                y: e.axes[this._axesIndices[1]]
            },
            previous: {
                x: this._axes.x,
                y: this._axes.y
            }
        },
        this._axes.y = e.axes[this._axesIndices[1]],
        r = !0)),
        t && (this._hasChanges = !0,
        this.onButtonStateChangedObservable.notifyObservers(this)),
        r && (this._hasChanges = !0,
        this.onAxisValueChangedObservable.notifyObservers(this._axes))
    }
    ,
    i.BUTTON_TYPE = "button",
    i.SQUEEZE_TYPE = "squeeze",
    i.THUMBSTICK_TYPE = "thumbstick",
    i.TOUCHPAD_TYPE = "touchpad",
    i.TRIGGER_TYPE = "trigger",
    i
}()
  , WebXRAbstractMotionController = function() {
    function i(e, t, r, n, o, a) {
        var s = this;
        o === void 0 && (o = !1),
        this.scene = e,
        this.layout = t,
        this.gamepadObject = r,
        this.handedness = n,
        this._doNotLoadControllerMesh = o,
        this._controllerCache = a,
        this._initComponent = function(l) {
            if (!!l) {
                var u = s.layout.components[l]
                  , c = u.type
                  , h = u.gamepadIndices.button
                  , f = [];
                u.gamepadIndices.xAxis !== void 0 && u.gamepadIndices.yAxis !== void 0 && f.push(u.gamepadIndices.xAxis, u.gamepadIndices.yAxis),
                s.components[l] = new WebXRControllerComponent(l,c,h,f)
            }
        }
        ,
        this._modelReady = !1,
        this.components = {},
        this.disableAnimation = !1,
        this.onModelLoadedObservable = new Observable,
        t.components && Object.keys(t.components).forEach(this._initComponent)
    }
    return i.prototype.dispose = function() {
        var e = this;
        this.getComponentIds().forEach(function(t) {
            return e.getComponent(t).dispose()
        }),
        this.rootMesh && (this.rootMesh.getChildren(void 0, !0).forEach(function(t) {
            t.setEnabled(!1)
        }),
        this.rootMesh.dispose(!!this._controllerCache, !this._controllerCache))
    }
    ,
    i.prototype.getAllComponentsOfType = function(e) {
        var t = this;
        return this.getComponentIds().map(function(r) {
            return t.components[r]
        }).filter(function(r) {
            return r.type === e
        })
    }
    ,
    i.prototype.getComponent = function(e) {
        return this.components[e]
    }
    ,
    i.prototype.getComponentIds = function() {
        return Object.keys(this.components)
    }
    ,
    i.prototype.getComponentOfType = function(e) {
        return this.getAllComponentsOfType(e)[0] || null
    }
    ,
    i.prototype.getMainComponent = function() {
        return this.getComponent(this.layout.selectComponentId)
    }
    ,
    i.prototype.loadModel = function() {
        return __awaiter(this, void 0, void 0, function() {
            var e, t, r = this;
            return __generator(this, function(n) {
                return e = !this._getModelLoadingConstraints(),
                t = this._getGenericFilenameAndPath(),
                e ? Logger$2.Warn("Falling back to generic models") : t = this._getFilenameAndPath(),
                [2, new Promise(function(o, a) {
                    var s = function(u) {
                        e ? r._getGenericParentMesh(u) : r._setRootMesh(u),
                        r._processLoadedModel(u),
                        r._modelReady = !0,
                        r.onModelLoadedObservable.notifyObservers(r),
                        o(!0)
                    };
                    if (r._controllerCache) {
                        var l = r._controllerCache.filter(function(u) {
                            return u.filename === t.filename && u.path === t.path
                        });
                        if (l[0]) {
                            l[0].meshes.forEach(function(u) {
                                return u.setEnabled(!0)
                            }),
                            s(l[0].meshes);
                            return
                        }
                    }
                    SceneLoader.ImportMesh("", t.path, t.filename, r.scene, function(u) {
                        r._controllerCache && r._controllerCache.push(__assign(__assign({}, t), {
                            meshes: u
                        })),
                        s(u)
                    }, null, function(u, c) {
                        Logger$2.Log(c),
                        Logger$2.Warn("Failed to retrieve controller model of type " + r.profileId + " from the remote server: " + t.path + t.filename),
                        a(c)
                    })
                }
                )]
            })
        })
    }
    ,
    i.prototype.updateFromXRFrame = function(e) {
        var t = this;
        this.getComponentIds().forEach(function(r) {
            return t.getComponent(r).update(t.gamepadObject)
        }),
        this.updateModel(e)
    }
    ,
    Object.defineProperty(i.prototype, "handness", {
        get: function() {
            return this.handedness
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.pulse = function(e, t, r) {
        return r === void 0 && (r = 0),
        this.gamepadObject.hapticActuators && this.gamepadObject.hapticActuators[r] ? this.gamepadObject.hapticActuators[r].pulse(e, t) : Promise.resolve(!1)
    }
    ,
    i.prototype._getChildByName = function(e, t) {
        return e.getChildren(function(r) {
            return r.name === t
        }, !1)[0]
    }
    ,
    i.prototype._getImmediateChildByName = function(e, t) {
        return e.getChildren(function(r) {
            return r.name == t
        }, !0)[0]
    }
    ,
    i.prototype._lerpTransform = function(e, t, r) {
        if (!(!e.minMesh || !e.maxMesh || !e.valueMesh) && !(!e.minMesh.rotationQuaternion || !e.maxMesh.rotationQuaternion || !e.valueMesh.rotationQuaternion)) {
            var n = r ? t * .5 + .5 : t;
            Quaternion.SlerpToRef(e.minMesh.rotationQuaternion, e.maxMesh.rotationQuaternion, n, e.valueMesh.rotationQuaternion),
            Vector3.LerpToRef(e.minMesh.position, e.maxMesh.position, n, e.valueMesh.position)
        }
    }
    ,
    i.prototype.updateModel = function(e) {
        !this._modelReady || this._updateModel(e)
    }
    ,
    i.prototype._getGenericFilenameAndPath = function() {
        return {
            filename: "generic.babylon",
            path: "https://controllers.babylonjs.com/generic/"
        }
    }
    ,
    i.prototype._getGenericParentMesh = function(e) {
        var t = this;
        this.rootMesh = new Mesh(this.profileId + " " + this.handedness,this.scene),
        e.forEach(function(r) {
            r.parent || (r.isPickable = !1,
            r.setParent(t.rootMesh))
        }),
        this.rootMesh.rotationQuaternion = Quaternion.FromEulerAngles(0, Math.PI, 0)
    }
    ,
    i
}()
  , WebXRGenericTriggerMotionController = function(i) {
    __extends(e, i);
    function e(t, r, n) {
        var o = i.call(this, t, GenericTriggerLayout[n], r, n) || this;
        return o.profileId = e.ProfileId,
        o
    }
    return e.prototype._getFilenameAndPath = function() {
        return {
            filename: "generic.babylon",
            path: "https://controllers.babylonjs.com/generic/"
        }
    }
    ,
    e.prototype._getModelLoadingConstraints = function() {
        return !0
    }
    ,
    e.prototype._processLoadedModel = function(t) {}
    ,
    e.prototype._setRootMesh = function(t) {
        var r = this;
        this.rootMesh = new Mesh(this.profileId + " " + this.handedness,this.scene),
        t.forEach(function(n) {
            n.isPickable = !1,
            n.parent || n.setParent(r.rootMesh)
        }),
        this.rootMesh.rotationQuaternion = Quaternion.FromEulerAngles(0, Math.PI, 0)
    }
    ,
    e.prototype._updateModel = function() {}
    ,
    e.ProfileId = "generic-trigger",
    e
}(WebXRAbstractMotionController)
  , GenericTriggerLayout = {
    left: {
        selectComponentId: "xr-standard-trigger",
        components: {
            "xr-standard-trigger": {
                type: "trigger",
                gamepadIndices: {
                    button: 0
                },
                rootNodeName: "xr_standard_trigger",
                visualResponses: {}
            }
        },
        gamepadMapping: "xr-standard",
        rootNodeName: "generic-trigger-left",
        assetPath: "left.glb"
    },
    right: {
        selectComponentId: "xr-standard-trigger",
        components: {
            "xr-standard-trigger": {
                type: "trigger",
                gamepadIndices: {
                    button: 0
                },
                rootNodeName: "xr_standard_trigger",
                visualResponses: {}
            }
        },
        gamepadMapping: "xr-standard",
        rootNodeName: "generic-trigger-right",
        assetPath: "right.glb"
    },
    none: {
        selectComponentId: "xr-standard-trigger",
        components: {
            "xr-standard-trigger": {
                type: "trigger",
                gamepadIndices: {
                    button: 0
                },
                rootNodeName: "xr_standard_trigger",
                visualResponses: {}
            }
        },
        gamepadMapping: "xr-standard",
        rootNodeName: "generic-trigger-none",
        assetPath: "none.glb"
    }
}
  , WebXRProfiledMotionController = function(i) {
    __extends(e, i);
    function e(t, r, n, o, a) {
        var s = i.call(this, t, n.layouts[r.handedness || "none"], r.gamepad, r.handedness, void 0, a) || this;
        return s._repositoryUrl = o,
        s.controllerCache = a,
        s._buttonMeshMapping = {},
        s._touchDots = {},
        s.profileId = n.profileId,
        s
    }
    return e.prototype.dispose = function() {
        var t = this;
        i.prototype.dispose.call(this),
        this.controllerCache || Object.keys(this._touchDots).forEach(function(r) {
            t._touchDots[r].dispose()
        })
    }
    ,
    e.prototype._getFilenameAndPath = function() {
        return {
            filename: this.layout.assetPath,
            path: this._repositoryUrl + "/profiles/" + this.profileId + "/"
        }
    }
    ,
    e.prototype._getModelLoadingConstraints = function() {
        var t = SceneLoader.IsPluginForExtensionAvailable(".glb");
        return t || Logger$2.Warn("glTF / glb loader was not registered, using generic controller instead"),
        t
    }
    ,
    e.prototype._processLoadedModel = function(t) {
        var r = this;
        this.getComponentIds().forEach(function(n) {
            var o = r.layout.components[n];
            r._buttonMeshMapping[n] = {
                mainMesh: r._getChildByName(r.rootMesh, o.rootNodeName),
                states: {}
            },
            Object.keys(o.visualResponses).forEach(function(a) {
                var s = o.visualResponses[a];
                if (s.valueNodeProperty === "transform")
                    r._buttonMeshMapping[n].states[a] = {
                        valueMesh: r._getChildByName(r.rootMesh, s.valueNodeName),
                        minMesh: r._getChildByName(r.rootMesh, s.minNodeName),
                        maxMesh: r._getChildByName(r.rootMesh, s.maxNodeName)
                    };
                else {
                    var l = o.type === WebXRControllerComponent.TOUCHPAD_TYPE && o.touchPointNodeName ? o.touchPointNodeName : s.valueNodeName;
                    if (r._buttonMeshMapping[n].states[a] = {
                        valueMesh: r._getChildByName(r.rootMesh, l)
                    },
                    o.type === WebXRControllerComponent.TOUCHPAD_TYPE && !r._touchDots[a]) {
                        var u = CreateSphere(a + "dot", {
                            diameter: .0015,
                            segments: 8
                        }, r.scene);
                        u.material = new StandardMaterial(a + "mat",r.scene),
                        u.material.diffuseColor = Color3.Red(),
                        u.parent = r._buttonMeshMapping[n].states[a].valueMesh || null,
                        u.isVisible = !1,
                        r._touchDots[a] = u
                    }
                }
            })
        })
    }
    ,
    e.prototype._setRootMesh = function(t) {
        this.rootMesh = new Mesh(this.profileId + "-" + this.handedness,this.scene),
        this.rootMesh.isPickable = !1;
        for (var r, n = 0; n < t.length; n++) {
            var o = t[n];
            o.isPickable = !1,
            o.parent || (r = o)
        }
        r && r.setParent(this.rootMesh),
        this.scene.useRightHandedSystem || this.rootMesh.rotate(Axis.Y, Math.PI, Space.WORLD)
    }
    ,
    e.prototype._updateModel = function(t) {
        var r = this;
        this.disableAnimation || this.getComponentIds().forEach(function(n) {
            var o = r.getComponent(n);
            if (!!o.hasChanges) {
                var a = r._buttonMeshMapping[n]
                  , s = r.layout.components[n];
                Object.keys(s.visualResponses).forEach(function(l) {
                    var u = s.visualResponses[l]
                      , c = o.value;
                    if (u.componentProperty === "xAxis" ? c = o.axes.x : u.componentProperty === "yAxis" && (c = o.axes.y),
                    u.valueNodeProperty === "transform")
                        r._lerpTransform(a.states[l], c, u.componentProperty !== "button");
                    else {
                        var h = a.states[l].valueMesh;
                        h && (h.isVisible = o.touched || o.pressed),
                        r._touchDots[l] && (r._touchDots[l].isVisible = o.touched || o.pressed)
                    }
                })
            }
        })
    }
    ,
    e
}(WebXRAbstractMotionController)
  , controllerCache = []
  , WebXRMotionControllerManager = function() {
    function i() {}
    return i.ClearProfilesCache = function() {
        this._ProfilesList = null,
        this._ProfileLoadingPromises = {}
    }
    ,
    i.DefaultFallbacks = function() {
        this.RegisterFallbacksForProfileId("google-daydream", ["generic-touchpad"]),
        this.RegisterFallbacksForProfileId("htc-vive-focus", ["generic-trigger-touchpad"]),
        this.RegisterFallbacksForProfileId("htc-vive", ["generic-trigger-squeeze-touchpad"]),
        this.RegisterFallbacksForProfileId("magicleap-one", ["generic-trigger-squeeze-touchpad"]),
        this.RegisterFallbacksForProfileId("windows-mixed-reality", ["generic-trigger-squeeze-touchpad-thumbstick"]),
        this.RegisterFallbacksForProfileId("microsoft-mixed-reality", ["windows-mixed-reality", "generic-trigger-squeeze-touchpad-thumbstick"]),
        this.RegisterFallbacksForProfileId("oculus-go", ["generic-trigger-touchpad"]),
        this.RegisterFallbacksForProfileId("oculus-touch-v2", ["oculus-touch", "generic-trigger-squeeze-thumbstick"]),
        this.RegisterFallbacksForProfileId("oculus-touch", ["generic-trigger-squeeze-thumbstick"]),
        this.RegisterFallbacksForProfileId("samsung-gearvr", ["windows-mixed-reality", "generic-trigger-squeeze-touchpad-thumbstick"]),
        this.RegisterFallbacksForProfileId("samsung-odyssey", ["generic-touchpad"]),
        this.RegisterFallbacksForProfileId("valve-index", ["generic-trigger-squeeze-touchpad-thumbstick"]),
        this.RegisterFallbacksForProfileId("generic-hand-select", ["generic-trigger"])
    }
    ,
    i.FindFallbackWithProfileId = function(e) {
        var t = this._Fallbacks[e] || [];
        return t.unshift(e),
        t
    }
    ,
    i.GetMotionControllerWithXRInput = function(e, t, r) {
        var n = this
          , o = [];
        if (r && o.push(r),
        o.push.apply(o, e.profiles || []),
        o.length && !o[0] && o.pop(),
        e.gamepad && e.gamepad.id)
            switch (e.gamepad.id) {
            case (e.gamepad.id.match(/oculus touch/gi) ? e.gamepad.id : void 0):
                o.push("oculus-touch-v2");
                break
            }
        var a = o.indexOf("windows-mixed-reality");
        if (a !== -1 && o.splice(a, 0, "microsoft-mixed-reality"),
        o.length || o.push("generic-trigger"),
        this.UseOnlineRepository) {
            var s = this.PrioritizeOnlineRepository ? this._LoadProfileFromRepository : this._LoadProfilesFromAvailableControllers
              , l = this.PrioritizeOnlineRepository ? this._LoadProfilesFromAvailableControllers : this._LoadProfileFromRepository;
            return s.call(this, o, e, t).catch(function() {
                return l.call(n, o, e, t)
            })
        } else
            return this._LoadProfilesFromAvailableControllers(o, e, t)
    }
    ,
    i.RegisterController = function(e, t) {
        this._AvailableControllers[e] = t
    }
    ,
    i.RegisterFallbacksForProfileId = function(e, t) {
        var r;
        this._Fallbacks[e] ? (r = this._Fallbacks[e]).push.apply(r, t) : this._Fallbacks[e] = t
    }
    ,
    i.UpdateProfilesList = function() {
        return this._ProfilesList = Tools.LoadFileAsync(this.BaseRepositoryUrl + "/profiles/profilesList.json", !1).then(function(e) {
            return JSON.parse(e.toString())
        }),
        this._ProfilesList
    }
    ,
    i.ClearControllerCache = function() {
        controllerCache.forEach(function(e) {
            e.meshes.forEach(function(t) {
                t.dispose(!1, !0)
            })
        }),
        controllerCache.length = 0
    }
    ,
    i._LoadProfileFromRepository = function(e, t, r) {
        var n = this;
        return Promise.resolve().then(function() {
            return n._ProfilesList ? n._ProfilesList : n.UpdateProfilesList()
        }).then(function(o) {
            for (var a = 0; a < e.length; ++a)
                if (!!e[a] && o[e[a]])
                    return e[a];
            throw new Error("neither controller " + e[0] + " nor all fallbacks were found in the repository,")
        }).then(function(o) {
            return n._ProfileLoadingPromises[o] || (n._ProfileLoadingPromises[o] = Tools.LoadFileAsync(n.BaseRepositoryUrl + "/profiles/" + o + "/profile.json", !1).then(function(a) {
                return JSON.parse(a)
            })),
            n._ProfileLoadingPromises[o]
        }).then(function(o) {
            return new WebXRProfiledMotionController(r,t,o,n.BaseRepositoryUrl,n.DisableControllerCache ? void 0 : controllerCache)
        })
    }
    ,
    i._LoadProfilesFromAvailableControllers = function(e, t, r) {
        for (var n = 0; n < e.length; ++n)
            if (!!e[n])
                for (var o = this.FindFallbackWithProfileId(e[n]), a = 0; a < o.length; ++a) {
                    var s = this._AvailableControllers[o[a]];
                    if (s)
                        return Promise.resolve(s(t, r))
                }
        throw new Error("no controller requested was found in the available controllers list")
    }
    ,
    i._AvailableControllers = {},
    i._Fallbacks = {},
    i._ProfileLoadingPromises = {},
    i.BaseRepositoryUrl = "https://immersive-web.github.io/webxr-input-profiles/packages/viewer/dist",
    i.PrioritizeOnlineRepository = !0,
    i.UseOnlineRepository = !0,
    i.DisableControllerCache = !0,
    i
}();
WebXRMotionControllerManager.RegisterController(WebXRGenericTriggerMotionController.ProfileId, function(i, e) {
    return new WebXRGenericTriggerMotionController(e,i.gamepad,i.handedness)
});
WebXRMotionControllerManager.DefaultFallbacks();
var idCount = 0
  , WebXRInputSource = function() {
    function i(e, t, r) {
        var n = this;
        r === void 0 && (r = {}),
        this._scene = e,
        this.inputSource = t,
        this._options = r,
        this._tmpVector = new Vector3,
        this._disposed = !1,
        this.onDisposeObservable = new Observable,
        this.onMeshLoadedObservable = new Observable,
        this.onMotionControllerInitObservable = new Observable,
        this._uniqueId = "controller-" + idCount++ + "-" + t.targetRayMode + "-" + t.handedness,
        this.pointer = new AbstractMesh(this._uniqueId + "-pointer",e),
        this.pointer.rotationQuaternion = new Quaternion,
        this.inputSource.gripSpace && (this.grip = new AbstractMesh(this._uniqueId + "-grip",this._scene),
        this.grip.rotationQuaternion = new Quaternion),
        this._tmpVector.set(0, 0, this._scene.useRightHandedSystem ? -1 : 1),
        this.inputSource.gamepad && this.inputSource.targetRayMode === "tracked-pointer" && WebXRMotionControllerManager.GetMotionControllerWithXRInput(t, e, this._options.forceControllerProfile).then(function(o) {
            n.motionController = o,
            n.onMotionControllerInitObservable.notifyObservers(o),
            !n._options.doNotLoadControllerMesh && !n.motionController._doNotLoadControllerMesh && n.motionController.loadModel().then(function(a) {
                var s;
                a && n.motionController && n.motionController.rootMesh && (n._options.renderingGroupId && (n.motionController.rootMesh.renderingGroupId = n._options.renderingGroupId,
                n.motionController.rootMesh.getChildMeshes(!1).forEach(function(l) {
                    return l.renderingGroupId = n._options.renderingGroupId
                })),
                n.onMeshLoadedObservable.notifyObservers(n.motionController.rootMesh),
                n.motionController.rootMesh.parent = n.grip || n.pointer,
                n.motionController.disableAnimation = !!n._options.disableMotionControllerAnimation),
                n._disposed && ((s = n.motionController) === null || s === void 0 || s.dispose())
            })
        }, function() {
            Tools.Warn("Could not find a matching motion controller for the registered input source")
        })
    }
    return Object.defineProperty(i.prototype, "uniqueId", {
        get: function() {
            return this._uniqueId
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.dispose = function() {
        this.grip && this.grip.dispose(!0),
        this.motionController && this.motionController.dispose(),
        this.pointer.dispose(!0),
        this.onMotionControllerInitObservable.clear(),
        this.onMeshLoadedObservable.clear(),
        this.onDisposeObservable.notifyObservers(this),
        this.onDisposeObservable.clear(),
        this._disposed = !0
    }
    ,
    i.prototype.getWorldPointerRayToRef = function(e, t) {
        t === void 0 && (t = !1);
        var r = t && this.grip ? this.grip : this.pointer;
        Vector3.TransformNormalToRef(this._tmpVector, r.getWorldMatrix(), e.direction),
        e.direction.normalize(),
        e.origin.copyFrom(r.absolutePosition),
        e.length = 1e3
    }
    ,
    i.prototype.updateFromXRFrame = function(e, t, r) {
        var n = e.getPose(this.inputSource.targetRaySpace, t);
        if (this._lastXRPose = n,
        n) {
            var o = n.transform.position;
            this.pointer.position.set(o.x, o.y, o.z);
            var a = n.transform.orientation;
            this.pointer.rotationQuaternion.set(a.x, a.y, a.z, a.w),
            this._scene.useRightHandedSystem || (this.pointer.position.z *= -1,
            this.pointer.rotationQuaternion.z *= -1,
            this.pointer.rotationQuaternion.w *= -1),
            this.pointer.parent = r.parent
        }
        if (this.inputSource.gripSpace && this.grip) {
            var s = e.getPose(this.inputSource.gripSpace, t);
            if (s) {
                var o = s.transform.position
                  , l = s.transform.orientation;
                this.grip.position.set(o.x, o.y, o.z),
                this.grip.rotationQuaternion.set(l.x, l.y, l.z, l.w),
                this._scene.useRightHandedSystem || (this.grip.position.z *= -1,
                this.grip.rotationQuaternion.z *= -1,
                this.grip.rotationQuaternion.w *= -1)
            }
            this.grip.parent = r.parent
        }
        this.motionController && this.motionController.updateFromXRFrame(e)
    }
    ,
    i
}()
  , WebXRInput = function() {
    function i(e, t, r) {
        var n = this;
        if (r === void 0 && (r = {}),
        this.xrSessionManager = e,
        this.xrCamera = t,
        this.options = r,
        this.controllers = [],
        this.onControllerAddedObservable = new Observable,
        this.onControllerRemovedObservable = new Observable,
        this._onInputSourcesChange = function(o) {
            n._addAndRemoveControllers(o.added, o.removed)
        }
        ,
        this._sessionEndedObserver = this.xrSessionManager.onXRSessionEnded.add(function() {
            n._addAndRemoveControllers([], n.controllers.map(function(o) {
                return o.inputSource
            }))
        }),
        this._sessionInitObserver = this.xrSessionManager.onXRSessionInit.add(function(o) {
            o.addEventListener("inputsourceschange", n._onInputSourcesChange)
        }),
        this._frameObserver = this.xrSessionManager.onXRFrameObservable.add(function(o) {
            n.controllers.forEach(function(a) {
                a.updateFromXRFrame(o, n.xrSessionManager.referenceSpace, n.xrCamera)
            })
        }),
        this.options.customControllersRepositoryURL && (WebXRMotionControllerManager.BaseRepositoryUrl = this.options.customControllersRepositoryURL),
        WebXRMotionControllerManager.UseOnlineRepository = !this.options.disableOnlineControllerRepository,
        WebXRMotionControllerManager.UseOnlineRepository)
            try {
                WebXRMotionControllerManager.UpdateProfilesList().catch(function() {
                    WebXRMotionControllerManager.UseOnlineRepository = !1
                })
            } catch {
                WebXRMotionControllerManager.UseOnlineRepository = !1
            }
    }
    return i.prototype._addAndRemoveControllers = function(e, t) {
        for (var r = this, n = this.controllers.map(function(h) {
            return h.inputSource
        }), o = 0, a = e; o < a.length; o++) {
            var s = a[o];
            if (n.indexOf(s) === -1) {
                var l = new WebXRInputSource(this.xrSessionManager.scene,s,__assign(__assign({}, this.options.controllerOptions || {}), {
                    forceControllerProfile: this.options.forceInputProfile,
                    doNotLoadControllerMesh: this.options.doNotLoadControllerMeshes,
                    disableMotionControllerAnimation: this.options.disableControllerAnimation
                }));
                this.controllers.push(l),
                this.onControllerAddedObservable.notifyObservers(l)
            }
        }
        var u = []
          , c = [];
        this.controllers.forEach(function(h) {
            t.indexOf(h.inputSource) === -1 ? u.push(h) : c.push(h)
        }),
        this.controllers = u,
        c.forEach(function(h) {
            r.onControllerRemovedObservable.notifyObservers(h),
            h.dispose()
        })
    }
    ,
    i.prototype.dispose = function() {
        this.controllers.forEach(function(e) {
            e.dispose()
        }),
        this.xrSessionManager.onXRFrameObservable.remove(this._frameObserver),
        this.xrSessionManager.onXRSessionInit.remove(this._sessionInitObserver),
        this.xrSessionManager.onXRSessionEnded.remove(this._sessionEndedObserver),
        this.onControllerAddedObservable.clear(),
        this.onControllerRemovedObservable.clear(),
        WebXRMotionControllerManager.ClearControllerCache()
    }
    ,
    i
}()
  , WebXRAbstractFeature = function() {
    function i(e) {
        this._xrSessionManager = e,
        this._attached = !1,
        this._removeOnDetach = [],
        this.isDisposed = !1,
        this.disableAutoAttach = !1,
        this.xrNativeFeatureName = ""
    }
    return Object.defineProperty(i.prototype, "attached", {
        get: function() {
            return this._attached
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.attach = function(e) {
        var t = this;
        if (this.isDisposed)
            return !1;
        if (e)
            this.attached && this.detach();
        else if (this.attached)
            return !1;
        return this._attached = !0,
        this._addNewAttachObserver(this._xrSessionManager.onXRFrameObservable, function(r) {
            return t._onXRFrame(r)
        }),
        !0
    }
    ,
    i.prototype.detach = function() {
        return this._attached ? (this._attached = !1,
        this._removeOnDetach.forEach(function(e) {
            e.observable.remove(e.observer)
        }),
        !0) : (this.disableAutoAttach = !0,
        !1)
    }
    ,
    i.prototype.dispose = function() {
        this.detach(),
        this.isDisposed = !0
    }
    ,
    i.prototype.isCompatible = function() {
        return !0
    }
    ,
    i.prototype._addNewAttachObserver = function(e, t) {
        this._removeOnDetach.push({
            observable: e,
            observer: e.add(t)
        })
    }
    ,
    i
}()
  , WebXRControllerPointerSelection = function(i) {
    __extends(e, i);
    function e(t, r) {
        var n = i.call(this, t) || this;
        return n._options = r,
        n._attachController = function(o) {
            if (!n._controllers[o.uniqueId]) {
                var a = n._generateNewMeshPair(o.pointer)
                  , s = a.laserPointer
                  , l = a.selectionMesh;
                switch (n._controllers[o.uniqueId] = {
                    xrController: o,
                    laserPointer: s,
                    selectionMesh: l,
                    meshUnderPointer: null,
                    pick: null,
                    tmpRay: new Ray(new Vector3,new Vector3),
                    disabledByNearInteraction: !1,
                    id: e._idCounter++
                },
                n._attachedController ? !n._options.enablePointerSelectionOnAllControllers && n._options.preferredHandedness && o.inputSource.handedness === n._options.preferredHandedness && (n._attachedController = o.uniqueId) : n._options.enablePointerSelectionOnAllControllers || (n._attachedController = o.uniqueId),
                o.inputSource.targetRayMode) {
                case "tracked-pointer":
                    return n._attachTrackedPointerRayMode(o);
                case "gaze":
                    return n._attachGazeMode(o);
                case "screen":
                    return n._attachScreenRayMode(o)
                }
            }
        }
        ,
        n._controllers = {},
        n._tmpVectorForPickCompare = new Vector3,
        n.disablePointerLighting = !0,
        n.disableSelectionMeshLighting = !0,
        n.displayLaserPointer = !0,
        n.displaySelectionMesh = !0,
        n.laserPointerPickedColor = new Color3(.9,.9,.9),
        n.laserPointerDefaultColor = new Color3(.7,.7,.7),
        n.selectionMeshDefaultColor = new Color3(.8,.8,.8),
        n.selectionMeshPickedColor = new Color3(.3,.3,1),
        n._identityMatrix = Matrix.Identity(),
        n._screenCoordinatesRef = Vector3.Zero(),
        n._viewportRef = new Viewport(0,0,0,0),
        n._scene = n._xrSessionManager.scene,
        n
    }
    return e.prototype.attach = function() {
        var t = this;
        if (!i.prototype.attach.call(this))
            return !1;
        if (this._options.xrInput.controllers.forEach(this._attachController),
        this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable, this._attachController),
        this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable, function(s) {
            t._detachController(s.uniqueId)
        }),
        this._scene.constantlyUpdateMeshUnderPointer = !0,
        this._options.gazeCamera) {
            var r = this._options.gazeCamera
              , n = this._generateNewMeshPair(r)
              , o = n.laserPointer
              , a = n.selectionMesh;
            this._controllers.camera = {
                webXRCamera: r,
                laserPointer: o,
                selectionMesh: a,
                meshUnderPointer: null,
                pick: null,
                tmpRay: new Ray(new Vector3,new Vector3),
                disabledByNearInteraction: !1,
                id: e._idCounter++
            },
            this._attachGazeMode()
        }
        return !0
    }
    ,
    e.prototype.detach = function() {
        var t = this;
        return i.prototype.detach.call(this) ? (Object.keys(this._controllers).forEach(function(r) {
            t._detachController(r)
        }),
        !0) : !1
    }
    ,
    e.prototype.getMeshUnderPointer = function(t) {
        return this._controllers[t] ? this._controllers[t].meshUnderPointer : null
    }
    ,
    e.prototype.getXRControllerByPointerId = function(t) {
        for (var r = Object.keys(this._controllers), n = 0; n < r.length; ++n)
            if (this._controllers[r[n]].id === t)
                return this._controllers[r[n]].xrController || null;
        return null
    }
    ,
    e.prototype._getPointerSelectionDisabledByPointerId = function(t) {
        for (var r = Object.keys(this._controllers), n = 0; n < r.length; ++n)
            if (this._controllers[r[n]].id === t)
                return this._controllers[r[n]].disabledByNearInteraction;
        return !0
    }
    ,
    e.prototype._setPointerSelectionDisabledByPointerId = function(t, r) {
        for (var n = Object.keys(this._controllers), o = 0; o < n.length; ++o)
            if (this._controllers[n[o]].id === t) {
                this._controllers[n[o]].disabledByNearInteraction = r;
                return
            }
    }
    ,
    e.prototype._onXRFrame = function(t) {
        var r = this;
        Object.keys(this._controllers).forEach(function(n) {
            var o = r._controllers[n];
            if (!r._options.enablePointerSelectionOnAllControllers && n !== r._attachedController || o.disabledByNearInteraction) {
                o.selectionMesh.isVisible = !1,
                o.laserPointer.isVisible = !1,
                o.pick = null;
                return
            }
            o.laserPointer.isVisible = r.displayLaserPointer;
            var a;
            if (o.xrController)
                a = o.xrController.pointer.position,
                o.xrController.getWorldPointerRayToRef(o.tmpRay);
            else if (o.webXRCamera)
                a = o.webXRCamera.position,
                o.webXRCamera.getForwardRayToRef(o.tmpRay);
            else
                return;
            if (r._options.maxPointerDistance && (o.tmpRay.length = r._options.maxPointerDistance),
            !r._options.disableScenePointerVectorUpdate && a) {
                var s = r._xrSessionManager.scene
                  , l = r._options.xrInput.xrCamera;
                l && (l.viewport.toGlobalToRef(s.getEngine().getRenderWidth(), s.getEngine().getRenderHeight(), r._viewportRef),
                Vector3.ProjectToRef(a, r._identityMatrix, s.getTransformMatrix(), r._viewportRef, r._screenCoordinatesRef),
                typeof r._screenCoordinatesRef.x == "number" && typeof r._screenCoordinatesRef.y == "number" && !isNaN(r._screenCoordinatesRef.x) && !isNaN(r._screenCoordinatesRef.y) && (s.pointerX = r._screenCoordinatesRef.x,
                s.pointerY = r._screenCoordinatesRef.y,
                o.screenCoordinates = {
                    x: r._screenCoordinatesRef.x,
                    y: r._screenCoordinatesRef.y
                }))
            }
            var u = null;
            r._utilityLayerScene && (u = r._utilityLayerScene.pickWithRay(o.tmpRay, r._utilityLayerScene.pointerMovePredicate || r.raySelectionPredicate));
            var c = r._scene.pickWithRay(o.tmpRay, r._scene.pointerMovePredicate || r.raySelectionPredicate);
            !u || !u.hit ? o.pick = c : !c || !c.hit || u.distance < c.distance ? o.pick = u : o.pick = c,
            o.pick && o.xrController && (o.pick.aimTransform = o.xrController.pointer,
            o.pick.gripTransform = o.xrController.grip || null);
            var h = o.pick;
            if (h && h.pickedPoint && h.hit) {
                r._updatePointerDistance(o.laserPointer, h.distance),
                o.selectionMesh.position.copyFrom(h.pickedPoint),
                o.selectionMesh.scaling.x = Math.sqrt(h.distance),
                o.selectionMesh.scaling.y = Math.sqrt(h.distance),
                o.selectionMesh.scaling.z = Math.sqrt(h.distance);
                var f = r._convertNormalToDirectionOfRay(h.getNormal(!0), o.tmpRay)
                  , d = .001;
                if (o.selectionMesh.position.copyFrom(h.pickedPoint),
                f) {
                    var _ = Vector3.Cross(Axis.Y, f)
                      , g = Vector3.Cross(f, _);
                    Vector3.RotationFromAxisToRef(g, f, _, o.selectionMesh.rotation),
                    o.selectionMesh.position.addInPlace(f.scale(d))
                }
                o.selectionMesh.isVisible = r.displaySelectionMesh,
                o.meshUnderPointer = h.pickedMesh
            } else
                o.selectionMesh.isVisible = !1,
                r._updatePointerDistance(o.laserPointer, 1),
                o.meshUnderPointer = null
        })
    }
    ,
    Object.defineProperty(e.prototype, "_utilityLayerScene", {
        get: function() {
            return this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._attachGazeMode = function(t) {
        var r = this
          , n = this._controllers[t && t.uniqueId || "camera"]
          , o = this._options.timeToSelect || 3e3
          , a = this._options.useUtilityLayer ? this._utilityLayerScene : this._scene
          , s = new PickingInfo
          , l = CreateTorus("selection", {
            diameter: .0035 * 15,
            thickness: .0025 * 6,
            tessellation: 20
        }, a);
        l.isVisible = !1,
        l.isPickable = !1,
        l.parent = n.selectionMesh;
        var u = 0
          , c = !1
          , h = {
            pointerId: n.id,
            pointerType: "xr"
        };
        n.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(function() {
            if (!!n.pick) {
                if (r._augmentPointerInit(h, n.id, n.screenCoordinates),
                n.laserPointer.material.alpha = 0,
                l.isVisible = !1,
                n.pick.hit)
                    if (r._pickingMoved(s, n.pick))
                        c && (r._options.disablePointerUpOnTouchOut || r._scene.simulatePointerUp(n.pick, h)),
                        c = !1,
                        u = 0;
                    else if (u > o / 10 && (l.isVisible = !0),
                    u += r._scene.getEngine().getDeltaTime(),
                    u >= o)
                        r._scene.simulatePointerDown(n.pick, h),
                        c = !0,
                        r._options.disablePointerUpOnTouchOut && r._scene.simulatePointerUp(n.pick, h),
                        l.isVisible = !1;
                    else {
                        var f = 1 - u / o;
                        l.scaling.set(f, f, f)
                    }
                else
                    c = !1,
                    u = 0;
                r._scene.simulatePointerMove(n.pick, h),
                s = n.pick
            }
        }),
        this._options.renderingGroupId !== void 0 && (l.renderingGroupId = this._options.renderingGroupId),
        t && t.onDisposeObservable.addOnce(function() {
            n.pick && !r._options.disablePointerUpOnTouchOut && c && (r._scene.simulatePointerUp(n.pick, h),
            n.finalPointerUpTriggered = !0),
            l.dispose()
        })
    }
    ,
    e.prototype._attachScreenRayMode = function(t) {
        var r = this
          , n = this._controllers[t.uniqueId]
          , o = !1
          , a = {
            pointerId: n.id,
            pointerType: "xr"
        };
        n.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(function() {
            r._augmentPointerInit(a, n.id, n.screenCoordinates),
            !(!n.pick || r._options.disablePointerUpOnTouchOut && o) && (o ? r._scene.simulatePointerMove(n.pick, a) : (r._scene.simulatePointerDown(n.pick, a),
            o = !0,
            r._options.disablePointerUpOnTouchOut && r._scene.simulatePointerUp(n.pick, a)))
        }),
        t.onDisposeObservable.addOnce(function() {
            r._augmentPointerInit(a, n.id, n.screenCoordinates),
            n.pick && o && !r._options.disablePointerUpOnTouchOut && (r._scene.simulatePointerUp(n.pick, a),
            n.finalPointerUpTriggered = !0)
        })
    }
    ,
    e.prototype._attachTrackedPointerRayMode = function(t) {
        var r = this
          , n = this._controllers[t.uniqueId];
        if (this._options.forceGazeMode)
            return this._attachGazeMode(t);
        var o = {
            pointerId: n.id,
            pointerType: "xr"
        };
        if (n.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(function() {
            n.laserPointer.material.disableLighting = r.disablePointerLighting,
            n.selectionMesh.material.disableLighting = r.disableSelectionMeshLighting,
            n.pick && (r._augmentPointerInit(o, n.id, n.screenCoordinates),
            r._scene.simulatePointerMove(n.pick, o))
        }),
        t.inputSource.gamepad) {
            var a = function(u) {
                r._options.overrideButtonId && (n.selectionComponent = u.getComponent(r._options.overrideButtonId)),
                n.selectionComponent || (n.selectionComponent = u.getMainComponent()),
                n.onButtonChangedObserver = n.selectionComponent.onButtonStateChangedObservable.add(function(c) {
                    if (c.changes.pressed) {
                        var h = c.changes.pressed.current;
                        n.pick ? (r._options.enablePointerSelectionOnAllControllers || t.uniqueId === r._attachedController) && (r._augmentPointerInit(o, n.id, n.screenCoordinates),
                        h ? (r._scene.simulatePointerDown(n.pick, o),
                        n.selectionMesh.material.emissiveColor = r.selectionMeshPickedColor,
                        n.laserPointer.material.emissiveColor = r.laserPointerPickedColor) : (r._scene.simulatePointerUp(n.pick, o),
                        n.selectionMesh.material.emissiveColor = r.selectionMeshDefaultColor,
                        n.laserPointer.material.emissiveColor = r.laserPointerDefaultColor)) : h && !r._options.enablePointerSelectionOnAllControllers && !r._options.disableSwitchOnClick && (r._attachedController = t.uniqueId)
                    }
                })
            };
            t.motionController ? a(t.motionController) : t.onMotionControllerInitObservable.add(a)
        } else {
            var s = function(u) {
                r._augmentPointerInit(o, n.id, n.screenCoordinates),
                n.xrController && u.inputSource === n.xrController.inputSource && n.pick && (r._scene.simulatePointerDown(n.pick, o),
                n.selectionMesh.material.emissiveColor = r.selectionMeshPickedColor,
                n.laserPointer.material.emissiveColor = r.laserPointerPickedColor)
            }
              , l = function(u) {
                r._augmentPointerInit(o, n.id, n.screenCoordinates),
                n.xrController && u.inputSource === n.xrController.inputSource && n.pick && (r._scene.simulatePointerUp(n.pick, o),
                n.selectionMesh.material.emissiveColor = r.selectionMeshDefaultColor,
                n.laserPointer.material.emissiveColor = r.laserPointerDefaultColor)
            };
            n.eventListeners = {
                selectend: l,
                selectstart: s
            },
            this._xrSessionManager.session.addEventListener("selectstart", s),
            this._xrSessionManager.session.addEventListener("selectend", l)
        }
    }
    ,
    e.prototype._convertNormalToDirectionOfRay = function(t, r) {
        if (t) {
            var n = Math.acos(Vector3.Dot(t, r.direction));
            n < Math.PI / 2 && t.scaleInPlace(-1)
        }
        return t
    }
    ,
    e.prototype._detachController = function(t) {
        var r = this
          , n = this._controllers[t];
        !n || (n.selectionComponent && n.onButtonChangedObserver && n.selectionComponent.onButtonStateChangedObservable.remove(n.onButtonChangedObserver),
        n.onFrameObserver && this._xrSessionManager.onXRFrameObservable.remove(n.onFrameObserver),
        n.eventListeners && Object.keys(n.eventListeners).forEach(function(o) {
            var a = n.eventListeners && n.eventListeners[o];
            a && r._xrSessionManager.session.removeEventListener(o, a)
        }),
        this._xrSessionManager.scene.onBeforeRenderObservable.addOnce(function() {
            try {
                if (!n.finalPointerUpTriggered) {
                    var o = {
                        pointerId: n.id,
                        pointerType: "xr"
                    };
                    r._augmentPointerInit(o, n.id, n.screenCoordinates),
                    r._scene.simulatePointerUp(new PickingInfo, o)
                }
                if (n.selectionMesh.dispose(),
                n.laserPointer.dispose(),
                delete r._controllers[t],
                r._attachedController === t) {
                    var a = Object.keys(r._controllers);
                    a.length ? r._attachedController = a[0] : r._attachedController = ""
                }
            } catch {
                Tools.Warn("controller already detached.")
            }
        }))
    }
    ,
    e.prototype._generateNewMeshPair = function(t) {
        var r = this._options.useUtilityLayer ? this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene : this._scene
          , n = this._options.customLasterPointerMeshGenerator ? this._options.customLasterPointerMeshGenerator() : CreateCylinder("laserPointer", {
            height: 1,
            diameterTop: 2e-4,
            diameterBottom: .004,
            tessellation: 20,
            subdivisions: 1
        }, r);
        n.parent = t;
        var o = new StandardMaterial("laserPointerMat",r);
        o.emissiveColor = this.laserPointerDefaultColor,
        o.alpha = .7,
        n.material = o,
        n.rotation.x = Math.PI / 2,
        this._updatePointerDistance(n, 1),
        n.isPickable = !1,
        n.isVisible = !1;
        var a = this._options.customSelectionMeshGenerator ? this._options.customSelectionMeshGenerator() : CreateTorus("gazeTracker", {
            diameter: .0035 * 3,
            thickness: .0025 * 3,
            tessellation: 20
        }, r);
        a.bakeCurrentTransformIntoVertices(),
        a.isPickable = !1,
        a.isVisible = !1;
        var s = new StandardMaterial("targetMat",r);
        return s.specularColor = Color3.Black(),
        s.emissiveColor = this.selectionMeshDefaultColor,
        s.backFaceCulling = !1,
        a.material = s,
        this._options.renderingGroupId !== void 0 && (n.renderingGroupId = this._options.renderingGroupId,
        a.renderingGroupId = this._options.renderingGroupId),
        {
            laserPointer: n,
            selectionMesh: a
        }
    }
    ,
    e.prototype._pickingMoved = function(t, r) {
        var n;
        if (!t.hit || !r.hit || !t.pickedMesh || !t.pickedPoint || !r.pickedMesh || !r.pickedPoint || t.pickedMesh !== r.pickedMesh)
            return !0;
        (n = t.pickedPoint) === null || n === void 0 || n.subtractToRef(r.pickedPoint, this._tmpVectorForPickCompare),
        this._tmpVectorForPickCompare.set(Math.abs(this._tmpVectorForPickCompare.x), Math.abs(this._tmpVectorForPickCompare.y), Math.abs(this._tmpVectorForPickCompare.z));
        var o = (this._options.gazeModePointerMovedFactor || 1) * .01 * r.distance
          , a = this._tmpVectorForPickCompare.length();
        return a > o
    }
    ,
    e.prototype._updatePointerDistance = function(t, r) {
        r === void 0 && (r = 100),
        t.scaling.y = r,
        this._scene.useRightHandedSystem && (r *= -1),
        t.position.z = r / 2 + .05
    }
    ,
    e.prototype._augmentPointerInit = function(t, r, n) {
        t.pointerId = r,
        t.pointerType = "xr",
        n && (t.screenX = n.x,
        t.screenY = n.y)
    }
    ,
    Object.defineProperty(e.prototype, "lasterPointerDefaultColor", {
        get: function() {
            return this.laserPointerDefaultColor
        },
        enumerable: !1,
        configurable: !0
    }),
    e._idCounter = 200,
    e.Name = WebXRFeatureName.POINTER_SELECTION,
    e.Version = 1,
    e
}(WebXRAbstractFeature);
WebXRFeaturesManager.AddWebXRFeature(WebXRControllerPointerSelection.Name, function(i, e) {
    return function() {
        return new WebXRControllerPointerSelection(i,e)
    }
}, WebXRControllerPointerSelection.Version, !0);
SubMesh.prototype._projectOnTrianglesToRef = function(i, e, t, r, n, o) {
    for (var a = TmpVectors.Vector3[0], s = TmpVectors.Vector3[1], l = 1 / 0, u = this.indexStart; u < this.indexStart + this.indexCount - (3 - r); u += r) {
        var c = t[u]
          , h = t[u + 1]
          , f = t[u + 2];
        if (n && f === 4294967295) {
            u += 2;
            continue
        }
        var d = e[c]
          , _ = e[h]
          , g = e[f];
        if (!(!d || !_ || !g)) {
            var m = Vector3.ProjectOnTriangleToRef(i, d, _, g, s);
            m < l && (a.copyFrom(s),
            l = m)
        }
    }
    return o.copyFrom(a),
    l
}
;
SubMesh.prototype._projectOnUnIndexedTrianglesToRef = function(i, e, t, r) {
    for (var n = TmpVectors.Vector3[0], o = TmpVectors.Vector3[1], a = 1 / 0, s = this.verticesStart; s < this.verticesStart + this.verticesCount; s += 3) {
        var l = e[s]
          , u = e[s + 1]
          , c = e[s + 2]
          , h = Vector3.ProjectOnTriangleToRef(i, l, u, c, o);
        h < a && (n.copyFrom(o),
        a = h)
    }
    return r.copyFrom(n),
    a
}
;
SubMesh.prototype.projectToRef = function(i, e, t, r) {
    var n = this.getMaterial();
    if (!n)
        return -1;
    var o = 3
      , a = !1;
    switch (n.fillMode) {
    case 3:
    case 4:
    case 5:
    case 6:
    case 8:
        return -1;
    case 7:
        o = 1,
        a = !0;
        break
    }
    return this._mesh.getClassName() === "InstancedLinesMesh" || this._mesh.getClassName() === "LinesMesh" ? -1 : !t.length && this._mesh._unIndexed ? this._projectOnUnIndexedTrianglesToRef(i, e, t, r) : this._projectOnTrianglesToRef(i, e, t, o, a, r)
}
;
var WebXRNearInteraction = function(i) {
    __extends(e, i);
    function e(t, r) {
        var n = i.call(this, t) || this;
        return n._options = r,
        n._attachController = function(o) {
            if (!n._controllers[o.uniqueId]) {
                var a = n._generateNewHandTipMesh()
                  , s = n._generateVisualCue();
                switch (n._controllers[o.uniqueId] = {
                    xrController: o,
                    meshUnderPointer: null,
                    nearInteractionMesh: null,
                    pick: null,
                    pickIndexMeshTip: a,
                    grabRay: new Ray(new Vector3,new Vector3),
                    hoverInteraction: !1,
                    nearInteraction: !1,
                    grabInteraction: !1,
                    id: e._idCounter++,
                    pickedPointVisualCue: s
                },
                n._attachedController ? !n._options.enableNearInteractionOnAllControllers && n._options.preferredHandedness && o.inputSource.handedness === n._options.preferredHandedness && (n._attachedController = o.uniqueId) : n._options.enableNearInteractionOnAllControllers || (n._attachedController = o.uniqueId),
                o.inputSource.targetRayMode) {
                case "tracked-pointer":
                    return n._attachNearInteractionMode(o);
                case "gaze":
                    return null;
                case "screen":
                    return null
                }
            }
        }
        ,
        n._controllers = {},
        n._farInteractionFeature = null,
        n.selectionMeshDefaultColor = new Color3(.8,.8,.8),
        n.selectionMeshPickedColor = new Color3(.3,.3,1),
        n._hoverRadius = .1,
        n._pickRadius = .02,
        n._nearGrabLengthScale = 5,
        n._indexTipQuaternion = new Quaternion,
        n._indexTipOrientationVector = Vector3.Zero(),
        n._scene = n._xrSessionManager.scene,
        n._options.farInteractionFeature && (n._farInteractionFeature = n._options.farInteractionFeature),
        n
    }
    return e.prototype.attach = function() {
        var t = this;
        return i.prototype.attach.call(this) ? (this._options.xrInput.controllers.forEach(this._attachController),
        this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable, this._attachController),
        this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable, function(r) {
            t._detachController(r.uniqueId)
        }),
        this._scene.constantlyUpdateMeshUnderPointer = !0,
        !0) : !1
    }
    ,
    e.prototype.detach = function() {
        var t = this;
        return i.prototype.detach.call(this) ? (Object.keys(this._controllers).forEach(function(r) {
            t._detachController(r)
        }),
        !0) : !1
    }
    ,
    e.prototype.getMeshUnderPointer = function(t) {
        return this._controllers[t] ? this._controllers[t].meshUnderPointer : null
    }
    ,
    e.prototype.getXRControllerByPointerId = function(t) {
        for (var r = Object.keys(this._controllers), n = 0; n < r.length; ++n)
            if (this._controllers[r[n]].id === t)
                return this._controllers[r[n]].xrController || null;
        return null
    }
    ,
    e.prototype.setFarInteractionFeature = function(t) {
        this._farInteractionFeature = t
    }
    ,
    e.prototype._nearPickPredicate = function(t) {
        return t.isEnabled() && t.isVisible && t.isPickable && t.isNearPickable
    }
    ,
    e.prototype._nearGrabPredicate = function(t) {
        return t.isEnabled() && t.isVisible && t.isPickable && t.isNearGrabbable
    }
    ,
    e.prototype._nearInteractionPredicate = function(t) {
        return t.isEnabled() && t.isVisible && t.isPickable && (t.isNearPickable || t.isNearGrabbable)
    }
    ,
    e.prototype._controllerAvailablePredicate = function(t, r) {
        for (var n = t; n; ) {
            if (n.reservedDataStore && n.reservedDataStore.nearInteraction && n.reservedDataStore.nearInteraction.excludedControllerId === r)
                return !1;
            n = n.parent
        }
        return !0
    }
    ,
    e.prototype._onXRFrame = function(t) {
        var r = this;
        Object.keys(this._controllers).forEach(function(n) {
            var o = r._controllers[n];
            if (!r._options.enableNearInteractionOnAllControllers && n !== r._attachedController || !o.xrController || !o.xrController.inputSource.hand) {
                o.pick = null;
                return
            }
            if (o.hoverInteraction = !1,
            o.nearInteraction = !1,
            o.xrController) {
                var a = o.xrController.inputSource.hand;
                if (a) {
                    var s = a.get("index-finger-tip");
                    if (s) {
                        var l = t.getJointPose(s, r._xrSessionManager.referenceSpace);
                        if (l && l.transform) {
                            var u = r._scene.useRightHandedSystem ? 1 : -1
                              , c = l.transform.position
                              , h = l.transform.orientation;
                            r._indexTipQuaternion.set(h.x, h.y, h.z * u, h.w * u),
                            o.pickIndexMeshTip && o.pickIndexMeshTip.position.set(c.x, c.y, c.z * u);
                            var f = r._nearGrabLengthScale * r._hoverRadius;
                            o.grabRay.origin.set(c.x, c.y, c.z * u),
                            r._indexTipQuaternion.toEulerAnglesToRef(r._indexTipOrientationVector),
                            o.grabRay.direction.set(r._indexTipOrientationVector.x, r._indexTipOrientationVector.y, r._indexTipOrientationVector.z),
                            o.grabRay.length = f
                        }
                    }
                }
            } else
                return;
            var d = function(S, P) {
                var R = null;
                return !P || !P.hit ? R = S : !S || !S.hit || P.distance < S.distance ? R = P : R = S,
                R
            }
              , _ = function(S) {
                var P = new PickingInfo
                  , R = !1
                  , M = S && S.pickedPoint && S.hit;
                return S != null && S.pickedPoint && (R = S.pickedPoint.x === 0 && S.pickedPoint.y === 0 && S.pickedPoint.z === 0),
                M && !R && (P = S),
                P
            };
            if (!o.grabInteraction) {
                var g = null
                  , m = null;
                r._options.useUtilityLayer && r._utilityLayerScene && (m = r._pickWithSphere(o, r._hoverRadius, r._utilityLayerScene, function(S) {
                    return r._nearInteractionPredicate(S)
                }));
                var v = r._pickWithSphere(o, r._hoverRadius, r._scene, function(S) {
                    return r._nearInteractionPredicate(S)
                })
                  , y = d(v, m);
                if (y && y.hit && (g = _(y),
                g.hit && (o.hoverInteraction = !0)),
                o.pickIndexMeshTip && o.hoverInteraction) {
                    var b = null;
                    r._options.useUtilityLayer && r._utilityLayerScene && (b = r._pickWithSphere(o, r._pickRadius, r._utilityLayerScene, function(S) {
                        return r._nearPickPredicate(S)
                    }));
                    var T = r._pickWithSphere(o, r._pickRadius, r._scene, function(S) {
                        return r._nearPickPredicate(S)
                    })
                      , C = d(T, b)
                      , A = _(C);
                    A.hit && (g = A,
                    o.nearInteraction = !0)
                }
                o.pick = g,
                o.pick && o.pick.pickedPoint && o.pick.hit ? (o.meshUnderPointer = o.pick.pickedMesh,
                o.pickedPointVisualCue.position.copyFrom(o.pick.pickedPoint),
                o.pickedPointVisualCue.isVisible = !0,
                r._farInteractionFeature && r._farInteractionFeature.attached && r._farInteractionFeature._setPointerSelectionDisabledByPointerId(o.id, !0)) : (o.meshUnderPointer = null,
                o.pickedPointVisualCue.isVisible = !1,
                r._farInteractionFeature && r._farInteractionFeature.attached && r._farInteractionFeature._setPointerSelectionDisabledByPointerId(o.id, !1))
            }
        })
    }
    ,
    Object.defineProperty(e.prototype, "_utilityLayerScene", {
        get: function() {
            return this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._generateVisualCue = function() {
        var t = this._options.useUtilityLayer ? this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene : this._scene
          , r = CreateSphere("nearInteraction", {
            diameter: .0035 * 3
        }, t);
        r.bakeCurrentTransformIntoVertices(),
        r.isPickable = !1,
        r.isVisible = !1,
        r.rotationQuaternion = Quaternion.Identity();
        var n = new StandardMaterial("targetMat",t);
        return n.specularColor = Color3.Black(),
        n.emissiveColor = this.selectionMeshDefaultColor,
        n.backFaceCulling = !1,
        r.material = n,
        r
    }
    ,
    e.prototype._isControllerReadyForNearInteraction = function(t) {
        return this._farInteractionFeature ? this._farInteractionFeature._getPointerSelectionDisabledByPointerId(t) : !0
    }
    ,
    e.prototype._attachNearInteractionMode = function(t) {
        var r = this
          , n = this._controllers[t.uniqueId]
          , o = {
            pointerId: n.id,
            pointerType: "xr"
        };
        n.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(function() {
            !r._options.enableNearInteractionOnAllControllers && t.uniqueId !== r._attachedController || !n.xrController || !n.xrController.inputSource.hand || (n.pick && (n.pick.ray = n.grabRay),
            n.pick && r._isControllerReadyForNearInteraction(n.id) && r._scene.simulatePointerMove(n.pick, o),
            n.nearInteraction && n.pick && n.pick.hit ? n.nearInteractionMesh || (r._scene.simulatePointerDown(n.pick, o),
            n.nearInteractionMesh = n.meshUnderPointer) : n.nearInteractionMesh && n.pick && (r._scene.simulatePointerUp(n.pick, o),
            n.nearInteractionMesh = null))
        });
        var a = function(c) {
            r._options.enableNearInteractionOnAllControllers || t.uniqueId === r._attachedController && r._isControllerReadyForNearInteraction(n.id) ? (n.pick && (n.pick.ray = n.grabRay),
            c && n.pick && n.meshUnderPointer && r._nearGrabPredicate(n.meshUnderPointer) ? (n.grabInteraction = !0,
            n.pickedPointVisualCue.isVisible = !1,
            r._scene.simulatePointerDown(n.pick, o)) : !c && n.pick && n.grabInteraction && (r._scene.simulatePointerUp(n.pick, o),
            n.grabInteraction = !1,
            n.pickedPointVisualCue.isVisible = !0)) : c && !r._options.enableNearInteractionOnAllControllers && !r._options.disableSwitchOnClick && (r._attachedController = t.uniqueId)
        };
        if (t.inputSource.gamepad) {
            var s = function(c) {
                n.squeezeComponent = c.getComponent("grasp"),
                n.squeezeComponent ? n.onSqueezeButtonChangedObserver = n.squeezeComponent.onButtonStateChangedObservable.add(function(h) {
                    if (h.changes.pressed) {
                        var f = h.changes.pressed.current;
                        a(f)
                    }
                }) : (n.selectionComponent = c.getMainComponent(),
                n.onButtonChangedObserver = n.selectionComponent.onButtonStateChangedObservable.add(function(h) {
                    if (h.changes.pressed) {
                        var f = h.changes.pressed.current;
                        a(f)
                    }
                }))
            };
            t.motionController ? s(t.motionController) : t.onMotionControllerInitObservable.add(s)
        } else {
            var l = function(c) {
                n.xrController && c.inputSource === n.xrController.inputSource && n.pick && r._isControllerReadyForNearInteraction(n.id) && n.meshUnderPointer && r._nearGrabPredicate(n.meshUnderPointer) && (n.grabInteraction = !0,
                n.pickedPointVisualCue.isVisible = !1,
                r._scene.simulatePointerDown(n.pick, o))
            }
              , u = function(c) {
                n.xrController && c.inputSource === n.xrController.inputSource && n.pick && r._isControllerReadyForNearInteraction(n.id) && (r._scene.simulatePointerUp(n.pick, o),
                n.grabInteraction = !1,
                n.pickedPointVisualCue.isVisible = !0)
            };
            n.eventListeners = {
                selectend: u,
                selectstart: l
            },
            this._xrSessionManager.session.addEventListener("selectstart", l),
            this._xrSessionManager.session.addEventListener("selectend", u)
        }
    }
    ,
    e.prototype._detachController = function(t) {
        var r = this, n, o = this._controllers[t];
        if (!!o) {
            o.squeezeComponent && o.onSqueezeButtonChangedObserver && o.squeezeComponent.onButtonStateChangedObservable.remove(o.onSqueezeButtonChangedObserver),
            o.selectionComponent && o.onButtonChangedObserver && o.selectionComponent.onButtonStateChangedObservable.remove(o.onButtonChangedObserver),
            o.onFrameObserver && this._xrSessionManager.onXRFrameObservable.remove(o.onFrameObserver),
            o.eventListeners && Object.keys(o.eventListeners).forEach(function(l) {
                var u = o.eventListeners && o.eventListeners[l];
                u && r._xrSessionManager.session.removeEventListener(l, u)
            }),
            (n = o.pickIndexMeshTip) === null || n === void 0 || n.dispose(),
            o.pickedPointVisualCue.dispose();
            var a = {
                pointerId: o.id,
                pointerType: "xr"
            };
            if (this._scene.simulatePointerUp(new PickingInfo, a),
            delete this._controllers[t],
            this._attachedController === t) {
                var s = Object.keys(this._controllers);
                s.length ? this._attachedController = s[0] : this._attachedController = ""
            }
        }
    }
    ,
    e.prototype._generateNewHandTipMesh = function() {
        var t = this._options.useUtilityLayer ? this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene : this._scene
          , r = null
          , n = function(o, a, s) {
            var l = null;
            return l = CreateSphere(o, {
                diameter: 1
            }, s),
            l.scaling.set(a, a, a),
            l.isVisible = !1,
            l
        };
        return r = n("IndexPickSphere", this._pickRadius, t),
        r
    }
    ,
    e.prototype._pickWithSphere = function(t, r, n, o) {
        var a = new PickingInfo;
        if (a.distance = 1 / 0,
        t.pickIndexMeshTip && t.xrController)
            for (var s = t.pickIndexMeshTip.position, l = BoundingSphere.CreateFromCenterAndRadius(s, r), u = 0; u < n.meshes.length; u++) {
                var c = n.meshes[u];
                if (!(!o(c) || !this._controllerAvailablePredicate(c, t.xrController.uniqueId))) {
                    var h = e.PickMeshWithSphere(c, l);
                    h && h.hit && h.distance < a.distance && (a.hit = h.hit,
                    a.pickedMesh = c,
                    a.pickedPoint = h.pickedPoint,
                    a.aimTransform = t.xrController.pointer,
                    a.gripTransform = t.xrController.grip || null,
                    a.originMesh = t.pickIndexMeshTip,
                    a.distance = h.distance)
                }
            }
        return a
    }
    ,
    e.PickMeshWithSphere = function(t, r, n) {
        n === void 0 && (n = !1);
        var o = t.subMeshes
          , a = new PickingInfo
          , s = t.getBoundingInfo();
        if (!t._generatePointsArray() || !t.subMeshes || !s || !n && !BoundingSphere.Intersects(s.boundingSphere, r))
            return a;
        var l = TmpVectors.Vector3[0], u = TmpVectors.Vector3[1], c = 1 / 0, h, f, d, _ = TmpVectors.Vector3[2], g = TmpVectors.Matrix[0];
        g.copyFrom(t.getWorldMatrix()),
        g.invert(),
        Vector3.TransformCoordinatesToRef(r.center, g, _);
        for (var m = 0; m < o.length; m++) {
            var v = o[m];
            v.projectToRef(_, t._positions, t.getIndices(), u),
            Vector3.TransformCoordinatesToRef(u, t.getWorldMatrix(), u),
            h = Vector3.Distance(u, r.center),
            d = Vector3.Distance(u, t.getAbsolutePosition()),
            f = Vector3.Distance(r.center, t.getAbsolutePosition()),
            f !== -1 && d !== -1 && d > f && (h = 0,
            u.copyFrom(r.center)),
            h !== -1 && h < c && (c = h,
            l.copyFrom(u))
        }
        return c < r.radius && (a.hit = !0,
        a.distance = c,
        a.pickedMesh = t,
        a.pickedPoint = l.clone()),
        a
    }
    ,
    e._idCounter = 200,
    e.Name = WebXRFeatureName.NEAR_INTERACTION,
    e.Version = 1,
    e
}(WebXRAbstractFeature);
WebXRFeaturesManager.AddWebXRFeature(WebXRNearInteraction.Name, function(i, e) {
    return function() {
        return new WebXRNearInteraction(i,e)
    }
}, WebXRNearInteraction.Version, !0);
var WebXREnterExitUIButton = function() {
    function i(e, t, r) {
        this.element = e,
        this.sessionMode = t,
        this.referenceSpaceType = r
    }
    return i.prototype.update = function(e) {}
    ,
    i
}(), WebXREnterExitUI = function() {
    function i(e, t) {
        var r = this;
        if (this.scene = e,
        this.options = t,
        this._activeButton = null,
        this._buttons = [],
        this.activeButtonChangedObservable = new Observable,
        this._onSessionGranted = function(h) {
            r._helper && r._enterXRWithButtonIndex(0)
        }
        ,
        this.overlay = document.createElement("div"),
        this.overlay.classList.add("xr-button-overlay"),
        this.overlay.style.cssText = "z-index:11;position: absolute; right: 20px;bottom: 50px;",
        !t.ignoreSessionGrantedEvent && navigator.xr && navigator.xr.addEventListener("sessiongranted", this._onSessionGranted),
        typeof window != "undefined" && window.location && window.location.protocol === "http:" && window.location.hostname !== "localhost")
            throw Tools.Warn("WebXR can only be served over HTTPS"),
            new Error("WebXR can only be served over HTTPS");
        if (t.customButtons)
            this._buttons = t.customButtons;
        else {
            var n = t.sessionMode || "immersive-vr"
              , o = t.referenceSpaceType || "local-floor"
              , a = typeof SVGSVGElement == "undefined" ? "https://cdn.babylonjs.com/Assets/vrButton.png" : "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"
              , s = ".babylonVRicon { color: #868686; border-color: #868686; border-style: solid; margin-left: 10px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url(" + a + "); 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) }";
            s += '.babylonVRicon.vrdisplaypresenting { background-image: none;} .vrdisplaypresenting::after { content: "EXIT"} .xr-error::after { content: "ERROR"}';
            var l = document.createElement("style");
            l.appendChild(document.createTextNode(s)),
            document.getElementsByTagName("head")[0].appendChild(l);
            var u = document.createElement("button");
            u.className = "babylonVRicon",
            u.title = n + " - " + o,
            this._buttons.push(new WebXREnterExitUIButton(u,n,o)),
            this._buttons[this._buttons.length - 1].update = function(h) {
                this.element.style.display = h === null || h === this ? "" : "none",
                u.className = "babylonVRicon" + (h === this ? " vrdisplaypresenting" : "")
            }
            ,
            this._updateButtons(null)
        }
        var c = e.getEngine().getInputElement();
        c && c.parentNode && (c.parentNode.appendChild(this.overlay),
        e.onDisposeObservable.addOnce(function() {
            r.dispose()
        }))
    }
    return i.prototype.setHelperAsync = function(e, t) {
        return __awaiter(this, void 0, void 0, function() {
            var r, n, o = this;
            return __generator(this, function(a) {
                switch (a.label) {
                case 0:
                    return this._helper = e,
                    this._renderTarget = t,
                    r = this._buttons.map(function(s) {
                        return e.sessionManager.isSessionSupportedAsync(s.sessionMode)
                    }),
                    e.onStateChangedObservable.add(function(s) {
                        s == WebXRState.NOT_IN_XR && o._updateButtons(null)
                    }),
                    [4, Promise.all(r)];
                case 1:
                    return n = a.sent(),
                    n.forEach(function(s, l) {
                        s ? (o.overlay.appendChild(o._buttons[l].element),
                        o._buttons[l].element.onclick = o._enterXRWithButtonIndex.bind(o, l)) : Tools.Warn('Session mode "' + o._buttons[l].sessionMode + '" not supported in browser')
                    }),
                    [2]
                }
            })
        })
    }
    ,
    i.CreateAsync = function(e, t, r) {
        return __awaiter(this, void 0, void 0, function() {
            var n;
            return __generator(this, function(o) {
                switch (o.label) {
                case 0:
                    return n = new i(e,r),
                    [4, n.setHelperAsync(t, r.renderTarget || void 0)];
                case 1:
                    return o.sent(),
                    [2, n]
                }
            })
        })
    }
    ,
    i.prototype._enterXRWithButtonIndex = function(e) {
        return e === void 0 && (e = 0),
        __awaiter(this, void 0, void 0, function() {
            var t, r, n;
            return __generator(this, function(o) {
                switch (o.label) {
                case 0:
                    return this._helper.state != WebXRState.IN_XR ? [3, 2] : [4, this._helper.exitXRAsync()];
                case 1:
                    return o.sent(),
                    this._updateButtons(null),
                    [3, 6];
                case 2:
                    if (this._helper.state != WebXRState.NOT_IN_XR)
                        return [3, 6];
                    o.label = 3;
                case 3:
                    return o.trys.push([3, 5, , 6]),
                    [4, this._helper.enterXRAsync(this._buttons[e].sessionMode, this._buttons[e].referenceSpaceType, this._renderTarget, {
                        optionalFeatures: this.options.optionalFeatures,
                        requiredFeatures: this.options.requiredFeatures
                    })];
                case 4:
                    return o.sent(),
                    this._updateButtons(this._buttons[e]),
                    [3, 6];
                case 5:
                    return t = o.sent(),
                    this._updateButtons(null),
                    r = this._buttons[e].element,
                    n = r.title,
                    r.title = "Error entering XR session : " + n,
                    r.classList.add("xr-error"),
                    this.options.onError && this.options.onError(t),
                    [3, 6];
                case 6:
                    return [2]
                }
            })
        })
    }
    ,
    i.prototype.dispose = function() {
        var e = this.scene.getEngine().getInputElement();
        e && e.parentNode && e.parentNode.contains(this.overlay) && e.parentNode.removeChild(this.overlay),
        this.activeButtonChangedObservable.clear(),
        navigator.xr.removeEventListener("sessiongranted", this._onSessionGranted)
    }
    ,
    i.prototype._updateButtons = function(e) {
        var t = this;
        this._activeButton = e,
        this._buttons.forEach(function(r) {
            r.update(t._activeButton)
        }),
        this.activeButtonChangedObservable.notifyObservers(this._activeButton)
    }
    ,
    i
}(), TimerState;
(function(i) {
    i[i.INIT = 0] = "INIT",
    i[i.STARTED = 1] = "STARTED",
    i[i.ENDED = 2] = "ENDED"
}
)(TimerState || (TimerState = {}));
function setAndStartTimer(i) {
    var e, t = 0, r = Date.now();
    i.observableParameters = (e = i.observableParameters) !== null && e !== void 0 ? e : {};
    var n = i.contextObservable.add(function(o) {
        var a = Date.now();
        t = a - r;
        var s = {
            startTime: r,
            currentTime: a,
            deltaTime: t,
            completeRate: t / i.timeout,
            payload: o
        };
        i.onTick && i.onTick(s),
        i.breakCondition && i.breakCondition() && (i.contextObservable.remove(n),
        i.onAborted && i.onAborted(s)),
        t >= i.timeout && (i.contextObservable.remove(n),
        i.onEnded && i.onEnded(s))
    }, i.observableParameters.mask, i.observableParameters.insertFirst, i.observableParameters.scope);
    return n
}
(function() {
    function i(e) {
        var t = this, r, n;
        this.onEachCountObservable = new Observable,
        this.onTimerAbortedObservable = new Observable,
        this.onTimerEndedObservable = new Observable,
        this.onStateChangedObservable = new Observable,
        this._observer = null,
        this._breakOnNextTick = !1,
        this._tick = function(o) {
            var a = Date.now();
            t._timer = a - t._startTime;
            var s = {
                startTime: t._startTime,
                currentTime: a,
                deltaTime: t._timer,
                completeRate: t._timer / t._timeToEnd,
                payload: o
            }
              , l = t._breakOnNextTick || t._breakCondition(s);
            l || t._timer >= t._timeToEnd ? t._stop(s, l) : t.onEachCountObservable.notifyObservers(s)
        }
        ,
        this._setState(TimerState.INIT),
        this._contextObservable = e.contextObservable,
        this._observableParameters = (r = e.observableParameters) !== null && r !== void 0 ? r : {},
        this._breakCondition = (n = e.breakCondition) !== null && n !== void 0 ? n : function() {
            return !1
        }
        ,
        e.onEnded && this.onTimerEndedObservable.add(e.onEnded),
        e.onTick && this.onEachCountObservable.add(e.onTick),
        e.onAborted && this.onTimerAbortedObservable.add(e.onAborted)
    }
    return Object.defineProperty(i.prototype, "breakCondition", {
        set: function(e) {
            this._breakCondition = e
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.clearObservables = function() {
        this.onEachCountObservable.clear(),
        this.onTimerAbortedObservable.clear(),
        this.onTimerEndedObservable.clear(),
        this.onStateChangedObservable.clear()
    }
    ,
    i.prototype.start = function(e) {
        if (e === void 0 && (e = this._timeToEnd),
        this._state === TimerState.STARTED)
            throw new Error("Timer already started. Please stop it before starting again");
        this._timeToEnd = e,
        this._startTime = Date.now(),
        this._timer = 0,
        this._observer = this._contextObservable.add(this._tick, this._observableParameters.mask, this._observableParameters.insertFirst, this._observableParameters.scope),
        this._setState(TimerState.STARTED)
    }
    ,
    i.prototype.stop = function() {
        this._state === TimerState.STARTED && (this._breakOnNextTick = !0)
    }
    ,
    i.prototype.dispose = function() {
        this._observer && this._contextObservable.remove(this._observer),
        this.clearObservables()
    }
    ,
    i.prototype._setState = function(e) {
        this._state = e,
        this.onStateChangedObservable.notifyObservers(this._state)
    }
    ,
    i.prototype._stop = function(e, t) {
        t === void 0 && (t = !1),
        this._contextObservable.remove(this._observer),
        this._setState(TimerState.ENDED),
        t ? this.onTimerAbortedObservable.notifyObservers(e) : this.onTimerEndedObservable.notifyObservers(e)
    }
    ,
    i
}
)();
var WebXRMotionControllerTeleportation = function(i) {
    __extends(e, i);
    function e(t, r) {
        var n = i.call(this, t) || this;
        return n._options = r,
        n._controllers = {},
        n._snappedToPoint = !1,
        n._tmpRay = new Ray(new Vector3,new Vector3),
        n._tmpVector = new Vector3,
        n._tmpQuaternion = new Quaternion,
        n.skipNextTeleportation = !1,
        n.backwardsMovementEnabled = !0,
        n.backwardsTeleportationDistance = .7,
        n.parabolicCheckRadius = 5,
        n.parabolicRayEnabled = !0,
        n.straightRayEnabled = !0,
        n.rotationAngle = Math.PI / 8,
        n.onTargetMeshPositionUpdatedObservable = new Observable,
        n.teleportationEnabled = !0,
        n._rotationEnabled = !0,
        n._attachController = function(o) {
            if (!(n._controllers[o.uniqueId] || n._options.forceHandedness && o.inputSource.handedness !== n._options.forceHandedness)) {
                n._controllers[o.uniqueId] = {
                    xrController: o,
                    teleportationState: {
                        forward: !1,
                        backwards: !1,
                        rotating: !1,
                        currentRotation: 0,
                        baseRotation: 0
                    }
                };
                var a = n._controllers[o.uniqueId];
                if (a.xrController.inputSource.targetRayMode === "tracked-pointer" && a.xrController.inputSource.gamepad) {
                    var s = function() {
                        if (o.motionController) {
                            var l = o.motionController.getComponentOfType(WebXRControllerComponent.THUMBSTICK_TYPE) || o.motionController.getComponentOfType(WebXRControllerComponent.TOUCHPAD_TYPE);
                            if (!l || n._options.useMainComponentOnly) {
                                var u = o.motionController.getMainComponent();
                                if (!u)
                                    return;
                                a.teleportationComponent = u,
                                a.onButtonChangedObserver = u.onButtonStateChangedObservable.add(function() {
                                    if (!!n.teleportationEnabled && u.changes.pressed)
                                        if (u.changes.pressed.current) {
                                            a.teleportationState.forward = !0,
                                            n._currentTeleportationControllerId = a.xrController.uniqueId,
                                            a.teleportationState.baseRotation = n._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,
                                            a.teleportationState.currentRotation = 0;
                                            var c = n._options.timeToTeleport || 3e3;
                                            setAndStartTimer({
                                                timeout: c,
                                                contextObservable: n._xrSessionManager.onXRFrameObservable,
                                                breakCondition: function() {
                                                    return !u.pressed
                                                },
                                                onEnded: function() {
                                                    n._currentTeleportationControllerId === a.xrController.uniqueId && a.teleportationState.forward && n._teleportForward(o.uniqueId)
                                                }
                                            })
                                        } else
                                            a.teleportationState.forward = !1,
                                            n._currentTeleportationControllerId = ""
                                })
                            } else
                                a.teleportationComponent = l,
                                a.onAxisChangedObserver = l.onAxisValueChangedObservable.add(function(c) {
                                    if (c.y <= .7 && a.teleportationState.backwards && (a.teleportationState.backwards = !1),
                                    c.y > .7 && !a.teleportationState.forward && n.backwardsMovementEnabled && !n.snapPointsOnly && !a.teleportationState.backwards) {
                                        a.teleportationState.backwards = !0,
                                        n._tmpQuaternion.copyFrom(n._options.xrInput.xrCamera.rotationQuaternion),
                                        n._tmpQuaternion.toEulerAnglesToRef(n._tmpVector),
                                        n._tmpVector.x = 0,
                                        n._tmpVector.z = 0,
                                        Quaternion.FromEulerVectorToRef(n._tmpVector, n._tmpQuaternion),
                                        n._tmpVector.set(0, 0, n.backwardsTeleportationDistance * (n._xrSessionManager.scene.useRightHandedSystem ? 1 : -1)),
                                        n._tmpVector.rotateByQuaternionToRef(n._tmpQuaternion, n._tmpVector),
                                        n._tmpVector.addInPlace(n._options.xrInput.xrCamera.position),
                                        n._tmpRay.origin.copyFrom(n._tmpVector),
                                        n._tmpRay.length = n._options.xrInput.xrCamera.realWorldHeight + .1,
                                        n._tmpRay.direction.set(0, -1, 0);
                                        var h = n._xrSessionManager.scene.pickWithRay(n._tmpRay, function(d) {
                                            return n._floorMeshes.indexOf(d) !== -1
                                        });
                                        h && h.pickedPoint && (n._options.xrInput.xrCamera.position.x = h.pickedPoint.x,
                                        n._options.xrInput.xrCamera.position.z = h.pickedPoint.z)
                                    }
                                    if (c.y < -.7 && !n._currentTeleportationControllerId && !a.teleportationState.rotating && n.teleportationEnabled && (a.teleportationState.forward = !0,
                                    n._currentTeleportationControllerId = a.xrController.uniqueId,
                                    a.teleportationState.baseRotation = n._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y),
                                    c.x) {
                                        if (a.teleportationState.forward)
                                            n._currentTeleportationControllerId === a.xrController.uniqueId && (n.rotationEnabled ? setTimeout(function() {
                                                a.teleportationState.currentRotation = Math.atan2(c.x, c.y * (n._xrSessionManager.scene.useRightHandedSystem ? 1 : -1))
                                            }) : a.teleportationState.currentRotation = 0);
                                        else if (!a.teleportationState.rotating && Math.abs(c.x) > .7) {
                                            a.teleportationState.rotating = !0;
                                            var f = n.rotationAngle * (c.x > 0 ? 1 : -1) * (n._xrSessionManager.scene.useRightHandedSystem ? -1 : 1);
                                            Quaternion.FromEulerAngles(0, f, 0).multiplyToRef(n._options.xrInput.xrCamera.rotationQuaternion, n._options.xrInput.xrCamera.rotationQuaternion)
                                        }
                                    } else
                                        a.teleportationState.rotating = !1;
                                    c.x === 0 && c.y === 0 && a.teleportationState.forward && n._teleportForward(o.uniqueId)
                                })
                        }
                    };
                    o.motionController ? s() : o.onMotionControllerInitObservable.addOnce(function() {
                        s()
                    })
                } else
                    n._xrSessionManager.scene.onPointerObservable.add(function(l) {
                        if (l.type === PointerEventTypes.POINTERDOWN) {
                            a.teleportationState.forward = !0,
                            n._currentTeleportationControllerId = a.xrController.uniqueId,
                            a.teleportationState.baseRotation = n._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,
                            a.teleportationState.currentRotation = 0;
                            var u = n._options.timeToTeleport || 3e3;
                            setAndStartTimer({
                                timeout: u,
                                contextObservable: n._xrSessionManager.onXRFrameObservable,
                                onEnded: function() {
                                    n._currentTeleportationControllerId === a.xrController.uniqueId && a.teleportationState.forward && n._teleportForward(o.uniqueId)
                                }
                            })
                        } else
                            l.type === PointerEventTypes.POINTERUP && (a.teleportationState.forward = !1,
                            n._currentTeleportationControllerId = "")
                    })
            }
        }
        ,
        n._options.teleportationTargetMesh || n._createDefaultTargetMesh(),
        n._floorMeshes = n._options.floorMeshes || [],
        n._snapToPositions = n._options.snapPositions || [],
        n._setTargetMeshVisibility(!1),
        n
    }
    return Object.defineProperty(e.prototype, "rotationEnabled", {
        get: function() {
            return this._rotationEnabled
        },
        set: function(t) {
            if (this._rotationEnabled = t,
            this._options.teleportationTargetMesh) {
                var r = this._options.teleportationTargetMesh.getChildMeshes(!1, function(n) {
                    return n.name === "rotationCone"
                });
                r[0] && r[0].setEnabled(t)
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "teleportationTargetMesh", {
        get: function() {
            return this._options.teleportationTargetMesh || null
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "snapPointsOnly", {
        get: function() {
            return !!this._options.snapPointsOnly
        },
        set: function(t) {
            this._options.snapPointsOnly = t
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.addFloorMesh = function(t) {
        this._floorMeshes.push(t)
    }
    ,
    e.prototype.addBlockerMesh = function(t) {
        this._options.pickBlockerMeshes = this._options.pickBlockerMeshes || [],
        this._options.pickBlockerMeshes.push(t)
    }
    ,
    e.prototype.addSnapPoint = function(t) {
        this._snapToPositions.push(t)
    }
    ,
    e.prototype.attach = function() {
        var t = this;
        return i.prototype.attach.call(this) ? (this._currentTeleportationControllerId = "",
        this._options.xrInput.controllers.forEach(this._attachController),
        this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable, this._attachController),
        this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable, function(r) {
            t._detachController(r.uniqueId)
        }),
        !0) : !1
    }
    ,
    e.prototype.detach = function() {
        var t = this;
        return i.prototype.detach.call(this) ? (Object.keys(this._controllers).forEach(function(r) {
            t._detachController(r)
        }),
        this._setTargetMeshVisibility(!1),
        this._currentTeleportationControllerId = "",
        this._controllers = {},
        !0) : !1
    }
    ,
    e.prototype.dispose = function() {
        i.prototype.dispose.call(this),
        this._options.teleportationTargetMesh && this._options.teleportationTargetMesh.dispose(!1, !0)
    }
    ,
    e.prototype.removeFloorMesh = function(t) {
        var r = this._floorMeshes.indexOf(t);
        r !== -1 && this._floorMeshes.splice(r, 1)
    }
    ,
    e.prototype.removeBlockerMesh = function(t) {
        this._options.pickBlockerMeshes = this._options.pickBlockerMeshes || [];
        var r = this._options.pickBlockerMeshes.indexOf(t);
        r !== -1 && this._options.pickBlockerMeshes.splice(r, 1)
    }
    ,
    e.prototype.removeFloorMeshByName = function(t) {
        var r = this._xrSessionManager.scene.getMeshByName(t);
        r && this.removeFloorMesh(r)
    }
    ,
    e.prototype.removeSnapPoint = function(t) {
        var r = this._snapToPositions.indexOf(t);
        if (r === -1) {
            for (var n = 0; n < this._snapToPositions.length; ++n)
                if (this._snapToPositions[n].equals(t)) {
                    r = n;
                    break
                }
        }
        return r !== -1 ? (this._snapToPositions.splice(r, 1),
        !0) : !1
    }
    ,
    e.prototype.setSelectionFeature = function(t) {
        this._selectionFeature = t
    }
    ,
    e.prototype._onXRFrame = function(t) {
        var r = this
          , n = this._xrSessionManager.currentFrame
          , o = this._xrSessionManager.scene;
        if (!(!this.attach || !n)) {
            var a = this._options.teleportationTargetMesh;
            if (this._currentTeleportationControllerId) {
                if (!a)
                    return;
                a.rotationQuaternion = a.rotationQuaternion || new Quaternion;
                var s = this._controllers[this._currentTeleportationControllerId];
                if (s && s.teleportationState.forward) {
                    Quaternion.RotationYawPitchRollToRef(s.teleportationState.currentRotation + s.teleportationState.baseRotation, 0, 0, a.rotationQuaternion);
                    var l = !1;
                    if (s.xrController.getWorldPointerRayToRef(this._tmpRay),
                    this.straightRayEnabled) {
                        var u = o.pickWithRay(this._tmpRay, function(d) {
                            if (r._options.pickBlockerMeshes && r._options.pickBlockerMeshes.indexOf(d) !== -1)
                                return !0;
                            var _ = r._floorMeshes.indexOf(d);
                            return _ === -1 ? !1 : r._floorMeshes[_].absolutePosition.y < r._options.xrInput.xrCamera.globalPosition.y
                        });
                        if (u && u.pickedMesh && this._options.pickBlockerMeshes && this._options.pickBlockerMeshes.indexOf(u.pickedMesh) !== -1)
                            return;
                        u && u.pickedPoint && (l = !0,
                        this._setTargetMeshPosition(u),
                        this._setTargetMeshVisibility(!0),
                        this._showParabolicPath(u))
                    }
                    if (this.parabolicRayEnabled && !l) {
                        var c = s.xrController.pointer.rotationQuaternion.toEulerAngles().x
                          , h = 1 + (Math.PI / 2 - Math.abs(c))
                          , f = this.parabolicCheckRadius * h;
                        this._tmpRay.origin.addToRef(this._tmpRay.direction.scale(f * 2), this._tmpVector),
                        this._tmpVector.y = this._tmpRay.origin.y,
                        this._tmpRay.origin.addInPlace(this._tmpRay.direction.scale(f)),
                        this._tmpVector.subtractToRef(this._tmpRay.origin, this._tmpRay.direction),
                        this._tmpRay.direction.normalize();
                        var u = o.pickWithRay(this._tmpRay, function(_) {
                            return r._options.pickBlockerMeshes && r._options.pickBlockerMeshes.indexOf(_) !== -1 ? !0 : r._floorMeshes.indexOf(_) !== -1
                        });
                        if (u && u.pickedMesh && this._options.pickBlockerMeshes && this._options.pickBlockerMeshes.indexOf(u.pickedMesh) !== -1)
                            return;
                        u && u.pickedPoint && (l = !0,
                        this._setTargetMeshPosition(u),
                        this._setTargetMeshVisibility(!0),
                        this._showParabolicPath(u))
                    }
                    this._setTargetMeshVisibility(l)
                } else
                    this._setTargetMeshVisibility(!1)
            } else
                this._setTargetMeshVisibility(!1)
        }
    }
    ,
    e.prototype._createDefaultTargetMesh = function() {
        this._options.defaultTargetMeshOptions = this._options.defaultTargetMeshOptions || {};
        var t = this._options.useUtilityLayer ? this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene : this._xrSessionManager.scene
          , r = CreateGround("teleportationTarget", {
            width: 2,
            height: 2,
            subdivisions: 2
        }, t);
        r.isPickable = !1;
        var n = 512
          , o = new DynamicTexture("teleportationPlaneDynamicTexture",n,t,!0);
        o.hasAlpha = !0;
        var a = o.getContext()
          , s = n / 2
          , l = n / 2
          , u = 200;
        a.beginPath(),
        a.arc(s, l, u, 0, 2 * Math.PI, !1),
        a.fillStyle = this._options.defaultTargetMeshOptions.teleportationFillColor || "#444444",
        a.fill(),
        a.lineWidth = 10,
        a.strokeStyle = this._options.defaultTargetMeshOptions.teleportationBorderColor || "#FFFFFF",
        a.stroke(),
        a.closePath(),
        o.update();
        var c = new StandardMaterial("teleportationPlaneMaterial",t);
        c.diffuseTexture = o,
        r.material = c;
        var h = CreateTorus("torusTeleportation", {
            diameter: .75,
            thickness: .1,
            tessellation: 20
        }, t);
        if (h.isPickable = !1,
        h.parent = r,
        !this._options.defaultTargetMeshOptions.disableAnimation) {
            var f = new Animation("animationInnerCircle","position.y",30,Animation.ANIMATIONTYPE_FLOAT,Animation.ANIMATIONLOOPMODE_CYCLE)
              , d = [];
            d.push({
                frame: 0,
                value: 0
            }),
            d.push({
                frame: 30,
                value: .4
            }),
            d.push({
                frame: 60,
                value: 0
            }),
            f.setKeys(d);
            var _ = new SineEase;
            _.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT),
            f.setEasingFunction(_),
            h.animations = [],
            h.animations.push(f),
            t.beginAnimation(h, 0, 60, !0)
        }
        var g = CreateCylinder("rotationCone", {
            diameterTop: 0,
            tessellation: 4
        }, t);
        if (g.isPickable = !1,
        g.scaling.set(.5, .12, .2),
        g.rotate(Axis.X, Math.PI / 2),
        g.position.z = .6,
        g.parent = h,
        this._options.defaultTargetMeshOptions.torusArrowMaterial)
            h.material = this._options.defaultTargetMeshOptions.torusArrowMaterial,
            g.material = this._options.defaultTargetMeshOptions.torusArrowMaterial;
        else {
            var m = new StandardMaterial("torusConsMat",t);
            m.disableLighting = !!this._options.defaultTargetMeshOptions.disableLighting,
            m.disableLighting ? m.emissiveColor = new Color3(.3,.3,1) : m.diffuseColor = new Color3(.3,.3,1),
            m.alpha = .9,
            h.material = m,
            g.material = m,
            this._teleportationRingMaterial = m
        }
        this._options.renderingGroupId !== void 0 && (r.renderingGroupId = this._options.renderingGroupId,
        h.renderingGroupId = this._options.renderingGroupId,
        g.renderingGroupId = this._options.renderingGroupId),
        this._options.teleportationTargetMesh = r
    }
    ,
    e.prototype._detachController = function(t) {
        var r = this._controllers[t];
        !r || (r.teleportationComponent && (r.onAxisChangedObserver && r.teleportationComponent.onAxisValueChangedObservable.remove(r.onAxisChangedObserver),
        r.onButtonChangedObserver && r.teleportationComponent.onButtonStateChangedObservable.remove(r.onButtonChangedObserver)),
        delete this._controllers[t])
    }
    ,
    e.prototype._findClosestSnapPointWithRadius = function(t, r) {
        r === void 0 && (r = this._options.snapToPositionRadius || .8);
        var n = null
          , o = Number.MAX_VALUE;
        if (this._snapToPositions.length) {
            var a = r * r;
            this._snapToPositions.forEach(function(s) {
                var l = Vector3.DistanceSquared(s, t);
                l <= a && l < o && (o = l,
                n = s)
            })
        }
        return n
    }
    ,
    e.prototype._setTargetMeshPosition = function(t) {
        var r = t.pickedPoint;
        if (!(!this._options.teleportationTargetMesh || !r)) {
            var n = this._findClosestSnapPointWithRadius(r);
            this._snappedToPoint = !!n,
            this.snapPointsOnly && !this._snappedToPoint && this._teleportationRingMaterial ? this._teleportationRingMaterial.diffuseColor.set(1, .3, .3) : this.snapPointsOnly && this._snappedToPoint && this._teleportationRingMaterial && this._teleportationRingMaterial.diffuseColor.set(.3, .3, 1),
            this._options.teleportationTargetMesh.position.copyFrom(n || r),
            this._options.teleportationTargetMesh.position.y += .01,
            this.onTargetMeshPositionUpdatedObservable.notifyObservers(t)
        }
    }
    ,
    e.prototype._setTargetMeshVisibility = function(t) {
        !this._options.teleportationTargetMesh || this._options.teleportationTargetMesh.isVisible !== t && (this._options.teleportationTargetMesh.isVisible = t,
        this._options.teleportationTargetMesh.getChildren(void 0, !1).forEach(function(r) {
            r.isVisible = t
        }),
        t ? this._selectionFeature && this._selectionFeature.detach() : (this._quadraticBezierCurve && (this._quadraticBezierCurve.dispose(),
        this._quadraticBezierCurve = null),
        this._selectionFeature && this._selectionFeature.attach()))
    }
    ,
    e.prototype._showParabolicPath = function(t) {
        if (!!t.pickedPoint) {
            var r = this._options.useUtilityLayer ? this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene : this._xrSessionManager.scene
              , n = this._controllers[this._currentTeleportationControllerId]
              , o = Curve3.CreateQuadraticBezier(n.xrController.pointer.absolutePosition, t.ray.origin, t.pickedPoint, 25);
            this._options.generateRayPathMesh ? this._quadraticBezierCurve = this._options.generateRayPathMesh(o.getPoints(), t) : this._quadraticBezierCurve = CreateLines("teleportation path line", {
                points: o.getPoints(),
                instance: this._quadraticBezierCurve,
                updatable: !0
            }, r),
            this._quadraticBezierCurve.isPickable = !1,
            this._options.renderingGroupId !== void 0 && (this._quadraticBezierCurve.renderingGroupId = this._options.renderingGroupId)
        }
    }
    ,
    e.prototype._teleportForward = function(t) {
        var r = this._controllers[t];
        if (!(!r || !r.teleportationState.forward || !this.teleportationEnabled) && (r.teleportationState.forward = !1,
        this._currentTeleportationControllerId = "",
        !(this.snapPointsOnly && !this._snappedToPoint))) {
            if (this.skipNextTeleportation) {
                this.skipNextTeleportation = !1;
                return
            }
            if (this._options.teleportationTargetMesh && this._options.teleportationTargetMesh.isVisible) {
                var n = this._options.xrInput.xrCamera.realWorldHeight;
                this._options.xrInput.xrCamera.onBeforeCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position),
                this._options.xrInput.xrCamera.position.copyFrom(this._options.teleportationTargetMesh.position),
                this._options.xrInput.xrCamera.position.y += n,
                Quaternion.FromEulerAngles(0, r.teleportationState.currentRotation - (this._xrSessionManager.scene.useRightHandedSystem ? Math.PI : 0), 0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion, this._options.xrInput.xrCamera.rotationQuaternion),
                this._options.xrInput.xrCamera.onAfterCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position)
            }
        }
    }
    ,
    e.Name = WebXRFeatureName.TELEPORTATION,
    e.Version = 1,
    e
}(WebXRAbstractFeature);
WebXRFeaturesManager.AddWebXRFeature(WebXRMotionControllerTeleportation.Name, function(i, e) {
    return function() {
        return new WebXRMotionControllerTeleportation(i,e)
    }
}, WebXRMotionControllerTeleportation.Version, !0);
var WebXRDefaultExperience = function() {
    function i() {}
    return i.CreateAsync = function(e, t) {
        t === void 0 && (t = {});
        var r = new i;
        if (!t.disableDefaultUI) {
            var n = __assign({
                renderTarget: r.renderTarget
            }, t.uiOptions || {});
            t.optionalFeatures && (typeof t.optionalFeatures == "boolean" ? n.optionalFeatures = ["hit-test", "anchors", "plane-detection", "hand-tracking"] : n.optionalFeatures = t.optionalFeatures),
            r.enterExitUI = new WebXREnterExitUI(e,n)
        }
        return WebXRExperienceHelper.CreateAsync(e).then(function(o) {
            if (r.baseExperience = o,
            t.ignoreNativeCameraTransformation && (r.baseExperience.camera.compensateOnFirstFrame = !1),
            r.input = new WebXRInput(o.sessionManager,o.camera,__assign({
                controllerOptions: {
                    renderingGroupId: t.renderingGroupId
                }
            }, t.inputOptions || {})),
            !t.disablePointerSelection) {
                var a = __assign(__assign({}, t.pointerSelectionOptions), {
                    xrInput: r.input,
                    renderingGroupId: t.renderingGroupId
                });
                r.pointerSelection = r.baseExperience.featuresManager.enableFeature(WebXRControllerPointerSelection.Name, t.useStablePlugins ? "stable" : "latest", a),
                t.disableTeleportation || (r.teleportation = r.baseExperience.featuresManager.enableFeature(WebXRMotionControllerTeleportation.Name, t.useStablePlugins ? "stable" : "latest", {
                    floorMeshes: t.floorMeshes,
                    xrInput: r.input,
                    renderingGroupId: t.renderingGroupId
                }),
                r.teleportation.setSelectionFeature(r.pointerSelection))
            }
            if (t.disableNearInteraction || (r.nearInteraction = r.baseExperience.featuresManager.enableFeature(WebXRNearInteraction.Name, t.useStablePlugins ? "stable" : "latest", {
                xrInput: r.input,
                farInteractionFeature: r.pointerSelection,
                renderingGroupId: t.renderingGroupId,
                useUtilityLayer: !0,
                enableNearInteractionOnAllControllers: !0
            })),
            r.renderTarget = r.baseExperience.sessionManager.getWebXRRenderTarget(t.outputCanvasOptions),
            !t.disableDefaultUI)
                return r.enterExitUI.setHelperAsync(r.baseExperience, r.renderTarget)
        }).then(function() {
            return r
        }).catch(function(o) {
            return Logger$2.Error("Error initializing XR"),
            Logger$2.Error(o),
            r
        })
    }
    ,
    i.prototype.dispose = function() {
        this.baseExperience && this.baseExperience.dispose(),
        this.input && this.input.dispose(),
        this.enterExitUI && this.enterExitUI.dispose(),
        this.renderTarget && this.renderTarget.dispose()
    }
    ,
    i
}();
Scene.prototype.createDefaultLight = function(i) {
    if (i === void 0 && (i = !1),
    i && this.lights)
        for (var e = 0; e < this.lights.length; e++)
            this.lights[e].dispose();
    this.lights.length === 0 && new HemisphericLight("default light",Vector3.Up(),this)
}
;
Scene.prototype.createDefaultCamera = function(i, e, t) {
    if (i === void 0 && (i = !1),
    e === void 0 && (e = !1),
    t === void 0 && (t = !1),
    e && this.activeCamera && (this.activeCamera.dispose(),
    this.activeCamera = null),
    !this.activeCamera) {
        var r = this.getWorldExtends(function(c) {
            return c.isVisible && c.isEnabled()
        }), n = r.max.subtract(r.min), o = r.min.add(n.scale(.5)), a, s = n.length() * 1.5;
        if (isFinite(s) || (s = 1,
        o.copyFromFloats(0, 0, 0)),
        i) {
            var l = new ArcRotateCamera("default camera",-(Math.PI / 2),Math.PI / 2,s,o,this);
            l.lowerRadiusLimit = s * .01,
            l.wheelPrecision = 100 / s,
            a = l
        } else {
            var u = new FreeCamera("default camera",new Vector3(o.x,o.y,-s),this);
            u.setTarget(o),
            a = u
        }
        a.minZ = s * .01,
        a.maxZ = s * 1e3,
        a.speed = s * .2,
        this.activeCamera = a,
        t && a.attachControl()
    }
}
;
Scene.prototype.createDefaultCameraOrLight = function(i, e, t) {
    i === void 0 && (i = !1),
    e === void 0 && (e = !1),
    t === void 0 && (t = !1),
    this.createDefaultLight(e),
    this.createDefaultCamera(i, e, t)
}
;
Scene.prototype.createDefaultSkybox = function(i, e, t, r, n) {
    if (e === void 0 && (e = !1),
    t === void 0 && (t = 1e3),
    r === void 0 && (r = 0),
    n === void 0 && (n = !0),
    !i)
        return Logger$2.Warn("Can not create default skybox without environment texture."),
        null;
    n && i && (this.environmentTexture = i);
    var o = CreateBox("hdrSkyBox", {
        size: t
    }, this);
    if (e) {
        var a = new PBRMaterial("skyBox",this);
        a.backFaceCulling = !1,
        a.reflectionTexture = i.clone(),
        a.reflectionTexture && (a.reflectionTexture.coordinatesMode = Texture.SKYBOX_MODE),
        a.microSurface = 1 - r,
        a.disableLighting = !0,
        a.twoSidedLighting = !0,
        o.material = a
    } else {
        var s = new StandardMaterial("skyBox",this);
        s.backFaceCulling = !1,
        s.reflectionTexture = i.clone(),
        s.reflectionTexture && (s.reflectionTexture.coordinatesMode = Texture.SKYBOX_MODE),
        s.disableLighting = !0,
        o.material = s
    }
    return o.isPickable = !1,
    o.infiniteDistance = !0,
    o.ignoreCameraMaxZ = !0,
    o
}
;
Scene.prototype.createDefaultEnvironment = function(i) {
    return EnvironmentHelper ? new EnvironmentHelper(i,this) : null
}
;
Scene.prototype.createDefaultVRExperience = function(i) {
    return i === void 0 && (i = {}),
    new VRExperienceHelper(this,i)
}
;
Scene.prototype.createDefaultXRExperienceAsync = function(i) {
    return i === void 0 && (i = {}),
    WebXRDefaultExperience.CreateAsync(this, i).then(function(e) {
        return e
    })
}
;
var NullEngineOptions = function() {
    function i() {
        this.renderWidth = 512,
        this.renderHeight = 256,
        this.textureSize = 512,
        this.deterministicLockstep = !1,
        this.lockstepMaxSteps = 4
    }
    return i
}();
(function(i) {
    __extends(e, i);
    function e(t) {
        t === void 0 && (t = new NullEngineOptions);
        var r = i.call(this, null) || this;
        Engine.Instances.push(r),
        t.deterministicLockstep === void 0 && (t.deterministicLockstep = !1),
        t.lockstepMaxSteps === void 0 && (t.lockstepMaxSteps = 4),
        r._options = t,
        PerformanceConfigurator.SetMatrixPrecision(!!t.useHighPrecisionMatrix),
        r._caps = {
            maxTexturesImageUnits: 16,
            maxVertexTextureImageUnits: 16,
            maxCombinedTexturesImageUnits: 32,
            maxTextureSize: 512,
            maxCubemapTextureSize: 512,
            maxRenderTextureSize: 512,
            maxVertexAttribs: 16,
            maxVaryingVectors: 16,
            maxFragmentUniformVectors: 16,
            maxVertexUniformVectors: 16,
            standardDerivatives: !1,
            astc: null,
            pvrtc: null,
            etc1: null,
            etc2: null,
            bptc: null,
            maxAnisotropy: 0,
            uintIndices: !1,
            fragmentDepthSupported: !1,
            highPrecisionShaderSupported: !0,
            colorBufferFloat: !1,
            textureFloat: !1,
            textureFloatLinearFiltering: !1,
            textureFloatRender: !1,
            textureHalfFloat: !1,
            textureHalfFloatLinearFiltering: !1,
            textureHalfFloatRender: !1,
            textureLOD: !1,
            drawBuffersExtension: !1,
            depthTextureExtension: !1,
            vertexArrayObject: !1,
            instancedArrays: !1,
            supportOcclusionQuery: !1,
            canUseTimestampForTimerQuery: !1,
            maxMSAASamples: 1,
            blendMinMax: !1,
            canUseGLInstanceID: !1,
            canUseGLVertexID: !1,
            supportComputeShaders: !1,
            supportSRGBBuffers: !1
        },
        r._features = {
            forceBitmapOverHTMLImageElement: !1,
            supportRenderAndCopyToLodForFloatTextures: !1,
            supportDepthStencilTexture: !1,
            supportShadowSamplers: !1,
            uniformBufferHardCheckMatrix: !1,
            allowTexturePrefiltering: !1,
            trackUbosInFrame: !1,
            checkUbosContentBeforeUpload: !1,
            supportCSM: !1,
            basisNeedsPOT: !1,
            support3DTextures: !1,
            needTypeSuffixInShaderConstants: !1,
            supportMSAA: !1,
            supportSSAO2: !1,
            supportExtendedTextureFormats: !1,
            supportSwitchCaseInShader: !1,
            supportSyncTextureRead: !1,
            needsInvertingBitmap: !1,
            useUBOBindingCache: !1,
            needShaderCodeInlining: !1,
            needToAlwaysBindUniformBuffers: !1,
            supportRenderPasses: !0,
            _collectUbosUpdatedInFrame: !1
        },
        Logger$2.Log("Babylon.js v" + Engine.Version + " - Null engine");
        var n = typeof self != "undefined" ? self : typeof global != "undefined" ? global : window;
        return typeof URL == "undefined" && (n.URL = {
            createObjectURL: function() {},
            revokeObjectURL: function() {}
        }),
        typeof Blob == "undefined" && (n.Blob = function() {}
        ),
        r
    }
    return e.prototype.isDeterministicLockStep = function() {
        return this._options.deterministicLockstep
    }
    ,
    e.prototype.getLockstepMaxSteps = function() {
        return this._options.lockstepMaxSteps
    }
    ,
    e.prototype.getHardwareScalingLevel = function() {
        return 1
    }
    ,
    e.prototype.createVertexBuffer = function(t) {
        var r = new DataBuffer;
        return r.references = 1,
        r
    }
    ,
    e.prototype.createIndexBuffer = function(t) {
        var r = new DataBuffer;
        return r.references = 1,
        r
    }
    ,
    e.prototype.clear = function(t, r, n, o) {}
    ,
    e.prototype.getRenderWidth = function(t) {
        return t === void 0 && (t = !1),
        !t && this._currentRenderTarget ? this._currentRenderTarget.width : this._options.renderWidth
    }
    ,
    e.prototype.getRenderHeight = function(t) {
        return t === void 0 && (t = !1),
        !t && this._currentRenderTarget ? this._currentRenderTarget.height : this._options.renderHeight
    }
    ,
    e.prototype.setViewport = function(t, r, n) {
        this._cachedViewport = t
    }
    ,
    e.prototype.createShaderProgram = function(t, r, n, o, a) {
        return {
            __SPECTOR_rebuildProgram: null
        }
    }
    ,
    e.prototype.getUniforms = function(t, r) {
        return []
    }
    ,
    e.prototype.getAttributes = function(t, r) {
        return []
    }
    ,
    e.prototype.bindSamplers = function(t) {
        this._currentEffect = null
    }
    ,
    e.prototype.enableEffect = function(t) {
        t = t !== null && DrawWrapper.IsWrapper(t) ? t.effect : t,
        this._currentEffect = t,
        t && (t.onBind && t.onBind(t),
        t._onBindObservable && t._onBindObservable.notifyObservers(t))
    }
    ,
    e.prototype.setState = function(t, r, n, o, a, s, l) {}
    ,
    e.prototype.setIntArray = function(t, r) {
        return !0
    }
    ,
    e.prototype.setIntArray2 = function(t, r) {
        return !0
    }
    ,
    e.prototype.setIntArray3 = function(t, r) {
        return !0
    }
    ,
    e.prototype.setIntArray4 = function(t, r) {
        return !0
    }
    ,
    e.prototype.setFloatArray = function(t, r) {
        return !0
    }
    ,
    e.prototype.setFloatArray2 = function(t, r) {
        return !0
    }
    ,
    e.prototype.setFloatArray3 = function(t, r) {
        return !0
    }
    ,
    e.prototype.setFloatArray4 = function(t, r) {
        return !0
    }
    ,
    e.prototype.setArray = function(t, r) {
        return !0
    }
    ,
    e.prototype.setArray2 = function(t, r) {
        return !0
    }
    ,
    e.prototype.setArray3 = function(t, r) {
        return !0
    }
    ,
    e.prototype.setArray4 = function(t, r) {
        return !0
    }
    ,
    e.prototype.setMatrices = function(t, r) {
        return !0
    }
    ,
    e.prototype.setMatrix3x3 = function(t, r) {
        return !0
    }
    ,
    e.prototype.setMatrix2x2 = function(t, r) {
        return !0
    }
    ,
    e.prototype.setFloat = function(t, r) {
        return !0
    }
    ,
    e.prototype.setFloat2 = function(t, r, n) {
        return !0
    }
    ,
    e.prototype.setFloat3 = function(t, r, n, o) {
        return !0
    }
    ,
    e.prototype.setBool = function(t, r) {
        return !0
    }
    ,
    e.prototype.setFloat4 = function(t, r, n, o, a) {
        return !0
    }
    ,
    e.prototype.setAlphaMode = function(t, r) {
        r === void 0 && (r = !1),
        this._alphaMode !== t && (this.alphaState.alphaBlend = t !== 0,
        r || this.setDepthWrite(t === 0),
        this._alphaMode = t)
    }
    ,
    e.prototype.bindBuffers = function(t, r, n) {}
    ,
    e.prototype.wipeCaches = function(t) {
        this.preventCacheWipeBetweenFrames || (this.resetTextureCache(),
        this._currentEffect = null,
        t && (this._currentProgram = null,
        this._stencilStateComposer.reset(),
        this.depthCullingState.reset(),
        this.alphaState.reset()),
        this._cachedVertexBuffers = null,
        this._cachedIndexBuffer = null,
        this._cachedEffectForVertexBuffers = null)
    }
    ,
    e.prototype.draw = function(t, r, n, o) {}
    ,
    e.prototype.drawElementsType = function(t, r, n, o) {}
    ,
    e.prototype.drawArraysType = function(t, r, n, o) {}
    ,
    e.prototype._createTexture = function() {
        return {}
    }
    ,
    e.prototype._releaseTexture = function(t) {}
    ,
    e.prototype.createTexture = function(t, r, n, o, a, s, l, u, c, h, f, d) {
        a === void 0 && (a = 3),
        s === void 0 && (s = null),
        h === void 0 && (h = null);
        var _ = new InternalTexture(this,InternalTextureSource.Url)
          , g = String(t);
        return _.url = g,
        _.generateMipMaps = !r,
        _.samplingMode = a,
        _.invertY = n,
        _.baseWidth = this._options.textureSize,
        _.baseHeight = this._options.textureSize,
        _.width = this._options.textureSize,
        _.height = this._options.textureSize,
        h && (_.format = h),
        _.isReady = !0,
        s && s(),
        this._internalTexturesCache.push(_),
        _
    }
    ,
    e.prototype._createHardwareRenderTargetWrapper = function(t, r, n) {
        var o = new RenderTargetWrapper(t,r,n,this);
        return this._renderTargetWrapperCache.push(o),
        o
    }
    ,
    e.prototype.createRenderTargetTexture = function(t, r) {
        var n = this._createHardwareRenderTargetWrapper(!1, !1, t)
          , o = {};
        r !== void 0 && typeof r == "object" ? (o.generateMipMaps = r.generateMipMaps,
        o.generateDepthBuffer = r.generateDepthBuffer === void 0 ? !0 : r.generateDepthBuffer,
        o.generateStencilBuffer = o.generateDepthBuffer && r.generateStencilBuffer,
        o.type = r.type === void 0 ? 0 : r.type,
        o.samplingMode = r.samplingMode === void 0 ? 3 : r.samplingMode) : (o.generateMipMaps = r,
        o.generateDepthBuffer = !0,
        o.generateStencilBuffer = !1,
        o.type = 0,
        o.samplingMode = 3);
        var a = new InternalTexture(this,InternalTextureSource.RenderTarget)
          , s = t.width || t
          , l = t.height || t;
        return n._generateDepthBuffer = o.generateDepthBuffer,
        n._generateStencilBuffer = !!o.generateStencilBuffer,
        a.baseWidth = s,
        a.baseHeight = l,
        a.width = s,
        a.height = l,
        a.isReady = !0,
        a.samples = 1,
        a.generateMipMaps = !!o.generateMipMaps,
        a.samplingMode = o.samplingMode,
        a.type = o.type,
        this._internalTexturesCache.push(a),
        n
    }
    ,
    e.prototype.updateTextureSamplingMode = function(t, r) {
        r.samplingMode = t
    }
    ,
    e.prototype.createRawTexture = function(t, r, n, o, a, s, l, u, c, h) {
        u === void 0 && (u = null),
        c === void 0 && (c = 0);
        var f = new InternalTexture(this,InternalTextureSource.Raw);
        return f.baseWidth = r,
        f.baseHeight = n,
        f.width = r,
        f.height = n,
        f.format = o,
        f.generateMipMaps = a,
        f.samplingMode = l,
        f.invertY = s,
        f._compression = u,
        f.type = c,
        this._doNotHandleContextLost || (f._bufferView = t),
        f
    }
    ,
    e.prototype.updateRawTexture = function(t, r, n, o, a, s) {
        a === void 0 && (a = null),
        s === void 0 && (s = 0),
        t && (t._bufferView = r,
        t.format = n,
        t.invertY = o,
        t._compression = a,
        t.type = s)
    }
    ,
    e.prototype.bindFramebuffer = function(t, r, n, o, a) {
        this._currentRenderTarget && this.unBindFramebuffer(this._currentRenderTarget),
        this._currentRenderTarget = t,
        this._currentFramebuffer = null,
        this._cachedViewport && !a && this.setViewport(this._cachedViewport, n, o)
    }
    ,
    e.prototype.unBindFramebuffer = function(t, r, n) {
        this._currentRenderTarget = null,
        n && n(),
        this._currentFramebuffer = null
    }
    ,
    e.prototype.createDynamicVertexBuffer = function(t) {
        var r = new DataBuffer;
        return r.references = 1,
        r.capacity = 1,
        r
    }
    ,
    e.prototype.updateDynamicTexture = function(t, r, n, o, a) {}
    ,
    e.prototype.areAllEffectsReady = function() {
        return !0
    }
    ,
    e.prototype.getError = function() {
        return 0
    }
    ,
    e.prototype._getUnpackAlignement = function() {
        return 1
    }
    ,
    e.prototype._unpackFlipY = function(t) {}
    ,
    e.prototype.updateDynamicIndexBuffer = function(t, r, n) {}
    ,
    e.prototype.updateDynamicVertexBuffer = function(t, r, n, o) {}
    ,
    e.prototype._bindTextureDirectly = function(t, r) {
        return this._boundTexturesCache[this._activeChannel] !== r ? (this._boundTexturesCache[this._activeChannel] = r,
        !0) : !1
    }
    ,
    e.prototype._bindTexture = function(t, r) {
        t < 0 || this._bindTextureDirectly(0, r)
    }
    ,
    e.prototype._deleteBuffer = function(t) {}
    ,
    e.prototype.releaseEffects = function() {}
    ,
    e.prototype.displayLoadingUI = function() {}
    ,
    e.prototype.hideLoadingUI = function() {}
    ,
    e.prototype._uploadCompressedDataToTextureDirectly = function(t, r, n, o, a, s, l) {}
    ,
    e.prototype._uploadDataToTextureDirectly = function(t, r, n, o) {}
    ,
    e.prototype._uploadArrayBufferViewToTexture = function(t, r, n, o) {}
    ,
    e.prototype._uploadImageToTexture = function(t, r, n, o) {}
    ,
    e
}
)(Engine);
ThinEngine.prototype._debugPushGroup = function(i, e) {}
;
ThinEngine.prototype._debugPopGroup = function(i) {}
;
ThinEngine.prototype._debugInsertMarker = function(i, e) {}
;
ThinEngine.prototype._debugFlushPendingCommands = function() {}
;
var _TimeToken = function() {
    function i() {
        this._timeElapsedQueryEnded = !1
    }
    return i
}()
  , _OcclusionDataStorage = function() {
    function i() {
        this.occlusionInternalRetryCounter = 0,
        this.isOcclusionQueryInProgress = !1,
        this.isOccluded = !1,
        this.occlusionRetryCount = -1,
        this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE,
        this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE
    }
    return i
}();
Engine.prototype.createQuery = function() {
    return this._gl.createQuery()
}
;
Engine.prototype.deleteQuery = function(i) {
    return this._gl.deleteQuery(i),
    this
}
;
Engine.prototype.isQueryResultAvailable = function(i) {
    return this._gl.getQueryParameter(i, this._gl.QUERY_RESULT_AVAILABLE)
}
;
Engine.prototype.getQueryResult = function(i) {
    return this._gl.getQueryParameter(i, this._gl.QUERY_RESULT)
}
;
Engine.prototype.beginOcclusionQuery = function(i, e) {
    var t = this._getGlAlgorithmType(i);
    return this._gl.beginQuery(t, e),
    !0
}
;
Engine.prototype.endOcclusionQuery = function(i) {
    var e = this._getGlAlgorithmType(i);
    return this._gl.endQuery(e),
    this
}
;
Engine.prototype._createTimeQuery = function() {
    var i = this.getCaps().timerQuery;
    return i.createQueryEXT ? i.createQueryEXT() : this.createQuery()
}
;
Engine.prototype._deleteTimeQuery = function(i) {
    var e = this.getCaps().timerQuery;
    if (e.deleteQueryEXT) {
        e.deleteQueryEXT(i);
        return
    }
    this.deleteQuery(i)
}
;
Engine.prototype._getTimeQueryResult = function(i) {
    var e = this.getCaps().timerQuery;
    return e.getQueryObjectEXT ? e.getQueryObjectEXT(i, e.QUERY_RESULT_EXT) : this.getQueryResult(i)
}
;
Engine.prototype._getTimeQueryAvailability = function(i) {
    var e = this.getCaps().timerQuery;
    return e.getQueryObjectEXT ? e.getQueryObjectEXT(i, e.QUERY_RESULT_AVAILABLE_EXT) : this.isQueryResultAvailable(i)
}
;
Engine.prototype.startTimeQuery = function() {
    var i = this.getCaps()
      , e = i.timerQuery;
    if (!e)
        return null;
    var t = new _TimeToken;
    if (this._gl.getParameter(e.GPU_DISJOINT_EXT),
    i.canUseTimestampForTimerQuery)
        t._startTimeQuery = this._createTimeQuery(),
        e.queryCounterEXT(t._startTimeQuery, e.TIMESTAMP_EXT);
    else {
        if (this._currentNonTimestampToken)
            return this._currentNonTimestampToken;
        t._timeElapsedQuery = this._createTimeQuery(),
        e.beginQueryEXT ? e.beginQueryEXT(e.TIME_ELAPSED_EXT, t._timeElapsedQuery) : this._gl.beginQuery(e.TIME_ELAPSED_EXT, t._timeElapsedQuery),
        this._currentNonTimestampToken = t
    }
    return t
}
;
Engine.prototype.endTimeQuery = function(i) {
    var e = this.getCaps()
      , t = e.timerQuery;
    if (!t || !i)
        return -1;
    if (e.canUseTimestampForTimerQuery) {
        if (!i._startTimeQuery)
            return -1;
        i._endTimeQuery || (i._endTimeQuery = this._createTimeQuery(),
        t.queryCounterEXT(i._endTimeQuery, t.TIMESTAMP_EXT))
    } else if (!i._timeElapsedQueryEnded) {
        if (!i._timeElapsedQuery)
            return -1;
        t.endQueryEXT ? t.endQueryEXT(t.TIME_ELAPSED_EXT) : this._gl.endQuery(t.TIME_ELAPSED_EXT),
        i._timeElapsedQueryEnded = !0
    }
    var r = this._gl.getParameter(t.GPU_DISJOINT_EXT)
      , n = !1;
    if (i._endTimeQuery ? n = this._getTimeQueryAvailability(i._endTimeQuery) : i._timeElapsedQuery && (n = this._getTimeQueryAvailability(i._timeElapsedQuery)),
    n && !r) {
        var o = 0;
        if (e.canUseTimestampForTimerQuery) {
            if (!i._startTimeQuery || !i._endTimeQuery)
                return -1;
            var a = this._getTimeQueryResult(i._startTimeQuery)
              , s = this._getTimeQueryResult(i._endTimeQuery);
            o = s - a,
            this._deleteTimeQuery(i._startTimeQuery),
            this._deleteTimeQuery(i._endTimeQuery),
            i._startTimeQuery = null,
            i._endTimeQuery = null
        } else {
            if (!i._timeElapsedQuery)
                return -1;
            o = this._getTimeQueryResult(i._timeElapsedQuery),
            this._deleteTimeQuery(i._timeElapsedQuery),
            i._timeElapsedQuery = null,
            i._timeElapsedQueryEnded = !1,
            this._currentNonTimestampToken = null
        }
        return o
    }
    return -1
}
;
Engine.prototype._captureGPUFrameTime = !1;
Engine.prototype._gpuFrameTime = new PerfCounter;
Engine.prototype.getGPUFrameTimeCounter = function() {
    return this._gpuFrameTime
}
;
Engine.prototype.captureGPUFrameTime = function(i) {
    var e = this;
    i !== this._captureGPUFrameTime && (this._captureGPUFrameTime = i,
    i ? (this._onBeginFrameObserver = this.onBeginFrameObservable.add(function() {
        e._gpuFrameTimeToken || (e._gpuFrameTimeToken = e.startTimeQuery())
    }),
    this._onEndFrameObserver = this.onEndFrameObservable.add(function() {
        if (!!e._gpuFrameTimeToken) {
            var t = e.endTimeQuery(e._gpuFrameTimeToken);
            t > -1 && (e._gpuFrameTimeToken = null,
            e._gpuFrameTime.fetchNewFrame(),
            e._gpuFrameTime.addCount(t, !0))
        }
    })) : (this.onBeginFrameObservable.remove(this._onBeginFrameObserver),
    this._onBeginFrameObserver = null,
    this.onEndFrameObservable.remove(this._onEndFrameObserver),
    this._onEndFrameObserver = null))
}
;
Engine.prototype._getGlAlgorithmType = function(i) {
    return i === AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED
}
;
Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
    get: function() {
        return this._occlusionDataStorage.isOcclusionQueryInProgress
    },
    set: function(i) {
        this._occlusionDataStorage.isOcclusionQueryInProgress = i
    },
    enumerable: !1,
    configurable: !0
});
Object.defineProperty(AbstractMesh.prototype, "_occlusionDataStorage", {
    get: function() {
        return this.__occlusionDataStorage || (this.__occlusionDataStorage = new _OcclusionDataStorage),
        this.__occlusionDataStorage
    },
    enumerable: !1,
    configurable: !0
});
Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
    get: function() {
        return this._occlusionDataStorage.isOccluded
    },
    set: function(i) {
        this._occlusionDataStorage.isOccluded = i
    },
    enumerable: !0,
    configurable: !0
});
Object.defineProperty(AbstractMesh.prototype, "occlusionQueryAlgorithmType", {
    get: function() {
        return this._occlusionDataStorage.occlusionQueryAlgorithmType
    },
    set: function(i) {
        this._occlusionDataStorage.occlusionQueryAlgorithmType = i
    },
    enumerable: !0,
    configurable: !0
});
Object.defineProperty(AbstractMesh.prototype, "occlusionType", {
    get: function() {
        return this._occlusionDataStorage.occlusionType
    },
    set: function(i) {
        this._occlusionDataStorage.occlusionType = i
    },
    enumerable: !0,
    configurable: !0
});
Object.defineProperty(AbstractMesh.prototype, "occlusionRetryCount", {
    get: function() {
        return this._occlusionDataStorage.occlusionRetryCount
    },
    set: function(i) {
        this._occlusionDataStorage.occlusionRetryCount = i
    },
    enumerable: !0,
    configurable: !0
});
AbstractMesh.prototype._checkOcclusionQuery = function() {
    var i = this._occlusionDataStorage;
    if (i.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE)
        return i.isOccluded = !1,
        !1;
    var e = this.getEngine();
    if (!e.getCaps().supportOcclusionQuery || !e.isQueryResultAvailable)
        return i.isOccluded = !1,
        !1;
    if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
        var t = e.isQueryResultAvailable(this._occlusionQuery);
        if (t) {
            var r = e.getQueryResult(this._occlusionQuery);
            i.isOcclusionQueryInProgress = !1,
            i.occlusionInternalRetryCounter = 0,
            i.isOccluded = !(r > 0)
        } else if (i.occlusionInternalRetryCounter++,
        i.occlusionRetryCount !== -1 && i.occlusionInternalRetryCounter > i.occlusionRetryCount)
            i.isOcclusionQueryInProgress = !1,
            i.occlusionInternalRetryCounter = 0,
            i.isOccluded = i.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? !1 : i.isOccluded;
        else
            return i.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? !1 : i.isOccluded
    }
    var n = this.getScene();
    if (n.getBoundingBoxRenderer) {
        var o = n.getBoundingBoxRenderer();
        this._occlusionQuery === null && (this._occlusionQuery = e.createQuery()),
        e.beginOcclusionQuery(i.occlusionQueryAlgorithmType, this._occlusionQuery) && (o.renderOcclusionBoundingBox(this),
        e.endOcclusionQuery(i.occlusionQueryAlgorithmType),
        this._occlusionDataStorage.isOcclusionQueryInProgress = !0)
    }
    return i.isOccluded
}
;
Engine.prototype.createTransformFeedback = function() {
    return this._gl.createTransformFeedback()
}
;
Engine.prototype.deleteTransformFeedback = function(i) {
    this._gl.deleteTransformFeedback(i)
}
;
Engine.prototype.bindTransformFeedback = function(i) {
    this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, i)
}
;
Engine.prototype.beginTransformFeedback = function(i) {
    i === void 0 && (i = !0),
    this._gl.beginTransformFeedback(i ? this._gl.POINTS : this._gl.TRIANGLES)
}
;
Engine.prototype.endTransformFeedback = function() {
    this._gl.endTransformFeedback()
}
;
Engine.prototype.setTranformFeedbackVaryings = function(i, e) {
    this._gl.transformFeedbackVaryings(i, e, this._gl.INTERLEAVED_ATTRIBS)
}
;
Engine.prototype.bindTransformFeedbackBuffer = function(i) {
    this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, i ? i.underlyingResource : null)
}
;
ThinEngine.prototype.createExternalTexture = function(i) {
    return null
}
;
ThinEngine.prototype.setExternalTexture = function(i, e) {
    throw new Error("setExternalTexture: This engine does not support external textures!")
}
;
ThinEngine.prototype.restoreSingleAttachment = function() {
    var i = this._gl;
    this.bindAttachments([i.BACK])
}
;
ThinEngine.prototype.restoreSingleAttachmentForRenderTarget = function() {
    var i = this._gl;
    this.bindAttachments([i.COLOR_ATTACHMENT0])
}
;
ThinEngine.prototype.buildTextureLayout = function(i) {
    for (var e = this._gl, t = [], r = 0; r < i.length; r++)
        i[r] ? t.push(e["COLOR_ATTACHMENT" + r]) : t.push(e.NONE);
    return t
}
;
ThinEngine.prototype.bindAttachments = function(i) {
    var e = this._gl;
    e.drawBuffers(i)
}
;
ThinEngine.prototype.unBindMultiColorAttachmentFramebuffer = function(i, e, t) {
    e === void 0 && (e = !1),
    this._currentRenderTarget = null;
    var r = this._gl
      , n = i._attachments
      , o = n.length;
    if (i._MSAAFramebuffer) {
        r.bindFramebuffer(r.READ_FRAMEBUFFER, i._MSAAFramebuffer),
        r.bindFramebuffer(r.DRAW_FRAMEBUFFER, i._framebuffer);
        for (var a = 0; a < o; a++) {
            for (var s = i.textures[a], l = 0; l < o; l++)
                n[l] = r.NONE;
            n[a] = r[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + a : "COLOR_ATTACHMENT" + a + "_WEBGL"],
            r.readBuffer(n[a]),
            r.drawBuffers(n),
            r.blitFramebuffer(0, 0, s.width, s.height, 0, 0, s.width, s.height, r.COLOR_BUFFER_BIT, r.NEAREST)
        }
        for (var a = 0; a < o; a++)
            n[a] = r[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + a : "COLOR_ATTACHMENT" + a + "_WEBGL"];
        r.drawBuffers(n)
    }
    for (var a = 0; a < o; a++) {
        var s = i.textures[a];
        s.generateMipMaps && !e && !s.isCube && (this._bindTextureDirectly(r.TEXTURE_2D, s, !0),
        r.generateMipmap(r.TEXTURE_2D),
        this._bindTextureDirectly(r.TEXTURE_2D, null))
    }
    t && (i._MSAAFramebuffer && this._bindUnboundFramebuffer(i._framebuffer),
    t()),
    this._bindUnboundFramebuffer(null)
}
;
ThinEngine.prototype.createMultipleRenderTarget = function(i, e, t) {
    t === void 0 && (t = !0);
    var r = !1
      , n = !0
      , o = !1
      , a = !1
      , s = 15
      , l = 1
      , u = 0
      , c = 3
      , h = new Array
      , f = new Array
      , d = this._createHardwareRenderTargetWrapper(!0, !1, i);
    e !== void 0 && (r = e.generateMipMaps === void 0 ? !1 : e.generateMipMaps,
    n = e.generateDepthBuffer === void 0 ? !0 : e.generateDepthBuffer,
    o = e.generateStencilBuffer === void 0 ? !1 : e.generateStencilBuffer,
    a = e.generateDepthTexture === void 0 ? !1 : e.generateDepthTexture,
    l = e.textureCount || 1,
    e.types && (h = e.types),
    e.samplingModes && (f = e.samplingModes),
    this.webGLVersion > 1 && (e.depthTextureFormat === 13 || e.depthTextureFormat === 16 || e.depthTextureFormat === 14) && (s = e.depthTextureFormat));
    var _ = this._gl
      , g = _.createFramebuffer();
    this._bindUnboundFramebuffer(g);
    var m = i.width || i
      , v = i.height || i
      , y = []
      , b = []
      , T = this.webGLVersion > 1 && a && e.depthTextureFormat === 13
      , C = this._setupFramebufferDepthAttachments(!T && o, !a && n, m, v);
    d._framebuffer = g,
    d._depthStencilBuffer = C,
    d._generateDepthBuffer = !a && n,
    d._generateStencilBuffer = !T && o,
    d._attachments = b;
    for (var A = 0; A < l; A++) {
        var S = f[A] || c
          , P = h[A] || u;
        (P === 1 && !this._caps.textureFloatLinearFiltering || P === 2 && !this._caps.textureHalfFloatLinearFiltering) && (S = 1);
        var R = this._getSamplingParameters(S, r);
        P === 1 && !this._caps.textureFloat && (P = 0,
        Logger$2.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type"));
        var M = new InternalTexture(this,InternalTextureSource.MultiRenderTarget)
          , x = _[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + A : "COLOR_ATTACHMENT" + A + "_WEBGL"];
        y.push(M),
        b.push(x),
        _.activeTexture(_["TEXTURE" + A]),
        _.bindTexture(_.TEXTURE_2D, M._hardwareTexture.underlyingResource),
        _.texParameteri(_.TEXTURE_2D, _.TEXTURE_MAG_FILTER, R.mag),
        _.texParameteri(_.TEXTURE_2D, _.TEXTURE_MIN_FILTER, R.min),
        _.texParameteri(_.TEXTURE_2D, _.TEXTURE_WRAP_S, _.CLAMP_TO_EDGE),
        _.texParameteri(_.TEXTURE_2D, _.TEXTURE_WRAP_T, _.CLAMP_TO_EDGE),
        _.texImage2D(_.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(P), m, v, 0, _.RGBA, this._getWebGLTextureType(P), null),
        _.framebufferTexture2D(_.DRAW_FRAMEBUFFER, x, _.TEXTURE_2D, M._hardwareTexture.underlyingResource, 0),
        r && this._gl.generateMipmap(this._gl.TEXTURE_2D),
        this._bindTextureDirectly(_.TEXTURE_2D, null),
        M.baseWidth = m,
        M.baseHeight = v,
        M.width = m,
        M.height = v,
        M.isReady = !0,
        M.samples = 1,
        M.generateMipMaps = r,
        M.samplingMode = S,
        M.type = P,
        this._internalTexturesCache.push(M)
    }
    if (a && this._caps.depthTextureExtension) {
        var I = new InternalTexture(this,InternalTextureSource.Depth)
          , w = 5
          , O = _.DEPTH_COMPONENT16
          , D = _.DEPTH_COMPONENT
          , F = _.UNSIGNED_SHORT
          , V = _.DEPTH_ATTACHMENT;
        this.webGLVersion < 2 ? O = _.DEPTH_COMPONENT : s === 14 ? (w = 1,
        F = _.FLOAT,
        O = _.DEPTH_COMPONENT32F) : s === 16 ? (w = 0,
        F = _.UNSIGNED_INT,
        O = _.DEPTH_COMPONENT24,
        V = _.DEPTH_ATTACHMENT) : s === 13 && (w = 12,
        F = _.UNSIGNED_INT_24_8,
        O = _.DEPTH24_STENCIL8,
        D = _.DEPTH_STENCIL,
        V = _.DEPTH_STENCIL_ATTACHMENT),
        _.activeTexture(_.TEXTURE0),
        _.bindTexture(_.TEXTURE_2D, I._hardwareTexture.underlyingResource),
        _.texParameteri(_.TEXTURE_2D, _.TEXTURE_MAG_FILTER, _.NEAREST),
        _.texParameteri(_.TEXTURE_2D, _.TEXTURE_MIN_FILTER, _.NEAREST),
        _.texParameteri(_.TEXTURE_2D, _.TEXTURE_WRAP_S, _.CLAMP_TO_EDGE),
        _.texParameteri(_.TEXTURE_2D, _.TEXTURE_WRAP_T, _.CLAMP_TO_EDGE),
        _.texImage2D(_.TEXTURE_2D, 0, O, m, v, 0, D, F, null),
        _.framebufferTexture2D(_.FRAMEBUFFER, V, _.TEXTURE_2D, I._hardwareTexture.underlyingResource, 0),
        I.baseWidth = m,
        I.baseHeight = v,
        I.width = m,
        I.height = v,
        I.isReady = !0,
        I.samples = 1,
        I.generateMipMaps = r,
        I.samplingMode = 1,
        I.format = s,
        I.type = w,
        y.push(I),
        this._internalTexturesCache.push(I)
    }
    return d.setTextures(y),
    t && _.drawBuffers(b),
    this._bindUnboundFramebuffer(null),
    this.resetTextureCache(),
    d
}
;
ThinEngine.prototype.updateMultipleRenderTargetTextureSampleCount = function(i, e, t) {
    if (t === void 0 && (t = !0),
    this.webGLVersion < 2 || !i || !i.texture)
        return 1;
    if (i.samples === e)
        return e;
    var r = i._attachments.length;
    if (r === 0)
        return 1;
    var n = this._gl;
    e = Math.min(e, this.getCaps().maxMSAASamples),
    i._depthStencilBuffer && (n.deleteRenderbuffer(i._depthStencilBuffer),
    i._depthStencilBuffer = null),
    i._MSAAFramebuffer && (n.deleteFramebuffer(i._MSAAFramebuffer),
    i._MSAAFramebuffer = null);
    for (var o = 0; o < r; o++) {
        var a = i.textures[o]._hardwareTexture;
        a != null && a._MSAARenderBuffer && (n.deleteRenderbuffer(a._MSAARenderBuffer),
        a._MSAARenderBuffer = null)
    }
    if (e > 1 && n.renderbufferStorageMultisample) {
        var s = n.createFramebuffer();
        if (!s)
            throw new Error("Unable to create multi sampled framebuffer");
        i._MSAAFramebuffer = s,
        this._bindUnboundFramebuffer(s);
        for (var l = [], o = 0; o < r; o++) {
            var u = i.textures[o]
              , a = u._hardwareTexture
              , c = n[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + o : "COLOR_ATTACHMENT" + o + "_WEBGL"]
              , h = this._createRenderBuffer(u.width, u.height, e, -1, this._getRGBAMultiSampleBufferFormat(u.type), c);
            if (!h)
                throw new Error("Unable to create multi sampled framebuffer");
            a._MSAARenderBuffer = h,
            u.samples = e,
            l.push(c)
        }
        t && n.drawBuffers(l)
    } else
        this._bindUnboundFramebuffer(i._framebuffer);
    return i._depthStencilBuffer = this._setupFramebufferDepthAttachments(i._generateStencilBuffer, i._generateDepthBuffer, i.texture.width, i.texture.height, e),
    this._bindUnboundFramebuffer(null),
    e
}
;
ThinEngine.prototype.setTextureSampler = function(i, e) {
    throw new Error("setTextureSampler: This engine does not support separate texture sampler objects!")
}
;
Engine.prototype.getInputElement = function() {
    return this.inputElement || this.getRenderingCanvas()
}
;
Engine.prototype.registerView = function(i, e, t) {
    var r = this;
    this.views || (this.views = []);
    for (var n = 0, o = this.views; n < o.length; n++) {
        var a = o[n];
        if (a.target === i)
            return a
    }
    var s = this.getRenderingCanvas();
    s && (i.width = s.width,
    i.height = s.height);
    var l = {
        target: i,
        camera: e,
        clearBeforeCopy: t,
        enabled: !0
    };
    return this.views.push(l),
    e && e.onDisposeObservable.add(function() {
        r.unRegisterView(i)
    }),
    l
}
;
Engine.prototype.unRegisterView = function(i) {
    if (!this.views)
        return this;
    for (var e = 0, t = this.views; e < t.length; e++) {
        var r = t[e];
        if (r.target === i) {
            var n = this.views.indexOf(r);
            n !== -1 && this.views.splice(n, 1);
            break
        }
    }
    return this
}
;
Engine.prototype._renderViews = function() {
    if (!this.views)
        return !1;
    var i = this.getRenderingCanvas();
    if (!i)
        return !1;
    for (var e = 0, t = this.views; e < t.length; e++) {
        var r = t[e];
        if (!!r.enabled) {
            var n = r.target
              , o = n.getContext("2d");
            if (!!o) {
                var a = r.camera
                  , s = null
                  , l = null;
                if (a) {
                    if (l = a.getScene(),
                    l.activeCameras && l.activeCameras.length)
                        continue;
                    this.activeView = r,
                    s = l.activeCamera,
                    l.activeCamera = a
                }
                if (r.customResize)
                    r.customResize(n);
                else {
                    var u = Math.floor(n.clientWidth / this._hardwareScalingLevel)
                      , c = Math.floor(n.clientHeight / this._hardwareScalingLevel)
                      , h = u !== n.width || i.width !== n.width || c !== n.height || i.height !== n.height;
                    n.clientWidth && n.clientHeight && h && (n.width = u,
                    n.height = c,
                    this.setSize(u, c))
                }
                if (!i.width || !i.height)
                    return !1;
                this._renderFrame(),
                this.flushFramebuffer(),
                r.clearBeforeCopy && o.clearRect(0, 0, i.width, i.height),
                o.drawImage(i, 0, 0),
                s && l && (l.activeCamera = s)
            }
        }
    }
    return this.activeView = null,
    !0
}
;
var ComputeBindingType;
(function(i) {
    i[i.Texture = 0] = "Texture",
    i[i.StorageTexture = 1] = "StorageTexture",
    i[i.UniformBuffer = 2] = "UniformBuffer",
    i[i.StorageBuffer = 3] = "StorageBuffer",
    i[i.TextureWithoutSampler = 4] = "TextureWithoutSampler",
    i[i.Sampler = 5] = "Sampler"
}
)(ComputeBindingType || (ComputeBindingType = {}));
ThinEngine.prototype.createComputeEffect = function(i, e) {
    throw new Error("createComputeEffect: This engine does not support compute shaders!")
}
;
ThinEngine.prototype.createComputePipelineContext = function() {
    throw new Error("createComputePipelineContext: This engine does not support compute shaders!")
}
;
ThinEngine.prototype.createComputeContext = function() {}
;
ThinEngine.prototype.computeDispatch = function(i, e, t, r, n, o, a) {
    throw new Error("computeDispatch: This engine does not support compute shaders!")
}
;
ThinEngine.prototype.areAllComputeEffectsReady = function() {
    return !0
}
;
ThinEngine.prototype.releaseComputeEffects = function() {}
;
ThinEngine.prototype._prepareComputePipelineContext = function(i, e, t, r, n) {}
;
ThinEngine.prototype._rebuildComputeEffects = function() {}
;
ThinEngine.prototype._executeWhenComputeStateIsCompiled = function(i, e) {
    e()
}
;
ThinEngine.prototype._releaseComputeEffect = function(i) {}
;
ThinEngine.prototype._deleteComputePipelineContext = function(i) {}
;
ThinEngine.prototype.createStorageBuffer = function(i, e) {
    throw new Error("createStorageBuffer: Unsupported method in this engine!")
}
;
ThinEngine.prototype.updateStorageBuffer = function(i, e, t, r) {}
;
ThinEngine.prototype.readFromStorageBuffer = function(i, e, t, r) {
    throw new Error("readFromStorageBuffer: Unsupported method in this engine!")
}
;
ThinEngine.prototype.setStorageBuffer = function(i, e) {
    throw new Error("setStorageBuffer: Unsupported method in this engine!")
}
;
function transformTextureUrl(i) {
    var e = function(o) {
        var a = "\\b" + o + "\\b";
        return i && (i === o || i.match(new RegExp(a,"g")))
    };
    if (this._excludedCompressedTextures && this._excludedCompressedTextures.some(e))
        return i;
    var t = i.lastIndexOf(".")
      , r = i.lastIndexOf("?")
      , n = r > -1 ? i.substring(r, i.length) : "";
    return (t > -1 ? i.substring(0, t) : i) + this._textureFormatInUse + n
}
Object.defineProperty(Engine.prototype, "texturesSupported", {
    get: function() {
        var i = new Array;
        return this._caps.astc && i.push("-astc.ktx"),
        this._caps.s3tc && i.push("-dxt.ktx"),
        this._caps.pvrtc && i.push("-pvrtc.ktx"),
        this._caps.etc2 && i.push("-etc2.ktx"),
        this._caps.etc1 && i.push("-etc1.ktx"),
        i
    },
    enumerable: !0,
    configurable: !0
});
Object.defineProperty(Engine.prototype, "textureFormatInUse", {
    get: function() {
        return this._textureFormatInUse || null
    },
    enumerable: !0,
    configurable: !0
});
Engine.prototype.setCompressedTextureExclusions = function(i) {
    this._excludedCompressedTextures = i
}
;
Engine.prototype.setTextureFormatToUse = function(i) {
    for (var e = this.texturesSupported, t = 0, r = e.length; t < r; t++)
        for (var n = 0, o = i.length; n < o; n++)
            if (e[t] === i[n].toLowerCase())
                return this._transformTextureUrl = transformTextureUrl.bind(this),
                this._textureFormatInUse = e[t];
    return this._textureFormatInUse = "",
    this._transformTextureUrl = null,
    null
}
;
var NativeDataStream = function() {
    function i() {
        var e = this
          , t = new ArrayBuffer(i.DEFAULT_BUFFER_SIZE);
        this._uint32s = new Uint32Array(t),
        this._int32s = new Int32Array(t),
        this._float32s = new Float32Array(t),
        this._length = i.DEFAULT_BUFFER_SIZE / 4,
        this._position = 0,
        this._nativeDataStream = new _native.NativeDataStream(function() {
            e._flush()
        }
        )
    }
    return i.prototype.writeUint32 = function(e) {
        this._flushIfNecessary(1),
        this._uint32s[this._position++] = e
    }
    ,
    i.prototype.writeInt32 = function(e) {
        this._flushIfNecessary(1),
        this._int32s[this._position++] = e
    }
    ,
    i.prototype.writeFloat32 = function(e) {
        this._flushIfNecessary(1),
        this._float32s[this._position++] = e
    }
    ,
    i.prototype.writeUint32Array = function(e) {
        this._flushIfNecessary(1 + e.length),
        this._uint32s[this._position++] = e.length,
        this._uint32s.set(e, this._position),
        this._position += e.length
    }
    ,
    i.prototype.writeInt32Array = function(e) {
        this._flushIfNecessary(1 + e.length),
        this._uint32s[this._position++] = e.length,
        this._int32s.set(e, this._position),
        this._position += e.length
    }
    ,
    i.prototype.writeFloat32Array = function(e) {
        this._flushIfNecessary(1 + e.length),
        this._uint32s[this._position++] = e.length,
        this._float32s.set(e, this._position),
        this._position += e.length
    }
    ,
    i.prototype.writeNativeData = function(e) {
        this._flushIfNecessary(e.length),
        this._uint32s.set(e, this._position),
        this._position += e.length
    }
    ,
    i.prototype.writeBoolean = function(e) {
        this.writeUint32(e ? 1 : 0)
    }
    ,
    i.prototype._flushIfNecessary = function(e) {
        this._position + e > this._length && this._flush()
    }
    ,
    i.prototype._flush = function() {
        this._nativeDataStream.writeBuffer(this._uint32s.buffer, this._position),
        this._position = 0
    }
    ,
    i.DEFAULT_BUFFER_SIZE = 65536,
    i
}();
function ExtractBetweenMarkers(i, e, t, r) {
    for (var n = r, o = 0, a = ""; n < t.length; ) {
        var s = t.charAt(n);
        if (a)
            s === a ? a === '"' || a === "'" ? t.charAt(n - 1) !== "\\" && (a = "") : a = "" : a === "*/" && s === "*" && n + 1 < t.length && (t.charAt(n + 1) === "/" && (a = ""),
            a === "" && n++);
        else
            switch (s) {
            case i:
                o++;
                break;
            case e:
                o--;
                break;
            case '"':
            case "'":
            case "`":
                a = s;
                break;
            case "/":
                if (n + 1 < t.length) {
                    var l = t.charAt(n + 1);
                    l === "/" ? a = `
` : l === "*" && (a = "*/")
                }
                break
            }
        if (n++,
        o === 0)
            break
    }
    return o === 0 ? n - 1 : -1
}
function SkipWhitespaces(i, e) {
    for (; e < i.length; ) {
        var t = i[e];
        if (t !== " " && t !== `
` && t !== "\r" && t !== "	" && t !== `
` && t !== "\xA0")
            break;
        e++
    }
    return e
}
function IsIdentifierChar(i) {
    var e = i.charCodeAt(0);
    return e >= 48 && e <= 57 || e >= 65 && e <= 90 || e >= 97 && e <= 122 || e == 95
}
function RemoveComments(i) {
    for (var e = 0, t = "", r = !1, n = []; e < i.length; ) {
        var o = i.charAt(e);
        if (t)
            o === t ? t === '"' || t === "'" ? (i.charAt(e - 1) !== "\\" && (t = ""),
            n.push(o)) : (t = "",
            r = !1) : t === "*/" && o === "*" && e + 1 < i.length ? (i.charAt(e + 1) === "/" && (t = ""),
            t === "" && (r = !1,
            e++)) : r || n.push(o);
        else {
            switch (o) {
            case '"':
            case "'":
            case "`":
                t = o;
                break;
            case "/":
                if (e + 1 < i.length) {
                    var a = i.charAt(e + 1);
                    a === "/" ? (t = `
`,
                    r = !0) : a === "*" && (t = "*/",
                    r = !0)
                }
                break
            }
            r || n.push(o)
        }
        e++
    }
    return n.join("")
}
function FindBackward(i, e, t) {
    for (; e >= 0 && i.charAt(e) !== t; )
        e--;
    return e
}
function EscapeRegExp(i) {
    return i.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
}
var ShaderCodeInliner = function() {
    function i(e, t) {
        t === void 0 && (t = 20),
        this.debug = !1,
        this._sourceCode = e,
        this._numMaxIterations = t,
        this._functionDescr = [],
        this.inlineToken = "#define inline"
    }
    return Object.defineProperty(i.prototype, "code", {
        get: function() {
            return this._sourceCode
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.processCode = function() {
        this.debug && console.log("Start inlining process (code size=" + this._sourceCode.length + ")..."),
        this._collectFunctions(),
        this._processInlining(this._numMaxIterations),
        this.debug && console.log("End of inlining process.")
    }
    ,
    i.prototype._collectFunctions = function() {
        for (var e = 0; e < this._sourceCode.length; ) {
            var t = this._sourceCode.indexOf(this.inlineToken, e);
            if (t < 0)
                break;
            var r = this._sourceCode.indexOf("(", t + this.inlineToken.length);
            if (r < 0) {
                this.debug && console.warn("Could not find the opening parenthesis after the token. startIndex=" + e),
                e = t + this.inlineToken.length;
                continue
            }
            var n = i._RegexpFindFunctionNameAndType.exec(this._sourceCode.substring(t + this.inlineToken.length, r));
            if (!n) {
                this.debug && console.warn("Could not extract the name/type of the function from: " + this._sourceCode.substring(t + this.inlineToken.length, r)),
                e = t + this.inlineToken.length;
                continue
            }
            var o = [n[3], n[4]]
              , a = o[0]
              , s = o[1]
              , l = ExtractBetweenMarkers("(", ")", this._sourceCode, r);
            if (l < 0) {
                this.debug && console.warn("Could not extract the parameters the function '" + s + "' (type=" + a + "). funcParamsStartIndex=" + r),
                e = t + this.inlineToken.length;
                continue
            }
            var u = this._sourceCode.substring(r + 1, l)
              , c = SkipWhitespaces(this._sourceCode, l + 1);
            if (c === this._sourceCode.length) {
                this.debug && console.warn("Could not extract the body of the function '" + s + "' (type=" + a + "). funcParamsEndIndex=" + l),
                e = t + this.inlineToken.length;
                continue
            }
            var h = ExtractBetweenMarkers("{", "}", this._sourceCode, c);
            if (h < 0) {
                this.debug && console.warn("Could not extract the body of the function '" + s + "' (type=" + a + "). funcBodyStartIndex=" + c),
                e = t + this.inlineToken.length;
                continue
            }
            for (var f = this._sourceCode.substring(c, h + 1), d = RemoveComments(u).split(","), _ = [], g = 0; g < d.length; ++g) {
                var m = d[g].trim()
                  , v = m.lastIndexOf(" ");
                v >= 0 && _.push(m.substring(v + 1))
            }
            a !== "void" && _.push("return"),
            this._functionDescr.push({
                name: s,
                type: a,
                parameters: _,
                body: f,
                callIndex: 0
            }),
            e = h + 1;
            var y = t > 0 ? this._sourceCode.substring(0, t) : ""
              , b = h + 1 < this._sourceCode.length - 1 ? this._sourceCode.substring(h + 1) : "";
            this._sourceCode = y + b,
            e -= h + 1 - t
        }
        this.debug && console.log("Collect functions: " + this._functionDescr.length + " functions found. functionDescr=", this._functionDescr)
    }
    ,
    i.prototype._processInlining = function(e) {
        for (e === void 0 && (e = 20); e-- >= 0 && this._replaceFunctionCallsByCode(); )
            ;
        return this.debug && console.log("numMaxIterations is " + e + " after inlining process"),
        e >= 0
    }
    ,
    i.prototype._replaceFunctionCallsByCode = function() {
        for (var e = !1, t = 0, r = this._functionDescr; t < r.length; t++)
            for (var n = r[t], o = n.name, a = n.type, s = n.parameters, l = n.body, u = 0; u < this._sourceCode.length; ) {
                var c = this._sourceCode.indexOf(o, u);
                if (c < 0)
                    break;
                if (c === 0 || IsIdentifierChar(this._sourceCode.charAt(c - 1))) {
                    u = c + o.length;
                    continue
                }
                var h = SkipWhitespaces(this._sourceCode, c + o.length);
                if (h === this._sourceCode.length || this._sourceCode.charAt(h) !== "(") {
                    u = c + o.length;
                    continue
                }
                var f = ExtractBetweenMarkers("(", ")", this._sourceCode, h);
                if (f < 0) {
                    this.debug && console.warn("Could not extract the parameters of the function call. Function '" + o + "' (type=" + a + "). callParamsStartIndex=" + h),
                    u = c + o.length;
                    continue
                }
                var d = this._sourceCode.substring(h + 1, f)
                  , _ = function(R) {
                    for (var M = [], x = 0, I = 0; x < R.length; ) {
                        if (R.charAt(x) === "(") {
                            var w = ExtractBetweenMarkers("(", ")", R, x);
                            if (w < 0)
                                return null;
                            x = w
                        } else
                            R.charAt(x) === "," && (M.push(R.substring(I, x)),
                            I = x + 1);
                        x++
                    }
                    return I < x && M.push(R.substring(I, x)),
                    M
                }
                  , g = _(RemoveComments(d));
                if (g === null) {
                    this.debug && console.warn("Invalid function call: can't extract the parameters of the function call. Function '" + o + "' (type=" + a + "). callParamsStartIndex=" + h + ", callParams=" + d),
                    u = c + o.length;
                    continue
                }
                for (var m = [], v = 0; v < g.length; ++v) {
                    var y = g[v].trim();
                    m.push(y)
                }
                var b = a !== "void" ? o + "_" + n.callIndex++ : null;
                if (b && m.push(b + " ="),
                m.length !== s.length) {
                    this.debug && console.warn("Invalid function call: not the same number of parameters for the call than the number expected by the function. Function '" + o + "' (type=" + a + "). function parameters=" + s + ", call parameters=" + m),
                    u = c + o.length;
                    continue
                }
                u = f + 1;
                var T = this._replaceNames(l, s, m)
                  , C = c > 0 ? this._sourceCode.substring(0, c) : ""
                  , A = f + 1 < this._sourceCode.length - 1 ? this._sourceCode.substring(f + 1) : "";
                if (b) {
                    var S = FindBackward(this._sourceCode, c - 1, `
`);
                    C = this._sourceCode.substring(0, S + 1);
                    var P = this._sourceCode.substring(S + 1, c);
                    this._sourceCode = C + a + " " + b + `;
` + T + `
` + P + b + A,
                    this.debug && console.log("Replace function call by code. Function '" + o + "' (type=" + a + "). injectDeclarationIndex=" + S + ", call parameters=" + m)
                } else
                    this._sourceCode = C + T + A,
                    u += T.length - (f + 1 - c),
                    this.debug && console.log("Replace function call by code. Function '" + o + "' (type=" + a + "). functionCallIndex=" + c + ", call parameters=" + m);
                e = !0
            }
        return e
    }
    ,
    i.prototype._replaceNames = function(e, t, r) {
        for (var n = function(a) {
            var s = new RegExp(EscapeRegExp(t[a]),"g")
              , l = t[a].length
              , u = r[a];
            e = e.replace(s, function(c) {
                for (var h = [], f = 1; f < arguments.length; f++)
                    h[f - 1] = arguments[f];
                var d = h[0];
                return IsIdentifierChar(e.charAt(d - 1)) || IsIdentifierChar(e.charAt(d + l)) ? t[a] : u
            })
        }, o = 0; o < t.length; ++o)
            n(o);
        return e
    }
    ,
    i._RegexpFindFunctionNameAndType = /((\s+?)(\w+)\s+(\w+)\s*?)$/,
    i
}()
  , NativePipelineContext = function() {
    function i(e) {
        this.isAsync = !1,
        this.isReady = !1,
        this._valueCache = {},
        this.engine = e
    }
    return i.prototype._getVertexShaderCode = function() {
        return null
    }
    ,
    i.prototype._getFragmentShaderCode = function() {
        return null
    }
    ,
    i.prototype._handlesSpectorRebuildCallback = function(e) {
        throw new Error("Not implemented")
    }
    ,
    i.prototype._fillEffectInformation = function(e, t, r, n, o, a, s, l) {
        var u = this.engine;
        if (u.supportsUniformBuffers)
            for (var c in t)
                e.bindUniformBlock(c, t[c]);
        var h = this.engine.getUniforms(this, r);
        h.forEach(function(_, g) {
            n[r[g]] = _
        }),
        this._uniforms = n;
        var f;
        for (f = 0; f < o.length; f++) {
            var d = e.getUniform(o[f]);
            d == null && (o.splice(f, 1),
            f--)
        }
        o.forEach(function(_, g) {
            a[_] = g
        }),
        l.push.apply(l, u.getAttributes(this, s))
    }
    ,
    i.prototype.dispose = function() {
        this._uniforms = {}
    }
    ,
    i.prototype._cacheMatrix = function(e, t) {
        var r = this._valueCache[e]
          , n = t.updateFlag;
        return r !== void 0 && r === n ? !1 : (this._valueCache[e] = n,
        !0)
    }
    ,
    i.prototype._cacheFloat2 = function(e, t, r) {
        var n = this._valueCache[e];
        if (!n)
            return n = [t, r],
            this._valueCache[e] = n,
            !0;
        var o = !1;
        return n[0] !== t && (n[0] = t,
        o = !0),
        n[1] !== r && (n[1] = r,
        o = !0),
        o
    }
    ,
    i.prototype._cacheFloat3 = function(e, t, r, n) {
        var o = this._valueCache[e];
        if (!o)
            return o = [t, r, n],
            this._valueCache[e] = o,
            !0;
        var a = !1;
        return o[0] !== t && (o[0] = t,
        a = !0),
        o[1] !== r && (o[1] = r,
        a = !0),
        o[2] !== n && (o[2] = n,
        a = !0),
        a
    }
    ,
    i.prototype._cacheFloat4 = function(e, t, r, n, o) {
        var a = this._valueCache[e];
        if (!a)
            return a = [t, r, n, o],
            this._valueCache[e] = a,
            !0;
        var s = !1;
        return a[0] !== t && (a[0] = t,
        s = !0),
        a[1] !== r && (a[1] = r,
        s = !0),
        a[2] !== n && (a[2] = n,
        s = !0),
        a[3] !== o && (a[3] = o,
        s = !0),
        s
    }
    ,
    i.prototype.setInt = function(e, t) {
        var r = this._valueCache[e];
        r !== void 0 && r === t || this.engine.setInt(this._uniforms[e], t) && (this._valueCache[e] = t)
    }
    ,
    i.prototype.setInt2 = function(e, t, r) {
        this._cacheFloat2(e, t, r) && (this.engine.setInt2(this._uniforms[e], t, r) || (this._valueCache[e] = null))
    }
    ,
    i.prototype.setInt3 = function(e, t, r, n) {
        this._cacheFloat3(e, t, r, n) && (this.engine.setInt3(this._uniforms[e], t, r, n) || (this._valueCache[e] = null))
    }
    ,
    i.prototype.setInt4 = function(e, t, r, n, o) {
        this._cacheFloat4(e, t, r, n, o) && (this.engine.setInt4(this._uniforms[e], t, r, n, o) || (this._valueCache[e] = null))
    }
    ,
    i.prototype.setIntArray = function(e, t) {
        this._valueCache[e] = null,
        this.engine.setIntArray(this._uniforms[e], t)
    }
    ,
    i.prototype.setIntArray2 = function(e, t) {
        this._valueCache[e] = null,
        this.engine.setIntArray2(this._uniforms[e], t)
    }
    ,
    i.prototype.setIntArray3 = function(e, t) {
        this._valueCache[e] = null,
        this.engine.setIntArray3(this._uniforms[e], t)
    }
    ,
    i.prototype.setIntArray4 = function(e, t) {
        this._valueCache[e] = null,
        this.engine.setIntArray4(this._uniforms[e], t)
    }
    ,
    i.prototype.setFloatArray = function(e, t) {
        this._valueCache[e] = null,
        this.engine.setFloatArray(this._uniforms[e], t)
    }
    ,
    i.prototype.setFloatArray2 = function(e, t) {
        this._valueCache[e] = null,
        this.engine.setFloatArray2(this._uniforms[e], t)
    }
    ,
    i.prototype.setFloatArray3 = function(e, t) {
        this._valueCache[e] = null,
        this.engine.setFloatArray3(this._uniforms[e], t)
    }
    ,
    i.prototype.setFloatArray4 = function(e, t) {
        this._valueCache[e] = null,
        this.engine.setFloatArray4(this._uniforms[e], t)
    }
    ,
    i.prototype.setArray = function(e, t) {
        this._valueCache[e] = null,
        this.engine.setArray(this._uniforms[e], t)
    }
    ,
    i.prototype.setArray2 = function(e, t) {
        this._valueCache[e] = null,
        this.engine.setArray2(this._uniforms[e], t)
    }
    ,
    i.prototype.setArray3 = function(e, t) {
        this._valueCache[e] = null,
        this.engine.setArray3(this._uniforms[e], t)
    }
    ,
    i.prototype.setArray4 = function(e, t) {
        this._valueCache[e] = null,
        this.engine.setArray4(this._uniforms[e], t)
    }
    ,
    i.prototype.setMatrices = function(e, t) {
        !t || (this._valueCache[e] = null,
        this.engine.setMatrices(this._uniforms[e], t))
    }
    ,
    i.prototype.setMatrix = function(e, t) {
        this._cacheMatrix(e, t) && (this.engine.setMatrices(this._uniforms[e], t.toArray()) || (this._valueCache[e] = null))
    }
    ,
    i.prototype.setMatrix3x3 = function(e, t) {
        this._valueCache[e] = null,
        this.engine.setMatrix3x3(this._uniforms[e], t)
    }
    ,
    i.prototype.setMatrix2x2 = function(e, t) {
        this._valueCache[e] = null,
        this.engine.setMatrix2x2(this._uniforms[e], t)
    }
    ,
    i.prototype.setFloat = function(e, t) {
        var r = this._valueCache[e];
        r !== void 0 && r === t || this.engine.setFloat(this._uniforms[e], t) && (this._valueCache[e] = t)
    }
    ,
    i.prototype.setBool = function(e, t) {
        var r = this._valueCache[e];
        r !== void 0 && r === t || this.engine.setInt(this._uniforms[e], t ? 1 : 0) && (this._valueCache[e] = t ? 1 : 0)
    }
    ,
    i.prototype.setVector2 = function(e, t) {
        this._cacheFloat2(e, t.x, t.y) && (this.engine.setFloat2(this._uniforms[e], t.x, t.y) || (this._valueCache[e] = null))
    }
    ,
    i.prototype.setFloat2 = function(e, t, r) {
        this._cacheFloat2(e, t, r) && (this.engine.setFloat2(this._uniforms[e], t, r) || (this._valueCache[e] = null))
    }
    ,
    i.prototype.setVector3 = function(e, t) {
        this._cacheFloat3(e, t.x, t.y, t.z) && (this.engine.setFloat3(this._uniforms[e], t.x, t.y, t.z) || (this._valueCache[e] = null))
    }
    ,
    i.prototype.setFloat3 = function(e, t, r, n) {
        this._cacheFloat3(e, t, r, n) && (this.engine.setFloat3(this._uniforms[e], t, r, n) || (this._valueCache[e] = null))
    }
    ,
    i.prototype.setVector4 = function(e, t) {
        this._cacheFloat4(e, t.x, t.y, t.z, t.w) && (this.engine.setFloat4(this._uniforms[e], t.x, t.y, t.z, t.w) || (this._valueCache[e] = null))
    }
    ,
    i.prototype.setFloat4 = function(e, t, r, n, o) {
        this._cacheFloat4(e, t, r, n, o) && (this.engine.setFloat4(this._uniforms[e], t, r, n, o) || (this._valueCache[e] = null))
    }
    ,
    i.prototype.setColor3 = function(e, t) {
        this._cacheFloat3(e, t.r, t.g, t.b) && (this.engine.setFloat3(this._uniforms[e], t.r, t.g, t.b) || (this._valueCache[e] = null))
    }
    ,
    i.prototype.setColor4 = function(e, t, r) {
        this._cacheFloat4(e, t.r, t.g, t.b, r) && (this.engine.setFloat4(this._uniforms[e], t.r, t.g, t.b, r) || (this._valueCache[e] = null))
    }
    ,
    i.prototype.setDirectColor4 = function(e, t) {
        this._cacheFloat4(e, t.r, t.g, t.b, t.a) && (this.engine.setFloat4(this._uniforms[e], t.r, t.g, t.b, t.a) || (this._valueCache[e] = null))
    }
    ,
    i
}()
  , NativeRenderTargetWrapper = function(i) {
    __extends(e, i);
    function e(t, r, n, o) {
        var a = i.call(this, t, r, n, o) || this;
        return a.__framebuffer = null,
        a.__framebufferDepthStencil = null,
        a._engine = o,
        a
    }
    return Object.defineProperty(e.prototype, "_framebuffer", {
        get: function() {
            return this.__framebuffer
        },
        set: function(t) {
            this.__framebuffer && this._engine._releaseFramebufferObjects(this.__framebuffer),
            this.__framebuffer = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "_framebufferDepthStencil", {
        get: function() {
            return this.__framebufferDepthStencil
        },
        set: function(t) {
            this.__framebufferDepthStencil && this._engine._releaseFramebufferObjects(this.__framebufferDepthStencil),
            this.__framebufferDepthStencil = t
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.dispose = function(t) {
        t === void 0 && (t = !1),
        this._framebuffer = null,
        this._framebufferDepthStencil = null,
        i.prototype.dispose.call(this, t)
    }
    ,
    e
}(RenderTargetWrapper)
  , NativeDataBuffer = function(i) {
    __extends(e, i);
    function e() {
        return i !== null && i.apply(this, arguments) || this
    }
    return e
}(DataBuffer)
  , CommandBufferEncoder = function() {
    function i(e) {
        this._engine = e,
        this._pending = new Array,
        this._isCommandBufferScopeActive = !1,
        this._commandStream = NativeEngine._createNativeDataStream(),
        this._engine.setCommandDataStream(this._commandStream)
    }
    return i.prototype.beginCommandScope = function() {
        if (this._isCommandBufferScopeActive)
            throw new Error("Command scope already active.");
        this._isCommandBufferScopeActive = !0
    }
    ,
    i.prototype.endCommandScope = function() {
        if (!this._isCommandBufferScopeActive)
            throw new Error("Command scope is not active.");
        this._isCommandBufferScopeActive = !1,
        this._submit()
    }
    ,
    i.prototype.startEncodingCommand = function(e) {
        this._commandStream.writeNativeData(e)
    }
    ,
    i.prototype.encodeCommandArgAsUInt32 = function(e) {
        this._commandStream.writeUint32(e)
    }
    ,
    i.prototype.encodeCommandArgAsUInt32s = function(e) {
        this._commandStream.writeUint32Array(e)
    }
    ,
    i.prototype.encodeCommandArgAsInt32 = function(e) {
        this._commandStream.writeInt32(e)
    }
    ,
    i.prototype.encodeCommandArgAsInt32s = function(e) {
        this._commandStream.writeInt32Array(e)
    }
    ,
    i.prototype.encodeCommandArgAsFloat32 = function(e) {
        this._commandStream.writeFloat32(e)
    }
    ,
    i.prototype.encodeCommandArgAsFloat32s = function(e) {
        this._commandStream.writeFloat32Array(e)
    }
    ,
    i.prototype.encodeCommandArgAsNativeData = function(e) {
        this._commandStream.writeNativeData(e),
        this._pending.push(e)
    }
    ,
    i.prototype.finishEncodingCommand = function() {
        this._isCommandBufferScopeActive || this._submit()
    }
    ,
    i.prototype._submit = function() {
        this._engine.submitCommands(),
        this._pending.length = 0
    }
    ,
    i
}()
  , NativeEngine = function(i) {
    __extends(e, i);
    function e(t) {
        t === void 0 && (t = {});
        var r = i.call(this, null, !1, void 0, t.adaptToDeviceRatio) || this;
        if (r._engine = new _native.Engine,
        r._camera = _native.Camera ? new _native.Camera : null,
        r._commandBufferEncoder = new CommandBufferEncoder(r._engine),
        r._boundBuffersVertexArray = null,
        r._currentDepthTest = _native.Engine.DEPTH_TEST_LEQUAL,
        r._stencilTest = !1,
        r._stencilMask = 255,
        r._stencilFunc = 519,
        r._stencilFuncRef = 0,
        r._stencilFuncMask = 255,
        r._stencilOpStencilFail = 7680,
        r._stencilOpDepthFail = 7680,
        r._stencilOpStencilDepthPass = 7681,
        r._zOffset = 0,
        r._zOffsetUnits = 0,
        r._depthWrite = !0,
        _native.Engine.PROTOCOL_VERSION !== e.PROTOCOL_VERSION)
            throw new Error("Protocol version mismatch: " + _native.Engine.PROTOCOL_VERSION + " (Native) !== " + e.PROTOCOL_VERSION + " (JS)");
        r._webGLVersion = 2,
        r.disableUniformBuffers = !0,
        r._caps = {
            maxTexturesImageUnits: 16,
            maxVertexTextureImageUnits: 16,
            maxCombinedTexturesImageUnits: 32,
            maxTextureSize: 512,
            maxCubemapTextureSize: 512,
            maxRenderTextureSize: 512,
            maxVertexAttribs: 16,
            maxVaryingVectors: 16,
            maxFragmentUniformVectors: 16,
            maxVertexUniformVectors: 16,
            standardDerivatives: !0,
            astc: null,
            pvrtc: null,
            etc1: null,
            etc2: null,
            bptc: null,
            maxAnisotropy: 16,
            uintIndices: !0,
            fragmentDepthSupported: !1,
            highPrecisionShaderSupported: !0,
            colorBufferFloat: !1,
            textureFloat: !0,
            textureFloatLinearFiltering: !1,
            textureFloatRender: !1,
            textureHalfFloat: !1,
            textureHalfFloatLinearFiltering: !1,
            textureHalfFloatRender: !1,
            textureLOD: !0,
            drawBuffersExtension: !1,
            depthTextureExtension: !1,
            vertexArrayObject: !0,
            instancedArrays: !1,
            supportOcclusionQuery: !1,
            canUseTimestampForTimerQuery: !1,
            blendMinMax: !1,
            maxMSAASamples: 1,
            canUseGLInstanceID: !0,
            canUseGLVertexID: !0,
            supportComputeShaders: !1,
            supportSRGBBuffers: !0
        },
        r._features = {
            forceBitmapOverHTMLImageElement: !1,
            supportRenderAndCopyToLodForFloatTextures: !1,
            supportDepthStencilTexture: !1,
            supportShadowSamplers: !1,
            uniformBufferHardCheckMatrix: !1,
            allowTexturePrefiltering: !1,
            trackUbosInFrame: !1,
            checkUbosContentBeforeUpload: !1,
            supportCSM: !1,
            basisNeedsPOT: !1,
            support3DTextures: !1,
            needTypeSuffixInShaderConstants: !1,
            supportMSAA: !1,
            supportSSAO2: !1,
            supportExtendedTextureFormats: !1,
            supportSwitchCaseInShader: !1,
            supportSyncTextureRead: !1,
            needsInvertingBitmap: !0,
            useUBOBindingCache: !0,
            needShaderCodeInlining: !0,
            needToAlwaysBindUniformBuffers: !1,
            supportRenderPasses: !0,
            _collectUbosUpdatedInFrame: !1
        },
        Tools.Log("Babylon Native (v" + Engine.Version + ") launched"),
        Tools.LoadScript = function(a, s, l, u) {
            Tools.LoadFile(a, function(c) {
                Function(c).apply(null),
                s && s()
            }, void 0, void 0, !1, function(c, h) {
                l && l("LoadScript Error", h)
            })
        }
        ,
        typeof URL == "undefined" && (window.URL = {
            createObjectURL: function() {},
            revokeObjectURL: function() {}
        }),
        typeof Blob == "undefined" && (window.Blob = function(a) {
            return a
        }
        );
        var n = window && window.devicePixelRatio || 1;
        r._hardwareScalingLevel = t.adaptToDeviceRatio ? n : 1,
        r.resize();
        var o = r.getDepthFunction();
        return o && r.setDepthFunction(o),
        r._shaderProcessor = new WebGL2ShaderProcessor,
        r.onNewSceneAddedObservable.add(function(a) {
            var s = a.render;
            a.render = function() {
                for (var l = [], u = 0; u < arguments.length; u++)
                    l[u] = arguments[u];
                r._commandBufferEncoder.beginCommandScope(),
                s.apply(a, l),
                r._commandBufferEncoder.endCommandScope()
            }
        }),
        r
    }
    return e.prototype.getHardwareScalingLevel = function() {
        return this._engine.getHardwareScalingLevel()
    }
    ,
    e.prototype.setHardwareScalingLevel = function(t) {
        this._engine.setHardwareScalingLevel(t)
    }
    ,
    e.prototype.dispose = function() {
        i.prototype.dispose.call(this),
        this._boundBuffersVertexArray && this._deleteVertexArray(this._boundBuffersVertexArray),
        this._engine.dispose()
    }
    ,
    e._createNativeDataStream = function() {
        return new NativeDataStream
    }
    ,
    e.prototype._queueNewFrame = function(t, r) {
        return r.requestAnimationFrame && r !== window ? r.requestAnimationFrame(t) : this._engine.requestAnimationFrame(t),
        0
    }
    ,
    e.prototype._bindUnboundFramebuffer = function(t) {
        this._currentFramebuffer !== t && (this._currentFramebuffer && (this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_UNBINDFRAMEBUFFER),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(this._currentFramebuffer),
        this._commandBufferEncoder.finishEncodingCommand()),
        t && (this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDFRAMEBUFFER),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(t),
        this._commandBufferEncoder.finishEncodingCommand()),
        this._currentFramebuffer = t)
    }
    ,
    e.prototype.getHostDocument = function() {
        return null
    }
    ,
    e.prototype.clear = function(t, r, n, o) {
        if (o === void 0 && (o = !1),
        this.useReverseDepthBuffer)
            throw new Error("reverse depth buffer is not currently implemented");
        this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_CLEAR),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(r && t ? 1 : 0),
        this._commandBufferEncoder.encodeCommandArgAsFloat32(t ? t.r : 0),
        this._commandBufferEncoder.encodeCommandArgAsFloat32(t ? t.g : 0),
        this._commandBufferEncoder.encodeCommandArgAsFloat32(t ? t.b : 0),
        this._commandBufferEncoder.encodeCommandArgAsFloat32(t ? t.a : 1),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(n ? 1 : 0),
        this._commandBufferEncoder.encodeCommandArgAsFloat32(1),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(o ? 1 : 0),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(0),
        this._commandBufferEncoder.finishEncodingCommand()
    }
    ,
    e.prototype.createIndexBuffer = function(t, r) {
        var n = this._normalizeIndexData(t)
          , o = new NativeDataBuffer;
        return o.references = 1,
        o.is32Bits = n.BYTES_PER_ELEMENT === 4,
        n.byteLength && (o.nativeIndexBuffer = this._engine.createIndexBuffer(n.buffer, n.byteOffset, n.byteLength, o.is32Bits, r != null ? r : !1)),
        o
    }
    ,
    e.prototype.createVertexBuffer = function(t, r) {
        var n = ArrayBuffer.isView(t) ? t : new Float32Array(t)
          , o = new NativeDataBuffer;
        return o.references = 1,
        n.byteLength && (o.nativeVertexBuffer = this._engine.createVertexBuffer(n.buffer, n.byteOffset, n.byteLength, r != null ? r : !1)),
        o
    }
    ,
    e.prototype._recordVertexArrayObject = function(t, r, n, o) {
        n && this._engine.recordIndexBuffer(t, n.nativeIndexBuffer);
        for (var a = o.getAttributesNames(), s = 0; s < a.length; s++) {
            var l = o.getAttributeLocation(s);
            if (l >= 0) {
                var u = a[s]
                  , c = r[u];
                if (c) {
                    var h = c.getBuffer();
                    h && this._engine.recordVertexBuffer(t, h.nativeVertexBuffer, l, c.byteOffset, c.byteStride, c.getSize(), this._getNativeAttribType(c.type), c.normalized)
                }
            }
        }
    }
    ,
    e.prototype.bindBuffers = function(t, r, n) {
        this._boundBuffersVertexArray && this._deleteVertexArray(this._boundBuffersVertexArray),
        this._boundBuffersVertexArray = this._engine.createVertexArray(),
        this._recordVertexArrayObject(this._boundBuffersVertexArray, t, r, n),
        this.bindVertexArrayObject(this._boundBuffersVertexArray)
    }
    ,
    e.prototype.recordVertexArrayObject = function(t, r, n) {
        var o = this._engine.createVertexArray();
        return this._recordVertexArrayObject(o, t, r, n),
        o
    }
    ,
    e.prototype._deleteVertexArray = function(t) {
        this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXARRAY),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(t),
        this._commandBufferEncoder.finishEncodingCommand()
    }
    ,
    e.prototype.bindVertexArrayObject = function(t) {
        this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDVERTEXARRAY),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(t),
        this._commandBufferEncoder.finishEncodingCommand()
    }
    ,
    e.prototype.releaseVertexArrayObject = function(t) {
        this._deleteVertexArray(t)
    }
    ,
    e.prototype.getAttributes = function(t, r) {
        var n = t;
        return this._engine.getAttributes(n.nativeProgram, r)
    }
    ,
    e.prototype.drawElementsType = function(t, r, n, o) {
        this._drawCalls.addCount(1, !1),
        this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINDEXED),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(t),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(r),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(n),
        this._commandBufferEncoder.finishEncodingCommand()
    }
    ,
    e.prototype.drawArraysType = function(t, r, n, o) {
        this._drawCalls.addCount(1, !1),
        this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAW),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(t),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(r),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(n),
        this._commandBufferEncoder.finishEncodingCommand()
    }
    ,
    e.prototype.createPipelineContext = function() {
        return new NativePipelineContext(this)
    }
    ,
    e.prototype.createMaterialContext = function() {}
    ,
    e.prototype.createDrawContext = function() {}
    ,
    e.prototype._preparePipelineContext = function(t, r, n, o, a, s, l, u, c) {
        var h = t;
        o ? h.nativeProgram = this.createRawShaderProgram(t, r, n, void 0, c) : h.nativeProgram = this.createShaderProgram(t, r, n, u, void 0, c)
    }
    ,
    e.prototype._isRenderingStateCompiled = function(t) {
        return !0
    }
    ,
    e.prototype._executeWhenRenderingStateIsCompiled = function(t, r) {
        r()
    }
    ,
    e.prototype.createRawShaderProgram = function(t, r, n, o, a) {
        throw new Error("Not Supported")
    }
    ,
    e.prototype.createShaderProgram = function(t, r, n, o, a, s) {
        this.onBeforeShaderCompilationObservable.notifyObservers(this);
        var l = new ShaderCodeInliner(r);
        l.processCode(),
        r = l.code;
        var u = new ShaderCodeInliner(n);
        u.processCode(),
        n = u.code,
        r = ThinEngine._ConcatenateShader(r, o),
        n = ThinEngine._ConcatenateShader(n, o);
        var c = this._engine.createProgram(r, n);
        return this.onAfterShaderCompilationObservable.notifyObservers(this),
        c
    }
    ,
    e.prototype.inlineShaderCode = function(t) {
        var r = new ShaderCodeInliner(t);
        return r.debug = !1,
        r.processCode(),
        r.code
    }
    ,
    e.prototype._setProgram = function(t) {
        this._currentProgram !== t && (this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETPROGRAM),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(t),
        this._commandBufferEncoder.finishEncodingCommand(),
        this._currentProgram = t)
    }
    ,
    e.prototype._deletePipelineContext = function(t) {
        var r = t;
        r && r.nativeProgram && (this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEPROGRAM),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(r.nativeProgram),
        this._commandBufferEncoder.finishEncodingCommand())
    }
    ,
    e.prototype.getUniforms = function(t, r) {
        var n = t;
        return this._engine.getUniforms(n.nativeProgram, r)
    }
    ,
    e.prototype.bindUniformBlock = function(t, r, n) {
        throw new Error("Not Implemented")
    }
    ,
    e.prototype.bindSamplers = function(t) {
        var r = t.getPipelineContext();
        this._setProgram(r.nativeProgram);
        for (var n = t.getSamplers(), o = 0; o < n.length; o++) {
            var a = t.getUniform(n[o]);
            a && (this._boundUniforms[o] = a)
        }
        this._currentEffect = null
    }
    ,
    e.prototype.setMatrix = function(t, r) {
        if (!!t) {
            var n = r.toArray();
            this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX),
            this._commandBufferEncoder.encodeCommandArgAsNativeData(t),
            this._commandBufferEncoder.encodeCommandArgAsFloat32s(n),
            this._commandBufferEncoder.finishEncodingCommand()
        }
    }
    ,
    e.prototype.getRenderWidth = function(t) {
        return t === void 0 && (t = !1),
        !t && this._currentRenderTarget ? this._currentRenderTarget.width : this._engine.getRenderWidth()
    }
    ,
    e.prototype.getRenderHeight = function(t) {
        return t === void 0 && (t = !1),
        !t && this._currentRenderTarget ? this._currentRenderTarget.height : this._engine.getRenderHeight()
    }
    ,
    e.prototype.setViewport = function(t, r, n) {
        this._cachedViewport = t,
        this._engine.setViewPort(t.x, t.y, t.width, t.height)
    }
    ,
    e.prototype.setState = function(t, r, n, o, a, s, l) {
        var u, c;
        r === void 0 && (r = 0),
        o === void 0 && (o = !1),
        l === void 0 && (l = 0),
        this._zOffset = r,
        this._zOffsetUnits = l,
        this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTATE),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(t ? 1 : 0),
        this._commandBufferEncoder.encodeCommandArgAsFloat32(r),
        this._commandBufferEncoder.encodeCommandArgAsFloat32(l),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(!((c = (u = this.cullBackFaces) !== null && u !== void 0 ? u : a) !== null && c !== void 0) || c ? 1 : 0),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(o ? 1 : 0),
        this._commandBufferEncoder.finishEncodingCommand()
    }
    ,
    e.prototype.getInputElementClientRect = function() {
        var t = {
            bottom: this.getRenderHeight(),
            height: this.getRenderHeight(),
            left: 0,
            right: this.getRenderWidth(),
            top: 0,
            width: this.getRenderWidth(),
            x: 0,
            y: 0,
            toJSON: function() {}
        };
        return t
    }
    ,
    e.prototype.setZOffset = function(t) {
        t !== this._zOffset && (this._zOffset = t,
        this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSET),
        this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer ? -t : t),
        this._commandBufferEncoder.finishEncodingCommand())
    }
    ,
    e.prototype.getZOffset = function() {
        return this._zOffset
    }
    ,
    e.prototype.setZOffsetUnits = function(t) {
        t !== this._zOffsetUnits && (this._zOffsetUnits = t,
        this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSETUNITS),
        this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer ? -t : t),
        this._commandBufferEncoder.finishEncodingCommand())
    }
    ,
    e.prototype.getZOffsetUnits = function() {
        return this._zOffsetUnits
    }
    ,
    e.prototype.setDepthBuffer = function(t) {
        this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(t ? this._currentDepthTest : _native.Engine.DEPTH_TEST_ALWAYS),
        this._commandBufferEncoder.finishEncodingCommand()
    }
    ,
    e.prototype.getDepthWrite = function() {
        return this._depthWrite
    }
    ,
    e.prototype.getDepthFunction = function() {
        switch (this._currentDepthTest) {
        case _native.Engine.DEPTH_TEST_NEVER:
            return 512;
        case _native.Engine.DEPTH_TEST_ALWAYS:
            return 519;
        case _native.Engine.DEPTH_TEST_GREATER:
            return 516;
        case _native.Engine.DEPTH_TEST_GEQUAL:
            return 518;
        case _native.Engine.DEPTH_TEST_NOTEQUAL:
            return 517;
        case _native.Engine.DEPTH_TEST_EQUAL:
            return 514;
        case _native.Engine.DEPTH_TEST_LESS:
            return 513;
        case _native.Engine.DEPTH_TEST_LEQUAL:
            return 515
        }
        return null
    }
    ,
    e.prototype.setDepthFunction = function(t) {
        var r = 0;
        switch (t) {
        case 512:
            r = _native.Engine.DEPTH_TEST_NEVER;
            break;
        case 519:
            r = _native.Engine.DEPTH_TEST_ALWAYS;
            break;
        case 516:
            r = _native.Engine.DEPTH_TEST_GREATER;
            break;
        case 518:
            r = _native.Engine.DEPTH_TEST_GEQUAL;
            break;
        case 517:
            r = _native.Engine.DEPTH_TEST_NOTEQUAL;
            break;
        case 514:
            r = _native.Engine.DEPTH_TEST_EQUAL;
            break;
        case 513:
            r = _native.Engine.DEPTH_TEST_LESS;
            break;
        case 515:
            r = _native.Engine.DEPTH_TEST_LEQUAL;
            break
        }
        this._currentDepthTest = r,
        this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(this._currentDepthTest),
        this._commandBufferEncoder.finishEncodingCommand()
    }
    ,
    e.prototype.setDepthWrite = function(t) {
        this._depthWrite = t,
        this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHWRITE),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(t)),
        this._commandBufferEncoder.finishEncodingCommand()
    }
    ,
    e.prototype.setColorWrite = function(t) {
        this._colorWrite = t,
        this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETCOLORWRITE),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(t)),
        this._commandBufferEncoder.finishEncodingCommand()
    }
    ,
    e.prototype.getColorWrite = function() {
        return this._colorWrite
    }
    ,
    e.prototype.applyStencil = function() {
        this._setStencil(this._stencilMask, this._getStencilOpFail(this._stencilOpStencilFail), this._getStencilDepthFail(this._stencilOpDepthFail), this._getStencilDepthPass(this._stencilOpStencilDepthPass), this._getStencilFunc(this._stencilFunc), this._stencilFuncRef)
    }
    ,
    e.prototype._setStencil = function(t, r, n, o, a, s) {
        this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTENCIL),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(t),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(r),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(n),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(o),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(a),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(s),
        this._commandBufferEncoder.finishEncodingCommand()
    }
    ,
    e.prototype.setStencilBuffer = function(t) {
        this._stencilTest = t,
        t ? this.applyStencil() : this._setStencil(255, _native.Engine.STENCIL_OP_FAIL_S_KEEP, _native.Engine.STENCIL_OP_FAIL_Z_KEEP, _native.Engine.STENCIL_OP_PASS_Z_KEEP, _native.Engine.STENCIL_TEST_ALWAYS, 0)
    }
    ,
    e.prototype.getStencilBuffer = function() {
        return this._stencilTest
    }
    ,
    e.prototype.getStencilOperationPass = function() {
        return this._stencilOpStencilDepthPass
    }
    ,
    e.prototype.setStencilOperationPass = function(t) {
        this._stencilOpStencilDepthPass = t,
        this.applyStencil()
    }
    ,
    e.prototype.setStencilMask = function(t) {
        this._stencilMask = t,
        this.applyStencil()
    }
    ,
    e.prototype.setStencilFunction = function(t) {
        this._stencilFunc = t,
        this.applyStencil()
    }
    ,
    e.prototype.setStencilFunctionReference = function(t) {
        this._stencilFuncRef = t,
        this.applyStencil()
    }
    ,
    e.prototype.setStencilFunctionMask = function(t) {
        this._stencilFuncMask = t
    }
    ,
    e.prototype.setStencilOperationFail = function(t) {
        this._stencilOpStencilFail = t,
        this.applyStencil()
    }
    ,
    e.prototype.setStencilOperationDepthFail = function(t) {
        this._stencilOpDepthFail = t,
        this.applyStencil()
    }
    ,
    e.prototype.getStencilMask = function() {
        return this._stencilMask
    }
    ,
    e.prototype.getStencilFunction = function() {
        return this._stencilFunc
    }
    ,
    e.prototype.getStencilFunctionReference = function() {
        return this._stencilFuncRef
    }
    ,
    e.prototype.getStencilFunctionMask = function() {
        return this._stencilFuncMask
    }
    ,
    e.prototype.getStencilOperationFail = function() {
        return this._stencilOpStencilFail
    }
    ,
    e.prototype.getStencilOperationDepthFail = function() {
        return this._stencilOpDepthFail
    }
    ,
    e.prototype.setAlphaConstants = function(t, r, n, o) {
        throw new Error("Setting alpha blend constant color not yet implemented.")
    }
    ,
    e.prototype.setAlphaMode = function(t, r) {
        r === void 0 && (r = !1),
        this._alphaMode !== t && (t = this._getNativeAlphaMode(t),
        this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETBLENDMODE),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(t),
        this._commandBufferEncoder.finishEncodingCommand(),
        r || this.setDepthWrite(t === 0),
        this._alphaMode = t)
    }
    ,
    e.prototype.getAlphaMode = function() {
        return this._alphaMode
    }
    ,
    e.prototype.setInt = function(t, r) {
        return t ? (this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINT),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(t),
        this._commandBufferEncoder.encodeCommandArgAsInt32(r),
        this._commandBufferEncoder.finishEncodingCommand(),
        !0) : !1
    }
    ,
    e.prototype.setIntArray = function(t, r) {
        return t ? (this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(t),
        this._commandBufferEncoder.encodeCommandArgAsInt32s(r),
        this._commandBufferEncoder.finishEncodingCommand(),
        !0) : !1
    }
    ,
    e.prototype.setIntArray2 = function(t, r) {
        return t ? (this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY2),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(t),
        this._commandBufferEncoder.encodeCommandArgAsInt32s(r),
        this._commandBufferEncoder.finishEncodingCommand(),
        !0) : !1
    }
    ,
    e.prototype.setIntArray3 = function(t, r) {
        return t ? (this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY3),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(t),
        this._commandBufferEncoder.encodeCommandArgAsInt32s(r),
        this._commandBufferEncoder.finishEncodingCommand(),
        !0) : !1
    }
    ,
    e.prototype.setIntArray4 = function(t, r) {
        return t ? (this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY4),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(t),
        this._commandBufferEncoder.encodeCommandArgAsInt32s(r),
        this._commandBufferEncoder.finishEncodingCommand(),
        !0) : !1
    }
    ,
    e.prototype.setFloatArray = function(t, r) {
        return t ? (this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(t),
        this._commandBufferEncoder.encodeCommandArgAsFloat32s(r),
        this._commandBufferEncoder.finishEncodingCommand(),
        !0) : !1
    }
    ,
    e.prototype.setFloatArray2 = function(t, r) {
        return t ? (this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY2),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(t),
        this._commandBufferEncoder.encodeCommandArgAsFloat32s(r),
        this._commandBufferEncoder.finishEncodingCommand(),
        !0) : !1
    }
    ,
    e.prototype.setFloatArray3 = function(t, r) {
        return t ? (this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY3),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(t),
        this._commandBufferEncoder.encodeCommandArgAsFloat32s(r),
        this._commandBufferEncoder.finishEncodingCommand(),
        !0) : !1
    }
    ,
    e.prototype.setFloatArray4 = function(t, r) {
        return t ? (this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY4),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(t),
        this._commandBufferEncoder.encodeCommandArgAsFloat32s(r),
        this._commandBufferEncoder.finishEncodingCommand(),
        !0) : !1
    }
    ,
    e.prototype.setArray = function(t, r) {
        return t ? this.setFloatArray(t, new Float32Array(r)) : !1
    }
    ,
    e.prototype.setArray2 = function(t, r) {
        return t ? (this.setFloatArray2(t, new Float32Array(r)),
        !0) : !1
    }
    ,
    e.prototype.setArray3 = function(t, r) {
        return t ? (this.setFloatArray3(t, new Float32Array(r)),
        !0) : !1
    }
    ,
    e.prototype.setArray4 = function(t, r) {
        return t ? (this.setFloatArray4(t, new Float32Array(r)),
        !0) : !1
    }
    ,
    e.prototype.setMatrices = function(t, r) {
        return t ? (this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRICES),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(t),
        this._commandBufferEncoder.encodeCommandArgAsFloat32s(r),
        this._commandBufferEncoder.finishEncodingCommand(),
        !0) : !1
    }
    ,
    e.prototype.setMatrix3x3 = function(t, r) {
        return t ? (this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX3X3),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(t),
        this._commandBufferEncoder.encodeCommandArgAsFloat32s(r),
        this._commandBufferEncoder.finishEncodingCommand(),
        !0) : !1
    }
    ,
    e.prototype.setMatrix2x2 = function(t, r) {
        return t ? (this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX2X2),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(t),
        this._commandBufferEncoder.encodeCommandArgAsFloat32s(r),
        this._commandBufferEncoder.finishEncodingCommand(),
        !0) : !1
    }
    ,
    e.prototype.setFloat = function(t, r) {
        return t ? (this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(t),
        this._commandBufferEncoder.encodeCommandArgAsFloat32(r),
        this._commandBufferEncoder.finishEncodingCommand(),
        !0) : !1
    }
    ,
    e.prototype.setFloat2 = function(t, r, n) {
        return t ? (this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT2),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(t),
        this._commandBufferEncoder.encodeCommandArgAsFloat32(r),
        this._commandBufferEncoder.encodeCommandArgAsFloat32(n),
        this._commandBufferEncoder.finishEncodingCommand(),
        !0) : !1
    }
    ,
    e.prototype.setFloat3 = function(t, r, n, o) {
        return t ? (this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT3),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(t),
        this._commandBufferEncoder.encodeCommandArgAsFloat32(r),
        this._commandBufferEncoder.encodeCommandArgAsFloat32(n),
        this._commandBufferEncoder.encodeCommandArgAsFloat32(o),
        this._commandBufferEncoder.finishEncodingCommand(),
        !0) : !1
    }
    ,
    e.prototype.setFloat4 = function(t, r, n, o, a) {
        return t ? (this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT4),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(t),
        this._commandBufferEncoder.encodeCommandArgAsFloat32(r),
        this._commandBufferEncoder.encodeCommandArgAsFloat32(n),
        this._commandBufferEncoder.encodeCommandArgAsFloat32(o),
        this._commandBufferEncoder.encodeCommandArgAsFloat32(a),
        this._commandBufferEncoder.finishEncodingCommand(),
        !0) : !1
    }
    ,
    e.prototype.setColor3 = function(t, r) {
        return t ? (this.setFloat3(t, r.r, r.g, r.b),
        !0) : !1
    }
    ,
    e.prototype.setColor4 = function(t, r, n) {
        return t ? (this.setFloat4(t, r.r, r.g, r.b, n),
        !0) : !1
    }
    ,
    e.prototype.wipeCaches = function(t) {
        this.preventCacheWipeBetweenFrames || (this.resetTextureCache(),
        this._currentEffect = null,
        t && (this._currentProgram = null,
        this._stencilStateComposer.reset(),
        this._depthCullingState.reset(),
        this._alphaState.reset()),
        this._cachedVertexBuffers = null,
        this._cachedIndexBuffer = null,
        this._cachedEffectForVertexBuffers = null)
    }
    ,
    e.prototype._createTexture = function() {
        return this._engine.createTexture()
    }
    ,
    e.prototype._deleteTexture = function(t) {
        t && this._engine.deleteTexture(t)
    }
    ,
    e.prototype.updateDynamicTexture = function(t, r, n, o, a) {
        if (!!t && !!t._hardwareTexture) {
            var s = r.getCanvasTexture()
              , l = t._hardwareTexture.underlyingResource;
            this._engine.copyTexture(l, s),
            t.isReady = !0
        }
    }
    ,
    e.prototype.createDynamicTexture = function(t, r, n, o) {
        return t = Math.max(t, 1),
        r = Math.max(r, 1),
        this.createRawTexture(new Uint8Array(t * r * 4), t, r, 5, !1, !1, o)
    }
    ,
    e.prototype.createVideoElement = function(t) {
        return this._camera ? this._camera.createVideo(t) : null
    }
    ,
    e.prototype.updateVideoTexture = function(t, r, n) {
        if (t && t._hardwareTexture && this._camera) {
            var o = t._hardwareTexture.underlyingResource;
            this._camera.updateVideoTexture(o, r, n)
        }
    }
    ,
    e.prototype.createRawTexture = function(t, r, n, o, a, s, l, u, c) {
        u === void 0 && (u = null),
        c === void 0 && (c = 0);
        var h = new InternalTexture(this,InternalTextureSource.Raw);
        if (h.format = o,
        h.generateMipMaps = a,
        h.samplingMode = l,
        h.invertY = s,
        h.baseWidth = r,
        h.baseHeight = n,
        h.width = h.baseWidth,
        h.height = h.baseHeight,
        h._compression = u,
        h.type = c,
        this.updateRawTexture(h, t, o, s, u, c),
        h._hardwareTexture) {
            var f = h._hardwareTexture.underlyingResource
              , d = this._getNativeSamplingMode(l);
            this._setTextureSampling(f, d)
        }
        return this._internalTexturesCache.push(h),
        h
    }
    ,
    e.prototype.updateRawTexture = function(t, r, n, o, a, s) {
        if (s === void 0 && (s = 0),
        !!t) {
            if (r && t._hardwareTexture) {
                var l = t._hardwareTexture.underlyingResource;
                this._engine.loadRawTexture(l, r, t.width, t.height, this._getNativeTextureFormat(n, s), t.generateMipMaps, t.invertY)
            }
            t.isReady = !0
        }
    }
    ,
    e.prototype.createTexture = function(t, r, n, o, a, s, l, u, c, h, f, d, _, g, m) {
        var v = this;
        a === void 0 && (a = 3),
        s === void 0 && (s = null),
        l === void 0 && (l = null),
        u === void 0 && (u = null),
        c === void 0 && (c = null),
        h === void 0 && (h = null),
        f === void 0 && (f = null),
        m === void 0 && (m = !1),
        t = t || "";
        var y = t.substr(0, 5) === "data:"
          , b = y && t.indexOf(";base64,") !== -1
          , T = c || new InternalTexture(this,InternalTextureSource.Url)
          , C = t;
        this._transformTextureUrl && !b && !c && !u && (t = this._transformTextureUrl(t));
        for (var A = t.lastIndexOf("."), S = f || (A > -1 ? t.substring(A).toLowerCase() : ""), P = null, R = 0, M = Engine._TextureLoaders; R < M.length; R++) {
            var x = M[R];
            if (x.canLoad(S)) {
                P = x;
                break
            }
        }
        o && o._addPendingData(T),
        T.url = t,
        T.generateMipMaps = !r,
        T.samplingMode = a,
        T.invertY = n,
        T._useSRGBBuffer = this._getUseSRGBBuffer(m, r),
        this.doNotHandleContextLost || (T._buffer = u);
        var I = null;
        s && !c && (I = T.onLoadedObservable.add(s)),
        c || this._internalTexturesCache.push(T);
        var w = function(D, F) {
            o && o._removePendingData(T),
            t === C ? (I && T.onLoadedObservable.remove(I),
            EngineStore.UseFallbackTexture && v.createTexture(EngineStore.FallbackTexture, r, T.invertY, o, a, null, l, u, T),
            l && l((D || "Unknown error") + (EngineStore.UseFallbackTexture ? " - Fallback texture was used" : ""), F)) : (Logger$2.Warn("Failed to load " + t + ", falling back to " + C),
            v.createTexture(C, r, T.invertY, o, a, s, l, u, T, h, f, d, _))
        };
        if (P)
            throw new Error("Loading textures from IInternalTextureLoader not yet implemented.");
        var O = function(D) {
            if (!T._hardwareTexture) {
                o && o._removePendingData(T);
                return
            }
            var F = T._hardwareTexture.underlyingResource;
            v._engine.loadTexture(F, D, !r, n, m, function() {
                T.baseWidth = v._engine.getTextureWidth(F),
                T.baseHeight = v._engine.getTextureHeight(F),
                T.width = T.baseWidth,
                T.height = T.baseHeight,
                T.isReady = !0;
                var V = v._getNativeSamplingMode(a);
                v._setTextureSampling(F, V),
                o && o._removePendingData(T),
                T.onLoadedObservable.notifyObservers(T),
                T.onLoadedObservable.clear()
            }, function() {
                throw new Error("Could not load a native texture.")
            })
        };
        if (y && u)
            if (u instanceof ArrayBuffer)
                O(new Uint8Array(u));
            else if (ArrayBuffer.isView(u))
                O(u);
            else if (typeof u == "string")
                O(new Uint8Array(Tools.DecodeBase64(u)));
            else
                throw new Error("Unsupported buffer type");
        else
            b ? O(new Uint8Array(Tools.DecodeBase64(t))) : this._loadFile(t, function(D) {
                return O(new Uint8Array(D))
            }, void 0, void 0, !0, function(D, F) {
                w("Unable to load " + (D && D.responseURL,
                F))
            });
        return T
    }
    ,
    e.prototype._createDepthStencilTexture = function(t, r, n) {
        var o = n
          , a = new InternalTexture(this,InternalTextureSource.DepthStencil)
          , s = t.width || t
          , l = t.height || t
          , u = this._engine.createFrameBuffer(a._hardwareTexture.underlyingResource, s, l, _native.Engine.TEXTURE_FORMAT_RGBA8, !1, !0, !1);
        return o._framebufferDepthStencil = u,
        a
    }
    ,
    e.prototype._releaseFramebufferObjects = function(t) {
        t && (this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEFRAMEBUFFER),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(t),
        this._commandBufferEncoder.finishEncodingCommand())
    }
    ,
    e.prototype.createImageBitmap = function(t, r) {
        var n = this;
        return new Promise(function(o, a) {
            if (Array.isArray(t)) {
                var s = t;
                if (s.length) {
                    var l = n._engine.createImageBitmap(s[0]);
                    if (l) {
                        o(l);
                        return
                    }
                }
            }
            a("Unsupported data for createImageBitmap.")
        }
        )
    }
    ,
    e.prototype.resizeImageBitmap = function(t, r, n) {
        return this._engine.resizeImageBitmap(t, r, n)
    }
    ,
    e.prototype.createCubeTexture = function(t, r, n, o, a, s, l, u, c, h, f, d, _, g) {
        var m = this;
        a === void 0 && (a = null),
        s === void 0 && (s = null),
        u === void 0 && (u = null),
        h === void 0 && (h = 0),
        f === void 0 && (f = 0),
        d === void 0 && (d = null),
        g === void 0 && (g = !1);
        var v = d || new InternalTexture(this,InternalTextureSource.Cube);
        v.isCube = !0,
        v.url = t,
        v.generateMipMaps = !o,
        v._lodGenerationScale = h,
        v._lodGenerationOffset = f,
        this._doNotHandleContextLost || (v._extension = u,
        v._files = n);
        var y = t.lastIndexOf(".")
          , b = u || (y > -1 ? t.substring(y).toLowerCase() : "");
        if (b === ".env") {
            var T = function(S) {
                var P = GetEnvInfo(S);
                v.width = P.width,
                v.height = P.width,
                UploadEnvSpherical(v, P);
                var R = P.specular;
                if (!R)
                    throw new Error("Nothing else parsed so far");
                v._lodGenerationScale = R.lodGenerationScale;
                var M = CreateImageDataArrayBufferViews(S, P);
                v.format = 5,
                v.type = 0,
                v.generateMipMaps = !0,
                v.getEngine().updateTextureSamplingMode(Texture.TRILINEAR_SAMPLINGMODE, v),
                v._isRGBD = !0,
                v.invertY = !0,
                m._engine.loadCubeTextureWithMips(v._hardwareTexture.underlyingResource, M, !1, g, function() {
                    v.isReady = !0,
                    a && a()
                }, function() {
                    throw new Error("Could not load a native cube texture.")
                })
            };
            if (n && n.length === 6)
                throw new Error("Multi-file loading not allowed on env files.");
            var C = function(S, P) {
                s && S && s(S.status + " " + S.statusText, P)
            };
            this._loadFile(t, function(S) {
                return T(new Uint8Array(S))
            }, void 0, void 0, !0, C)
        } else {
            if (!n || n.length !== 6)
                throw new Error("Cannot load cubemap because 6 files were not defined");
            var A = [n[0], n[3], n[1], n[4], n[2], n[5]];
            Promise.all(A.map(function(S) {
                return Tools.LoadFileAsync(S).then(function(P) {
                    return new Uint8Array(P)
                })
            })).then(function(S) {
                return new Promise(function(P, R) {
                    m._engine.loadCubeTexture(v._hardwareTexture.underlyingResource, S, !o, !0, g, P, R)
                }
                )
            }).then(function() {
                v.isReady = !0,
                a && a()
            }, function(S) {
                s && s("Failed to load cubemap: " + S.message, S)
            })
        }
        return this._internalTexturesCache.push(v),
        v
    }
    ,
    e.prototype._createHardwareRenderTargetWrapper = function(t, r, n) {
        var o = new NativeRenderTargetWrapper(t,r,n,this);
        return this._renderTargetWrapperCache.push(o),
        o
    }
    ,
    e.prototype.createRenderTargetTexture = function(t, r) {
        var n = this._createHardwareRenderTargetWrapper(!1, !1, t)
          , o = {};
        r !== void 0 && typeof r == "object" ? (o.generateMipMaps = r.generateMipMaps,
        o.generateDepthBuffer = r.generateDepthBuffer === void 0 ? !0 : r.generateDepthBuffer,
        o.generateStencilBuffer = o.generateDepthBuffer && r.generateStencilBuffer,
        o.type = r.type === void 0 ? 0 : r.type,
        o.samplingMode = r.samplingMode === void 0 ? 3 : r.samplingMode,
        o.format = r.format === void 0 ? 5 : r.format) : (o.generateMipMaps = r,
        o.generateDepthBuffer = !0,
        o.generateStencilBuffer = !1,
        o.type = 0,
        o.samplingMode = 3,
        o.format = 5),
        (o.type === 1 && !this._caps.textureFloatLinearFiltering || o.type === 2 && !this._caps.textureHalfFloatLinearFiltering) && (o.samplingMode = 1);
        var a = new InternalTexture(this,InternalTextureSource.RenderTarget)
          , s = t.width || t
          , l = t.height || t;
        o.type === 1 && !this._caps.textureFloat && (o.type = 0,
        Logger$2.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type"));
        var u = this._engine.createFrameBuffer(a._hardwareTexture.underlyingResource, s, l, this._getNativeTextureFormat(o.format, o.type), !!o.generateStencilBuffer, o.generateDepthBuffer, !!o.generateMipMaps);
        return n._framebuffer = u,
        n._generateDepthBuffer = o.generateDepthBuffer,
        n._generateStencilBuffer = !!o.generateStencilBuffer,
        a.baseWidth = s,
        a.baseHeight = l,
        a.width = s,
        a.height = l,
        a.isReady = !0,
        a.samples = 1,
        a.generateMipMaps = !!o.generateMipMaps,
        a.samplingMode = o.samplingMode,
        a.type = o.type,
        a.format = o.format,
        this._internalTexturesCache.push(a),
        n.setTextures(a),
        n
    }
    ,
    e.prototype.updateTextureSamplingMode = function(t, r) {
        if (r._hardwareTexture) {
            var n = this._getNativeSamplingMode(t);
            this._setTextureSampling(r._hardwareTexture.underlyingResource, n)
        }
        r.samplingMode = t
    }
    ,
    e.prototype.bindFramebuffer = function(t, r, n, o, a) {
        var s = t;
        if (r)
            throw new Error("Cuboid frame buffers are not yet supported in NativeEngine.");
        if (n || o)
            throw new Error("Required width/height for frame buffers not yet supported in NativeEngine.");
        s._framebufferDepthStencil ? this._bindUnboundFramebuffer(s._framebufferDepthStencil) : this._bindUnboundFramebuffer(s._framebuffer)
    }
    ,
    e.prototype.unBindFramebuffer = function(t, r, n) {
        n && n(),
        this._bindUnboundFramebuffer(null)
    }
    ,
    e.prototype.createDynamicVertexBuffer = function(t) {
        return this.createVertexBuffer(t, !0)
    }
    ,
    e.prototype.updateDynamicIndexBuffer = function(t, r, n) {
        n === void 0 && (n = 0);
        var o = t
          , a = this._normalizeIndexData(r);
        o.is32Bits = a.BYTES_PER_ELEMENT === 4,
        this._engine.updateDynamicIndexBuffer(o.nativeIndexBuffer, a.buffer, a.byteOffset, a.byteLength, n)
    }
    ,
    e.prototype.updateDynamicVertexBuffer = function(t, r, n, o) {
        var a = t
          , s = ArrayBuffer.isView(r) ? r : new Float32Array(r);
        this._engine.updateDynamicVertexBuffer(a.nativeVertexBuffer, s.buffer, s.byteOffset + (n != null ? n : 0), o != null ? o : s.byteLength)
    }
    ,
    e.prototype._setTexture = function(t, r, n, o) {
        o === void 0 && (o = !1);
        var a = this._boundUniforms[t];
        if (!a)
            return !1;
        if (!r)
            return this._boundTexturesCache[t] != null && (this._activeChannel = t,
            this._setTextureCore(a, null)),
            !1;
        if (r.video)
            this._activeChannel = t,
            r.update();
        else if (r.delayLoadState === 4)
            return r.delayLoad(),
            !1;
        var s;
        return o ? s = r.depthStencilTexture : r.isReady() ? s = r.getInternalTexture() : r.isCube ? s = this.emptyCubeTexture : r.is3D ? s = this.emptyTexture3D : r.is2DArray ? s = this.emptyTexture2DArray : s = this.emptyTexture,
        this._activeChannel = t,
        !s || !s._hardwareTexture ? !1 : (this._setTextureWrapMode(s._hardwareTexture.underlyingResource, this._getAddressMode(r.wrapU), this._getAddressMode(r.wrapV), this._getAddressMode(r.wrapR)),
        this._updateAnisotropicLevel(r),
        this._setTextureCore(a, s._hardwareTexture.underlyingResource),
        !0)
    }
    ,
    e.prototype._setTextureSampling = function(t, r) {
        this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURESAMPLING),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(t),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(r),
        this._commandBufferEncoder.finishEncodingCommand()
    }
    ,
    e.prototype._setTextureWrapMode = function(t, r, n, o) {
        this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREWRAPMODE),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(t),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(r),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(n),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(o),
        this._commandBufferEncoder.finishEncodingCommand()
    }
    ,
    e.prototype._setTextureCore = function(t, r) {
        this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURE),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(t),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(r),
        this._commandBufferEncoder.finishEncodingCommand()
    }
    ,
    e.prototype._updateAnisotropicLevel = function(t) {
        var r = t.getInternalTexture()
          , n = t.anisotropicFilteringLevel;
        !r || !r._hardwareTexture || r._cachedAnisotropicFilteringLevel !== n && (this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREANISOTROPICLEVEL),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(r._hardwareTexture.underlyingResource),
        this._commandBufferEncoder.encodeCommandArgAsUInt32(n),
        this._commandBufferEncoder.finishEncodingCommand(),
        r._cachedAnisotropicFilteringLevel = n)
    }
    ,
    e.prototype._getAddressMode = function(t) {
        switch (t) {
        case 1:
            return _native.Engine.ADDRESS_MODE_WRAP;
        case 0:
            return _native.Engine.ADDRESS_MODE_CLAMP;
        case 2:
            return _native.Engine.ADDRESS_MODE_MIRROR;
        default:
            throw new Error("Unexpected wrap mode: " + t + ".")
        }
    }
    ,
    e.prototype._bindTexture = function(t, r) {
        var n = this._boundUniforms[t];
        if (!!n && r && r._hardwareTexture) {
            var o = r._hardwareTexture.underlyingResource;
            this._setTextureCore(n, o)
        }
    }
    ,
    e.prototype._deleteBuffer = function(t) {
        t.nativeIndexBuffer && (this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEINDEXBUFFER),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(t.nativeIndexBuffer),
        this._commandBufferEncoder.finishEncodingCommand(),
        delete t.nativeIndexBuffer),
        t.nativeVertexBuffer && (this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXBUFFER),
        this._commandBufferEncoder.encodeCommandArgAsNativeData(t.nativeVertexBuffer),
        this._commandBufferEncoder.finishEncodingCommand(),
        delete t.nativeVertexBuffer)
    }
    ,
    e.prototype.createCanvas = function(t, r) {
        if (!_native.Canvas)
            throw new Error("Native Canvas plugin not available.");
        var n = new _native.Canvas;
        return n.width = t,
        n.height = r,
        n
    }
    ,
    e.prototype.createCanvasImage = function() {
        if (!_native.Canvas)
            throw new Error("Native Canvas plugin not available.");
        var t = new _native.Image;
        return t
    }
    ,
    e.prototype._uploadCompressedDataToTextureDirectly = function(t, r, n, o, a, s, l) {
        throw new Error("_uploadCompressedDataToTextureDirectly not implemented.")
    }
    ,
    e.prototype._uploadDataToTextureDirectly = function(t, r, n, o) {
        throw new Error("_uploadDataToTextureDirectly not implemented.")
    }
    ,
    e.prototype._uploadArrayBufferViewToTexture = function(t, r, n, o) {
        throw new Error("_uploadArrayBufferViewToTexture not implemented.")
    }
    ,
    e.prototype._uploadImageToTexture = function(t, r, n, o) {
        throw new Error("_uploadArrayBufferViewToTexture not implemented.")
    }
    ,
    e.prototype._getNativeSamplingMode = function(t) {
        switch (t) {
        case 1:
            return _native.Engine.TEXTURE_NEAREST_NEAREST;
        case 2:
            return _native.Engine.TEXTURE_LINEAR_LINEAR;
        case 3:
            return _native.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR;
        case 4:
            return _native.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
        case 5:
            return _native.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
        case 6:
            return _native.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
        case 7:
            return _native.Engine.TEXTURE_NEAREST_LINEAR;
        case 8:
            return _native.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR;
        case 9:
            return _native.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
        case 10:
            return _native.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
        case 11:
            return _native.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST;
        case 12:
            return _native.Engine.TEXTURE_LINEAR_NEAREST;
        default:
            throw new Error("Unsupported sampling mode: " + t + ".")
        }
    }
    ,
    e.prototype._getStencilFunc = function(t) {
        switch (t) {
        case 513:
            return _native.Engine.STENCIL_TEST_LESS;
        case 515:
            return _native.Engine.STENCIL_TEST_LEQUAL;
        case 514:
            return _native.Engine.STENCIL_TEST_EQUAL;
        case 518:
            return _native.Engine.STENCIL_TEST_GEQUAL;
        case 516:
            return _native.Engine.STENCIL_TEST_GREATER;
        case 517:
            return _native.Engine.STENCIL_TEST_NOTEQUAL;
        case 512:
            return _native.Engine.STENCIL_TEST_NEVER;
        case 519:
            return _native.Engine.STENCIL_TEST_ALWAYS;
        default:
            throw new Error("Unsupported stencil func mode: " + t + ".")
        }
    }
    ,
    e.prototype._getStencilOpFail = function(t) {
        switch (t) {
        case 7680:
            return _native.Engine.STENCIL_OP_FAIL_S_KEEP;
        case 0:
            return _native.Engine.STENCIL_OP_FAIL_S_ZERO;
        case 7681:
            return _native.Engine.STENCIL_OP_FAIL_S_REPLACE;
        case 7682:
            return _native.Engine.STENCIL_OP_FAIL_S_INCR;
        case 7683:
            return _native.Engine.STENCIL_OP_FAIL_S_DECR;
        case 5386:
            return _native.Engine.STENCIL_OP_FAIL_S_INVERT;
        case 34055:
            return _native.Engine.STENCIL_OP_FAIL_S_INCRSAT;
        case 34056:
            return _native.Engine.STENCIL_OP_FAIL_S_DECRSAT;
        default:
            throw new Error("Unsupported stencil OpFail mode: " + t + ".")
        }
    }
    ,
    e.prototype._getStencilDepthFail = function(t) {
        switch (t) {
        case 7680:
            return _native.Engine.STENCIL_OP_FAIL_Z_KEEP;
        case 0:
            return _native.Engine.STENCIL_OP_FAIL_Z_ZERO;
        case 7681:
            return _native.Engine.STENCIL_OP_FAIL_Z_REPLACE;
        case 7682:
            return _native.Engine.STENCIL_OP_FAIL_Z_INCR;
        case 7683:
            return _native.Engine.STENCIL_OP_FAIL_Z_DECR;
        case 5386:
            return _native.Engine.STENCIL_OP_FAIL_Z_INVERT;
        case 34055:
            return _native.Engine.STENCIL_OP_FAIL_Z_INCRSAT;
        case 34056:
            return _native.Engine.STENCIL_OP_FAIL_Z_DECRSAT;
        default:
            throw new Error("Unsupported stencil depthFail mode: " + t + ".")
        }
    }
    ,
    e.prototype._getStencilDepthPass = function(t) {
        switch (t) {
        case 7680:
            return _native.Engine.STENCIL_OP_PASS_Z_KEEP;
        case 0:
            return _native.Engine.STENCIL_OP_PASS_Z_ZERO;
        case 7681:
            return _native.Engine.STENCIL_OP_PASS_Z_REPLACE;
        case 7682:
            return _native.Engine.STENCIL_OP_PASS_Z_INCR;
        case 7683:
            return _native.Engine.STENCIL_OP_PASS_Z_DECR;
        case 5386:
            return _native.Engine.STENCIL_OP_PASS_Z_INVERT;
        case 34055:
            return _native.Engine.STENCIL_OP_PASS_Z_INCRSAT;
        case 34056:
            return _native.Engine.STENCIL_OP_PASS_Z_DECRSAT;
        default:
            throw new Error("Unsupported stencil opPass mode: " + t + ".")
        }
    }
    ,
    e.prototype._getNativeTextureFormat = function(t, r) {
        if (t == 4 && r == 0)
            return _native.Engine.TEXTURE_FORMAT_RGB8;
        if (t == 5 && r == 0)
            return _native.Engine.TEXTURE_FORMAT_RGBA8;
        if (t == 5 && r == 1)
            return _native.Engine.TEXTURE_FORMAT_RGBA32F;
        throw new Error("Unsupported texture format or type: format " + t + ", type " + r + ".")
    }
    ,
    e.prototype._getNativeAlphaMode = function(t) {
        switch (t) {
        case 0:
            return _native.Engine.ALPHA_DISABLE;
        case 1:
            return _native.Engine.ALPHA_ADD;
        case 2:
            return _native.Engine.ALPHA_COMBINE;
        case 3:
            return _native.Engine.ALPHA_SUBTRACT;
        case 4:
            return _native.Engine.ALPHA_MULTIPLY;
        case 5:
            return _native.Engine.ALPHA_MAXIMIZED;
        case 6:
            return _native.Engine.ALPHA_ONEONE;
        case 7:
            return _native.Engine.ALPHA_PREMULTIPLIED;
        case 8:
            return _native.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
        case 9:
            return _native.Engine.ALPHA_INTERPOLATE;
        case 10:
            return _native.Engine.ALPHA_SCREENMODE;
        default:
            throw new Error("Unsupported alpha mode: " + t + ".")
        }
    }
    ,
    e.prototype._getNativeAttribType = function(t) {
        switch (t) {
        case VertexBuffer.BYTE:
            return _native.Engine.ATTRIB_TYPE_INT8;
        case VertexBuffer.UNSIGNED_BYTE:
            return _native.Engine.ATTRIB_TYPE_UINT8;
        case VertexBuffer.SHORT:
            return _native.Engine.ATTRIB_TYPE_INT16;
        case VertexBuffer.UNSIGNED_SHORT:
            return _native.Engine.ATTRIB_TYPE_UINT16;
        case VertexBuffer.FLOAT:
            return _native.Engine.ATTRIB_TYPE_FLOAT;
        default:
            throw new Error("Unsupported attribute type: " + t + ".")
        }
    }
    ,
    e.prototype.getFontOffset = function(t) {
        var r = {
            ascent: 0,
            height: 0,
            descent: 0
        };
        return r
    }
    ,
    e.PROTOCOL_VERSION = 2,
    e
}(Engine);
NativeEngine._createNativeDataStream = function() {
    return _native.NativeDataStream.VALIDATION_ENABLED ? new ValidatedNativeDataStream : new NativeDataStream
}
;
var ValidatedNativeDataStream = function(i) {
    __extends(e, i);
    function e() {
        return i.call(this) || this
    }
    return e.prototype.writeUint32 = function(t) {
        i.prototype.writeUint32.call(this, _native.NativeDataStream.VALIDATION_UINT_32),
        i.prototype.writeUint32.call(this, t)
    }
    ,
    e.prototype.writeInt32 = function(t) {
        i.prototype.writeUint32.call(this, _native.NativeDataStream.VALIDATION_INT_32),
        i.prototype.writeInt32.call(this, t)
    }
    ,
    e.prototype.writeFloat32 = function(t) {
        i.prototype.writeUint32.call(this, _native.NativeDataStream.VALIDATION_FLOAT_32),
        i.prototype.writeFloat32.call(this, t)
    }
    ,
    e.prototype.writeUint32Array = function(t) {
        i.prototype.writeUint32.call(this, _native.NativeDataStream.VALIDATION_UINT_32_ARRAY),
        i.prototype.writeUint32Array.call(this, t)
    }
    ,
    e.prototype.writeInt32Array = function(t) {
        i.prototype.writeUint32.call(this, _native.NativeDataStream.VALIDATION_INT_32_ARRAY),
        i.prototype.writeInt32Array.call(this, t)
    }
    ,
    e.prototype.writeFloat32Array = function(t) {
        i.prototype.writeUint32.call(this, _native.NativeDataStream.VALIDATION_FLOAT_32_ARRAY),
        i.prototype.writeFloat32Array.call(this, t)
    }
    ,
    e.prototype.writeNativeData = function(t) {
        i.prototype.writeUint32.call(this, _native.NativeDataStream.VALIDATION_NATIVE_DATA),
        i.prototype.writeNativeData.call(this, t)
    }
    ,
    e.prototype.writeBoolean = function(t) {
        i.prototype.writeUint32.call(this, _native.NativeDataStream.VALIDATION_BOOLEAN),
        i.prototype.writeBoolean.call(this, t)
    }
    ,
    e
}(NativeDataStream), PowerPreference;
(function(i) {
    i.SRGB = "srgb"
}
)(PowerPreference || (PowerPreference = {}));
(function(i) {
    i.LowPower = "low-power",
    i.HighPerformance = "high-performance"
}
)(PowerPreference || (PowerPreference = {}));
var FeatureName;
(function(i) {
    i.DepthClipControl = "depth-clip-control",
    i.Depth24UnormStencil8 = "depth24unorm-stencil8",
    i.Depth32FloatStencil8 = "depth32float-stencil8",
    i.TextureCompressionBC = "texture-compression-bc",
    i.TextureCompressionETC2 = "texture-compression-etc2",
    i.TextureCompressionASTC = "texture-compression-astc",
    i.TimestampQuery = "timestamp-query",
    i.IndirectFirstInstance = "indirect-first-instance"
}
)(FeatureName || (FeatureName = {}));
var BufferUsage;
(function(i) {
    i[i.MapRead = 1] = "MapRead",
    i[i.MapWrite = 2] = "MapWrite",
    i[i.CopySrc = 4] = "CopySrc",
    i[i.CopyDst = 8] = "CopyDst",
    i[i.Index = 16] = "Index",
    i[i.Vertex = 32] = "Vertex",
    i[i.Uniform = 64] = "Uniform",
    i[i.Storage = 128] = "Storage",
    i[i.Indirect = 256] = "Indirect",
    i[i.QueryResolve = 512] = "QueryResolve"
}
)(BufferUsage || (BufferUsage = {}));
var MapMode;
(function(i) {
    i[i.Read = 1] = "Read",
    i[i.Write = 2] = "Write"
}
)(MapMode || (MapMode = {}));
var TextureDimension;
(function(i) {
    i.E1d = "1d",
    i.E2d = "2d",
    i.E3d = "3d"
}
)(TextureDimension || (TextureDimension = {}));
var TextureUsage;
(function(i) {
    i[i.CopySrc = 1] = "CopySrc",
    i[i.CopyDst = 2] = "CopyDst",
    i[i.TextureBinding = 4] = "TextureBinding",
    i[i.StorageBinding = 8] = "StorageBinding",
    i[i.RenderAttachment = 16] = "RenderAttachment"
}
)(TextureUsage || (TextureUsage = {}));
var TextureViewDimension;
(function(i) {
    i.E1d = "1d",
    i.E2d = "2d",
    i.E2dArray = "2d-array",
    i.Cube = "cube",
    i.CubeArray = "cube-array",
    i.E3d = "3d"
}
)(TextureViewDimension || (TextureViewDimension = {}));
var TextureAspect;
(function(i) {
    i.All = "all",
    i.StencilOnly = "stencil-only",
    i.DepthOnly = "depth-only"
}
)(TextureAspect || (TextureAspect = {}));
var TextureFormat;
(function(i) {
    i.R8Unorm = "r8unorm",
    i.R8Snorm = "r8snorm",
    i.R8Uint = "r8uint",
    i.R8Sint = "r8sint",
    i.R16Uint = "r16uint",
    i.R16Sint = "r16sint",
    i.R16Float = "r16float",
    i.RG8Unorm = "rg8unorm",
    i.RG8Snorm = "rg8snorm",
    i.RG8Uint = "rg8uint",
    i.RG8Sint = "rg8sint",
    i.R32Uint = "r32uint",
    i.R32Sint = "r32sint",
    i.R32Float = "r32float",
    i.RG16Uint = "rg16uint",
    i.RG16Sint = "rg16sint",
    i.RG16Float = "rg16float",
    i.RGBA8Unorm = "rgba8unorm",
    i.RGBA8UnormSRGB = "rgba8unorm-srgb",
    i.RGBA8Snorm = "rgba8snorm",
    i.RGBA8Uint = "rgba8uint",
    i.RGBA8Sint = "rgba8sint",
    i.BGRA8Unorm = "bgra8unorm",
    i.BGRA8UnormSRGB = "bgra8unorm-srgb",
    i.RGB9E5UFloat = "rgb9e5ufloat",
    i.RGB10A2Unorm = "rgb10a2unorm",
    i.RG11B10UFloat = "rg11b10ufloat",
    i.RG32Uint = "rg32uint",
    i.RG32Sint = "rg32sint",
    i.RG32Float = "rg32float",
    i.RGBA16Uint = "rgba16uint",
    i.RGBA16Sint = "rgba16sint",
    i.RGBA16Float = "rgba16float",
    i.RGBA32Uint = "rgba32uint",
    i.RGBA32Sint = "rgba32sint",
    i.RGBA32Float = "rgba32float",
    i.Stencil8 = "stencil8",
    i.Depth16Unorm = "depth16unorm",
    i.Depth24Plus = "depth24plus",
    i.Depth24PlusStencil8 = "depth24plus-stencil8",
    i.Depth32Float = "depth32float",
    i.BC1RGBAUnorm = "bc1-rgba-unorm",
    i.BC1RGBAUnormSRGB = "bc1-rgba-unorm-srgb",
    i.BC2RGBAUnorm = "bc2-rgba-unorm",
    i.BC2RGBAUnormSRGB = "bc2-rgba-unorm-srgb",
    i.BC3RGBAUnorm = "bc3-rgba-unorm",
    i.BC3RGBAUnormSRGB = "bc3-rgba-unorm-srgb",
    i.BC4RUnorm = "bc4-r-unorm",
    i.BC4RSnorm = "bc4-r-snorm",
    i.BC5RGUnorm = "bc5-rg-unorm",
    i.BC5RGSnorm = "bc5-rg-snorm",
    i.BC6HRGBUFloat = "bc6h-rgb-ufloat",
    i.BC6HRGBFloat = "bc6h-rgb-float",
    i.BC7RGBAUnorm = "bc7-rgba-unorm",
    i.BC7RGBAUnormSRGB = "bc7-rgba-unorm-srgb",
    i.ETC2RGB8Unorm = "etc2-rgb8unorm",
    i.ETC2RGB8UnormSRGB = "etc2-rgb8unorm-srgb",
    i.ETC2RGB8A1Unorm = "etc2-rgb8a1unorm",
    i.ETC2RGB8A1UnormSRGB = "etc2-rgb8a1unorm-srgb",
    i.ETC2RGBA8Unorm = "etc2-rgba8unorm",
    i.ETC2RGBA8UnormSRGB = "etc2-rgba8unorm-srgb",
    i.EACR11Unorm = "eac-r11unorm",
    i.EACR11Snorm = "eac-r11snorm",
    i.EACRG11Unorm = "eac-rg11unorm",
    i.EACRG11Snorm = "eac-rg11snorm",
    i.ASTC4x4Unorm = "astc-4x4-unorm",
    i.ASTC4x4UnormSRGB = "astc-4x4-unorm-srgb",
    i.ASTC5x4Unorm = "astc-5x4-unorm",
    i.ASTC5x4UnormSRGB = "astc-5x4-unorm-srgb",
    i.ASTC5x5Unorm = "astc-5x5-unorm",
    i.ASTC5x5UnormSRGB = "astc-5x5-unorm-srgb",
    i.ASTC6x5Unorm = "astc-6x5-unorm",
    i.ASTC6x5UnormSRGB = "astc-6x5-unorm-srgb",
    i.ASTC6x6Unorm = "astc-6x6-unorm",
    i.ASTC6x6UnormSRGB = "astc-6x6-unorm-srgb",
    i.ASTC8x5Unorm = "astc-8x5-unorm",
    i.ASTC8x5UnormSRGB = "astc-8x5-unorm-srgb",
    i.ASTC8x6Unorm = "astc-8x6-unorm",
    i.ASTC8x6UnormSRGB = "astc-8x6-unorm-srgb",
    i.ASTC8x8Unorm = "astc-8x8-unorm",
    i.ASTC8x8UnormSRGB = "astc-8x8-unorm-srgb",
    i.ASTC10x5Unorm = "astc-10x5-unorm",
    i.ASTC10x5UnormSRGB = "astc-10x5-unorm-srgb",
    i.ASTC10x6Unorm = "astc-10x6-unorm",
    i.ASTC10x6UnormSRGB = "astc-10x6-unorm-srgb",
    i.ASTC10x8Unorm = "astc-10x8-unorm",
    i.ASTC10x8UnormSRGB = "astc-10x8-unorm-srgb",
    i.ASTC10x10Unorm = "astc-10x10-unorm",
    i.ASTC10x10UnormSRGB = "astc-10x10-unorm-srgb",
    i.ASTC12x10Unorm = "astc-12x10-unorm",
    i.ASTC12x10UnormSRGB = "astc-12x10-unorm-srgb",
    i.ASTC12x12Unorm = "astc-12x12-unorm",
    i.ASTC12x12UnormSRGB = "astc-12x12-unorm-srgb",
    i.Depth24UnormStencil8 = "depth24unorm-stencil8",
    i.Depth32FloatStencil8 = "depth32float-stencil8"
}
)(TextureFormat || (TextureFormat = {}));
var AddressMode;
(function(i) {
    i.ClampToEdge = "clamp-to-edge",
    i.Repeat = "repeat",
    i.MirrorRepeat = "mirror-repeat"
}
)(AddressMode || (AddressMode = {}));
var FilterMode;
(function(i) {
    i.Nearest = "nearest",
    i.Linear = "linear"
}
)(FilterMode || (FilterMode = {}));
var CompareFunction;
(function(i) {
    i.Never = "never",
    i.Less = "less",
    i.Equal = "equal",
    i.LessEqual = "less-equal",
    i.Greater = "greater",
    i.NotEqual = "not-equal",
    i.GreaterEqual = "greater-equal",
    i.Always = "always"
}
)(CompareFunction || (CompareFunction = {}));
var ShaderStage;
(function(i) {
    i[i.Vertex = 1] = "Vertex",
    i[i.Fragment = 2] = "Fragment",
    i[i.Compute = 4] = "Compute"
}
)(ShaderStage || (ShaderStage = {}));
var BufferBindingType;
(function(i) {
    i.Uniform = "uniform",
    i.Storage = "storage",
    i.ReadOnlyStorage = "read-only-storage"
}
)(BufferBindingType || (BufferBindingType = {}));
var SamplerBindingType;
(function(i) {
    i.Filtering = "filtering",
    i.NonFiltering = "non-filtering",
    i.Comparison = "comparison"
}
)(SamplerBindingType || (SamplerBindingType = {}));
var TextureSampleType;
(function(i) {
    i.Float = "float",
    i.UnfilterableFloat = "unfilterable-float",
    i.Depth = "depth",
    i.Sint = "sint",
    i.Uint = "uint"
}
)(TextureSampleType || (TextureSampleType = {}));
var StorageTextureAccess;
(function(i) {
    i.WriteOnly = "write-only"
}
)(StorageTextureAccess || (StorageTextureAccess = {}));
var CompilationMessageType;
(function(i) {
    i.Error = "error",
    i.Warning = "warning",
    i.Info = "info"
}
)(CompilationMessageType || (CompilationMessageType = {}));
var PrimitiveTopology;
(function(i) {
    i.PointList = "point-list",
    i.LineList = "line-list",
    i.LineStrip = "line-strip",
    i.TriangleList = "triangle-list",
    i.TriangleStrip = "triangle-strip"
}
)(PrimitiveTopology || (PrimitiveTopology = {}));
var FrontFace;
(function(i) {
    i.CCW = "ccw",
    i.CW = "cw"
}
)(FrontFace || (FrontFace = {}));
var CullMode;
(function(i) {
    i.None = "none",
    i.Front = "front",
    i.Back = "back"
}
)(CullMode || (CullMode = {}));
var ColorWrite;
(function(i) {
    i[i.Red = 1] = "Red",
    i[i.Green = 2] = "Green",
    i[i.Blue = 4] = "Blue",
    i[i.Alpha = 8] = "Alpha",
    i[i.All = 15] = "All"
}
)(ColorWrite || (ColorWrite = {}));
var BlendFactor;
(function(i) {
    i.Zero = "zero",
    i.One = "one",
    i.Src = "src",
    i.OneMinusSrc = "one-minus-src",
    i.SrcAlpha = "src-alpha",
    i.OneMinusSrcAlpha = "one-minus-src-alpha",
    i.Dst = "dst",
    i.OneMinusDst = "one-minus-dst",
    i.DstAlpha = "dst-alpha",
    i.OneMinusDstAlpha = "one-minus-dst-alpha",
    i.SrcAlphaSaturated = "src-alpha-saturated",
    i.Constant = "constant",
    i.OneMinusConstant = "one-minus-constant"
}
)(BlendFactor || (BlendFactor = {}));
var BlendOperation;
(function(i) {
    i.Add = "add",
    i.Subtract = "subtract",
    i.ReverseSubtract = "reverse-subtract",
    i.Min = "min",
    i.Max = "max"
}
)(BlendOperation || (BlendOperation = {}));
var StencilOperation;
(function(i) {
    i.Keep = "keep",
    i.Zero = "zero",
    i.Replace = "replace",
    i.Invert = "invert",
    i.IncrementClamp = "increment-clamp",
    i.DecrementClamp = "decrement-clamp",
    i.IncrementWrap = "increment-wrap",
    i.DecrementWrap = "decrement-wrap"
}
)(StencilOperation || (StencilOperation = {}));
var IndexFormat;
(function(i) {
    i.Uint16 = "uint16",
    i.Uint32 = "uint32"
}
)(IndexFormat || (IndexFormat = {}));
var VertexFormat;
(function(i) {
    i.Uint8x2 = "uint8x2",
    i.Uint8x4 = "uint8x4",
    i.Sint8x2 = "sint8x2",
    i.Sint8x4 = "sint8x4",
    i.Unorm8x2 = "unorm8x2",
    i.Unorm8x4 = "unorm8x4",
    i.Snorm8x2 = "snorm8x2",
    i.Snorm8x4 = "snorm8x4",
    i.Uint16x2 = "uint16x2",
    i.Uint16x4 = "uint16x4",
    i.Sint16x2 = "sint16x2",
    i.Sint16x4 = "sint16x4",
    i.Unorm16x2 = "unorm16x2",
    i.Unorm16x4 = "unorm16x4",
    i.Snorm16x2 = "snorm16x2",
    i.Snorm16x4 = "snorm16x4",
    i.Float16x2 = "float16x2",
    i.Float16x4 = "float16x4",
    i.Float32 = "float32",
    i.Float32x2 = "float32x2",
    i.Float32x3 = "float32x3",
    i.Float32x4 = "float32x4",
    i.Uint32 = "uint32",
    i.Uint32x2 = "uint32x2",
    i.Uint32x3 = "uint32x3",
    i.Uint32x4 = "uint32x4",
    i.Sint32 = "sint32",
    i.Sint32x2 = "sint32x2",
    i.Sint32x3 = "sint32x3",
    i.Sint32x4 = "sint32x4"
}
)(VertexFormat || (VertexFormat = {}));
var InputStepMode;
(function(i) {
    i.Vertex = "vertex",
    i.Instance = "instance"
}
)(InputStepMode || (InputStepMode = {}));
var ComputePassTimestampLocation;
(function(i) {
    i.Beginning = "beginning",
    i.End = "end"
}
)(ComputePassTimestampLocation || (ComputePassTimestampLocation = {}));
var RenderPassTimestampLocation;
(function(i) {
    i.Beginning = "beginning",
    i.End = "end"
}
)(RenderPassTimestampLocation || (RenderPassTimestampLocation = {}));
var LoadOp;
(function(i) {
    i.Load = "load"
}
)(LoadOp || (LoadOp = {}));
var StoreOp;
(function(i) {
    i.Store = "store",
    i.Discard = "discard"
}
)(StoreOp || (StoreOp = {}));
var QueryType;
(function(i) {
    i.Occlusion = "occlusion",
    i.Timestamp = "timestamp"
}
)(QueryType || (QueryType = {}));
var CanvasCompositingAlphaMode;
(function(i) {
    i.Opaque = "opaque",
    i.Premultiplied = "premultiplied"
}
)(CanvasCompositingAlphaMode || (CanvasCompositingAlphaMode = {}));
var DeviceLostReason;
(function(i) {
    i.Destroyed = "destroyed"
}
)(DeviceLostReason || (DeviceLostReason = {}));
var ErrorFilter;
(function(i) {
    i.OutOfMemory = "out-of-memory",
    i.Validation = "validation"
}
)(ErrorFilter || (ErrorFilter = {}));
var WebGPUShaderProcessor = function() {
    function i() {
        this.shaderLanguage = ShaderLanguage.GLSL
    }
    return i.prototype._addUniformToLeftOverUBO = function(e, t, r) {
        var n, o = 0;
        n = this._getArraySize(e, t, r),
        e = n[0],
        t = n[1],
        o = n[2];
        for (var a = 0; a < this.webgpuProcessingContext.leftOverUniforms.length; a++)
            if (this.webgpuProcessingContext.leftOverUniforms[a].name === e)
                return;
        this.webgpuProcessingContext.leftOverUniforms.push({
            name: e,
            type: t,
            length: o
        })
    }
    ,
    i.prototype._buildLeftOverUBO = function() {
        if (!this.webgpuProcessingContext.leftOverUniforms.length)
            return "";
        var e = i.LeftOvertUBOName
          , t = this.webgpuProcessingContext.availableBuffers[e];
        return t || (t = {
            binding: this.webgpuProcessingContext.getNextFreeUBOBinding()
        },
        this.webgpuProcessingContext.availableBuffers[e] = t,
        this._addBufferBindingDescription(e, t, BufferBindingType.Uniform, !0),
        this._addBufferBindingDescription(e, t, BufferBindingType.Uniform, !1)),
        this._generateLeftOverUBOCode(e, t)
    }
    ,
    i.prototype._collectBindingNames = function() {
        for (var e = 0; e < this.webgpuProcessingContext.bindGroupLayoutEntries.length; e++) {
            var t = this.webgpuProcessingContext.bindGroupLayoutEntries[e];
            if (t === void 0) {
                this.webgpuProcessingContext.bindGroupLayoutEntries[e] = [];
                continue
            }
            for (var r = 0; r < t.length; r++) {
                var n = this.webgpuProcessingContext.bindGroupLayoutEntries[e][r]
                  , o = this.webgpuProcessingContext.bindGroupLayoutEntryInfo[e][n.binding].name
                  , a = this.webgpuProcessingContext.bindGroupLayoutEntryInfo[e][n.binding].nameInArrayOfTexture;
                n && (n.texture || n.externalTexture || n.storageTexture ? this.webgpuProcessingContext.textureNames.push(a) : n.sampler ? this.webgpuProcessingContext.samplerNames.push(o) : n.buffer && this.webgpuProcessingContext.bufferNames.push(o))
            }
        }
    }
    ,
    i.prototype._preCreateBindGroupEntries = function() {
        for (var e = this.webgpuProcessingContext.bindGroupEntries, t = 0; t < this.webgpuProcessingContext.bindGroupLayoutEntries.length; t++) {
            for (var r = this.webgpuProcessingContext.bindGroupLayoutEntries[t], n = [], o = 0; o < r.length; o++) {
                var a = this.webgpuProcessingContext.bindGroupLayoutEntries[t][o];
                a.sampler || a.texture || a.storageTexture || a.externalTexture ? n.push({
                    binding: a.binding,
                    resource: void 0
                }) : a.buffer && n.push({
                    binding: a.binding,
                    resource: {
                        buffer: void 0,
                        offset: 0,
                        size: 0
                    }
                })
            }
            e[t] = n
        }
    }
    ,
    i.prototype._addTextureBindingDescription = function(e, t, r, n, o, a) {
        var s = t.textures[r]
          , l = s.groupIndex
          , u = s.bindingIndex;
        if (this.webgpuProcessingContext.bindGroupLayoutEntries[l] || (this.webgpuProcessingContext.bindGroupLayoutEntries[l] = [],
        this.webgpuProcessingContext.bindGroupLayoutEntryInfo[l] = []),
        !this.webgpuProcessingContext.bindGroupLayoutEntryInfo[l][u]) {
            var c = void 0;
            n === null ? c = this.webgpuProcessingContext.bindGroupLayoutEntries[l].push({
                binding: u,
                visibility: 0,
                externalTexture: {}
            }) : o ? c = this.webgpuProcessingContext.bindGroupLayoutEntries[l].push({
                binding: u,
                visibility: 0,
                storageTexture: {
                    access: StorageTextureAccess.WriteOnly,
                    format: o,
                    viewDimension: n
                }
            }) : c = this.webgpuProcessingContext.bindGroupLayoutEntries[l].push({
                binding: u,
                visibility: 0,
                texture: {
                    sampleType: t.sampleType,
                    viewDimension: n,
                    multisampled: !1
                }
            });
            var h = t.isTextureArray ? e + r : e;
            this.webgpuProcessingContext.bindGroupLayoutEntryInfo[l][u] = {
                name: e,
                index: c - 1,
                nameInArrayOfTexture: h
            }
        }
        u = this.webgpuProcessingContext.bindGroupLayoutEntryInfo[l][u].index,
        a ? this.webgpuProcessingContext.bindGroupLayoutEntries[l][u].visibility |= ShaderStage.Vertex : this.webgpuProcessingContext.bindGroupLayoutEntries[l][u].visibility |= ShaderStage.Fragment
    }
    ,
    i.prototype._addSamplerBindingDescription = function(e, t, r) {
        var n = t.binding
          , o = n.groupIndex
          , a = n.bindingIndex;
        if (this.webgpuProcessingContext.bindGroupLayoutEntries[o] || (this.webgpuProcessingContext.bindGroupLayoutEntries[o] = [],
        this.webgpuProcessingContext.bindGroupLayoutEntryInfo[o] = []),
        !this.webgpuProcessingContext.bindGroupLayoutEntryInfo[o][a]) {
            var s = this.webgpuProcessingContext.bindGroupLayoutEntries[o].push({
                binding: a,
                visibility: 0,
                sampler: {
                    type: t.type
                }
            });
            this.webgpuProcessingContext.bindGroupLayoutEntryInfo[o][a] = {
                name: e,
                index: s - 1
            }
        }
        a = this.webgpuProcessingContext.bindGroupLayoutEntryInfo[o][a].index,
        r ? this.webgpuProcessingContext.bindGroupLayoutEntries[o][a].visibility |= ShaderStage.Vertex : this.webgpuProcessingContext.bindGroupLayoutEntries[o][a].visibility |= ShaderStage.Fragment
    }
    ,
    i.prototype._addBufferBindingDescription = function(e, t, r, n) {
        var o = t.binding
          , a = o.groupIndex
          , s = o.bindingIndex;
        if (this.webgpuProcessingContext.bindGroupLayoutEntries[a] || (this.webgpuProcessingContext.bindGroupLayoutEntries[a] = [],
        this.webgpuProcessingContext.bindGroupLayoutEntryInfo[a] = []),
        !this.webgpuProcessingContext.bindGroupLayoutEntryInfo[a][s]) {
            var l = this.webgpuProcessingContext.bindGroupLayoutEntries[a].push({
                binding: s,
                visibility: 0,
                buffer: {
                    type: r
                }
            });
            this.webgpuProcessingContext.bindGroupLayoutEntryInfo[a][s] = {
                name: e,
                index: l - 1
            }
        }
        s = this.webgpuProcessingContext.bindGroupLayoutEntryInfo[a][s].index,
        n ? this.webgpuProcessingContext.bindGroupLayoutEntries[a][s].visibility |= ShaderStage.Vertex : this.webgpuProcessingContext.bindGroupLayoutEntries[a][s].visibility |= ShaderStage.Fragment
    }
    ,
    i.AutoSamplerSuffix = "Sampler",
    i.LeftOvertUBOName = "LeftOver",
    i.UniformSizes = {
        bool: 1,
        int: 1,
        float: 1,
        vec2: 2,
        ivec2: 2,
        vec3: 3,
        ivec3: 3,
        vec4: 4,
        ivec4: 4,
        mat2: 4,
        mat3: 12,
        mat4: 16,
        i32: 1,
        u32: 1,
        f32: 1,
        mat2x2: 4,
        mat3x3: 12,
        mat4x4: 16
    },
    i._SamplerFunctionByWebGLSamplerType = {
        sampler2D: "sampler2D",
        sampler2DArray: "sampler2DArray",
        sampler2DShadow: "sampler2DShadow",
        sampler2DArrayShadow: "sampler2DArrayShadow",
        samplerCube: "samplerCube",
        sampler3D: "sampler3D"
    },
    i._TextureTypeByWebGLSamplerType = {
        sampler2D: "texture2D",
        sampler2DArray: "texture2DArray",
        sampler2DShadow: "texture2D",
        sampler2DArrayShadow: "texture2DArray",
        samplerCube: "textureCube",
        samplerCubeArray: "textureCubeArray",
        sampler3D: "texture3D"
    },
    i._GpuTextureViewDimensionByWebGPUTextureType = {
        textureCube: TextureViewDimension.Cube,
        textureCubeArray: TextureViewDimension.CubeArray,
        texture2D: TextureViewDimension.E2d,
        texture2DArray: TextureViewDimension.E2dArray,
        texture3D: TextureViewDimension.E3d
    },
    i._SamplerTypeByWebGLSamplerType = {
        sampler2DShadow: "samplerShadow",
        sampler2DArrayShadow: "samplerShadow"
    },
    i._IsComparisonSamplerByWebGPUSamplerType = {
        samplerShadow: !0,
        samplerArrayShadow: !0,
        sampler: !1
    },
    i
}()
  , WebGPUPipelineContext = function() {
    function i(e, t) {
        this._name = "unnamed",
        this.shaderProcessingContext = e,
        this._leftOverUniformsByName = {},
        this.engine = t
    }
    return Object.defineProperty(i.prototype, "isAsync", {
        get: function() {
            return !1
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "isReady", {
        get: function() {
            return !!this.stages
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype._handlesSpectorRebuildCallback = function(e) {}
    ,
    i.prototype._fillEffectInformation = function(e, t, r, n, o, a, s, l) {
        var u = this.engine;
        e._fragmentSourceCode = "",
        e._vertexSourceCode = "";
        var c = this.shaderProcessingContext.availableTextures, h;
        for (h = 0; h < o.length; h++) {
            var f = o[h]
              , d = c[o[h]];
            d == null || d == null ? (o.splice(h, 1),
            h--) : a[f] = h
        }
        for (var _ = 0, g = u.getAttributes(this, s); _ < g.length; _++) {
            var m = g[_];
            l.push(m)
        }
        this.buildUniformLayout();
        var v = []
          , y = [];
        for (h = 0; h < s.length; h++) {
            var b = l[h];
            b >= 0 && (v.push(s[h]),
            y.push(b))
        }
        this.shaderProcessingContext.attributeNamesFromEffect = v,
        this.shaderProcessingContext.attributeLocationsFromEffect = y
    }
    ,
    i.prototype.buildUniformLayout = function() {
        if (!!this.shaderProcessingContext.leftOverUniforms.length) {
            this.uniformBuffer = new UniformBuffer(this.engine,void 0,void 0,"leftOver-" + this._name);
            for (var e = 0, t = this.shaderProcessingContext.leftOverUniforms; e < t.length; e++) {
                var r = t[e]
                  , n = r.type.replace(/^(.*?)(<.*>)?$/, "$1")
                  , o = WebGPUShaderProcessor.UniformSizes[n];
                this.uniformBuffer.addUniform(r.name, o, r.length),
                this._leftOverUniformsByName[r.name] = r.type
            }
            this.uniformBuffer.create()
        }
    }
    ,
    i.prototype.dispose = function() {
        this.uniformBuffer && this.uniformBuffer.dispose()
    }
    ,
    i.prototype.setInt = function(e, t) {
        !this.uniformBuffer || !this._leftOverUniformsByName[e] || this.uniformBuffer.updateInt(e, t)
    }
    ,
    i.prototype.setInt2 = function(e, t, r) {
        !this.uniformBuffer || !this._leftOverUniformsByName[e] || this.uniformBuffer.updateInt2(e, t, r)
    }
    ,
    i.prototype.setInt3 = function(e, t, r, n) {
        !this.uniformBuffer || !this._leftOverUniformsByName[e] || this.uniformBuffer.updateInt3(e, t, r, n)
    }
    ,
    i.prototype.setInt4 = function(e, t, r, n, o) {
        !this.uniformBuffer || !this._leftOverUniformsByName[e] || this.uniformBuffer.updateInt4(e, t, r, n, o)
    }
    ,
    i.prototype.setIntArray = function(e, t) {
        !this.uniformBuffer || !this._leftOverUniformsByName[e] || this.uniformBuffer.updateIntArray(e, t)
    }
    ,
    i.prototype.setIntArray2 = function(e, t) {
        this.setIntArray(e, t)
    }
    ,
    i.prototype.setIntArray3 = function(e, t) {
        this.setIntArray(e, t)
    }
    ,
    i.prototype.setIntArray4 = function(e, t) {
        this.setIntArray(e, t)
    }
    ,
    i.prototype.setArray = function(e, t) {
        !this.uniformBuffer || !this._leftOverUniformsByName[e] || this.uniformBuffer.updateArray(e, t)
    }
    ,
    i.prototype.setArray2 = function(e, t) {
        this.setArray(e, t)
    }
    ,
    i.prototype.setArray3 = function(e, t) {
        this.setArray(e, t)
    }
    ,
    i.prototype.setArray4 = function(e, t) {
        this.setArray(e, t)
    }
    ,
    i.prototype.setMatrices = function(e, t) {
        !this.uniformBuffer || !this._leftOverUniformsByName[e] || this.uniformBuffer.updateMatrices(e, t)
    }
    ,
    i.prototype.setMatrix = function(e, t) {
        !this.uniformBuffer || !this._leftOverUniformsByName[e] || this.uniformBuffer.updateMatrix(e, t)
    }
    ,
    i.prototype.setMatrix3x3 = function(e, t) {
        !this.uniformBuffer || !this._leftOverUniformsByName[e] || this.uniformBuffer.updateMatrix3x3(e, t)
    }
    ,
    i.prototype.setMatrix2x2 = function(e, t) {
        !this.uniformBuffer || !this._leftOverUniformsByName[e] || this.uniformBuffer.updateMatrix2x2(e, t)
    }
    ,
    i.prototype.setFloat = function(e, t) {
        !this.uniformBuffer || !this._leftOverUniformsByName[e] || this.uniformBuffer.updateFloat(e, t)
    }
    ,
    i.prototype.setVector2 = function(e, t) {
        this.setFloat2(e, t.x, t.y)
    }
    ,
    i.prototype.setFloat2 = function(e, t, r) {
        !this.uniformBuffer || !this._leftOverUniformsByName[e] || this.uniformBuffer.updateFloat2(e, t, r)
    }
    ,
    i.prototype.setVector3 = function(e, t) {
        this.setFloat3(e, t.x, t.y, t.z)
    }
    ,
    i.prototype.setFloat3 = function(e, t, r, n) {
        !this.uniformBuffer || !this._leftOverUniformsByName[e] || this.uniformBuffer.updateFloat3(e, t, r, n)
    }
    ,
    i.prototype.setVector4 = function(e, t) {
        this.setFloat4(e, t.x, t.y, t.z, t.w)
    }
    ,
    i.prototype.setFloat4 = function(e, t, r, n, o) {
        !this.uniformBuffer || !this._leftOverUniformsByName[e] || this.uniformBuffer.updateFloat4(e, t, r, n, o)
    }
    ,
    i.prototype.setColor3 = function(e, t) {
        this.setFloat3(e, t.r, t.g, t.b)
    }
    ,
    i.prototype.setColor4 = function(e, t, r) {
        this.setFloat4(e, t.r, t.g, t.b, r)
    }
    ,
    i.prototype.setDirectColor4 = function(e, t) {
        this.setFloat4(e, t.r, t.g, t.b, t.a)
    }
    ,
    i.prototype._getVertexShaderCode = function() {
        var e;
        return (e = this.sources) === null || e === void 0 ? void 0 : e.vertex
    }
    ,
    i.prototype._getFragmentShaderCode = function() {
        var e;
        return (e = this.sources) === null || e === void 0 ? void 0 : e.fragment
    }
    ,
    i
}()
  , _maxGroups = 4
  , _maxBindingsPerGroup = 1 << 16
  , _typeToLocationSize = {
    mat2: 2,
    mat3: 3,
    mat4: 4,
    mat2x2: 2,
    mat3x3: 3,
    mat4x4: 4
}
  , WebGPUShaderProcessingContext = function() {
    function i(e) {
        this.shaderLanguage = e,
        this._attributeNextLocation = 0,
        this._varyingNextLocation = 0,
        this.freeGroupIndex = 0,
        this.freeBindingIndex = 0,
        this.availableVaryings = {},
        this.availableAttributes = {},
        this.availableBuffers = {},
        this.availableTextures = {},
        this.availableSamplers = {},
        this.orderedAttributes = [],
        this.bindGroupLayoutEntries = [],
        this.bindGroupLayoutEntryInfo = [],
        this.bindGroupEntries = [],
        this.bufferNames = [],
        this.textureNames = [],
        this.samplerNames = [],
        this.leftOverUniforms = [],
        this._findStartingGroupBinding()
    }
    return Object.defineProperty(i, "KnownUBOs", {
        get: function() {
            return i._SimplifiedKnownBindings ? i._SimplifiedKnownUBOs : i._KnownUBOs
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype._findStartingGroupBinding = function() {
        var e = i.KnownUBOs
          , t = [];
        for (var r in e) {
            var n = e[r].binding;
            n.groupIndex !== -1 && (t[n.groupIndex] === void 0 ? t[n.groupIndex] = n.bindingIndex : t[n.groupIndex] = Math.max(t[n.groupIndex], n.bindingIndex))
        }
        this.freeGroupIndex = t.length - 1,
        this.freeGroupIndex === 0 ? (this.freeGroupIndex++,
        this.freeBindingIndex = 0) : this.freeBindingIndex = t[t.length - 1] + 1
    }
    ,
    i.prototype.getAttributeNextLocation = function(e, t) {
        var r;
        t === void 0 && (t = 0);
        var n = this._attributeNextLocation;
        return this._attributeNextLocation += ((r = _typeToLocationSize[e]) !== null && r !== void 0 ? r : 1) * (t || 1),
        n
    }
    ,
    i.prototype.getVaryingNextLocation = function(e, t) {
        var r;
        t === void 0 && (t = 0);
        var n = this._varyingNextLocation;
        return this._varyingNextLocation += ((r = _typeToLocationSize[e]) !== null && r !== void 0 ? r : 1) * (t || 1),
        n
    }
    ,
    i.prototype.getNextFreeUBOBinding = function() {
        return this._getNextFreeBinding(1)
    }
    ,
    i.prototype._getNextFreeBinding = function(e) {
        if (this.freeBindingIndex > _maxBindingsPerGroup - e && (this.freeGroupIndex++,
        this.freeBindingIndex = 0),
        this.freeGroupIndex === _maxGroups)
            throw "Too many textures or UBOs have been declared and it is not supported in WebGPU.";
        var t = {
            groupIndex: this.freeGroupIndex,
            bindingIndex: this.freeBindingIndex
        };
        return this.freeBindingIndex += e,
        t
    }
    ,
    i._SimplifiedKnownBindings = !0,
    i._SimplifiedKnownUBOs = {
        Scene: {
            binding: {
                groupIndex: 0,
                bindingIndex: 0
            }
        },
        Light0: {
            binding: {
                groupIndex: -1,
                bindingIndex: -1
            }
        },
        Light1: {
            binding: {
                groupIndex: -1,
                bindingIndex: -1
            }
        },
        Light2: {
            binding: {
                groupIndex: -1,
                bindingIndex: -1
            }
        },
        Light3: {
            binding: {
                groupIndex: -1,
                bindingIndex: -1
            }
        },
        Light4: {
            binding: {
                groupIndex: -1,
                bindingIndex: -1
            }
        },
        Light5: {
            binding: {
                groupIndex: -1,
                bindingIndex: -1
            }
        },
        Light6: {
            binding: {
                groupIndex: -1,
                bindingIndex: -1
            }
        },
        Light7: {
            binding: {
                groupIndex: -1,
                bindingIndex: -1
            }
        },
        Light8: {
            binding: {
                groupIndex: -1,
                bindingIndex: -1
            }
        },
        Light9: {
            binding: {
                groupIndex: -1,
                bindingIndex: -1
            }
        },
        Light10: {
            binding: {
                groupIndex: -1,
                bindingIndex: -1
            }
        },
        Light11: {
            binding: {
                groupIndex: -1,
                bindingIndex: -1
            }
        },
        Light12: {
            binding: {
                groupIndex: -1,
                bindingIndex: -1
            }
        },
        Light13: {
            binding: {
                groupIndex: -1,
                bindingIndex: -1
            }
        },
        Light14: {
            binding: {
                groupIndex: -1,
                bindingIndex: -1
            }
        },
        Light15: {
            binding: {
                groupIndex: -1,
                bindingIndex: -1
            }
        },
        Light16: {
            binding: {
                groupIndex: -1,
                bindingIndex: -1
            }
        },
        Light17: {
            binding: {
                groupIndex: -1,
                bindingIndex: -1
            }
        },
        Light18: {
            binding: {
                groupIndex: -1,
                bindingIndex: -1
            }
        },
        Light19: {
            binding: {
                groupIndex: -1,
                bindingIndex: -1
            }
        },
        Light20: {
            binding: {
                groupIndex: -1,
                bindingIndex: -1
            }
        },
        Light21: {
            binding: {
                groupIndex: -1,
                bindingIndex: -1
            }
        },
        Light22: {
            binding: {
                groupIndex: -1,
                bindingIndex: -1
            }
        },
        Light23: {
            binding: {
                groupIndex: -1,
                bindingIndex: -1
            }
        },
        Light24: {
            binding: {
                groupIndex: -1,
                bindingIndex: -1
            }
        },
        Light25: {
            binding: {
                groupIndex: -1,
                bindingIndex: -1
            }
        },
        Light26: {
            binding: {
                groupIndex: -1,
                bindingIndex: -1
            }
        },
        Light27: {
            binding: {
                groupIndex: -1,
                bindingIndex: -1
            }
        },
        Light28: {
            binding: {
                groupIndex: -1,
                bindingIndex: -1
            }
        },
        Light29: {
            binding: {
                groupIndex: -1,
                bindingIndex: -1
            }
        },
        Light30: {
            binding: {
                groupIndex: -1,
                bindingIndex: -1
            }
        },
        Light31: {
            binding: {
                groupIndex: -1,
                bindingIndex: -1
            }
        },
        Material: {
            binding: {
                groupIndex: -1,
                bindingIndex: -1
            }
        },
        Mesh: {
            binding: {
                groupIndex: -1,
                bindingIndex: -1
            }
        }
    },
    i._KnownUBOs = {
        Scene: {
            binding: {
                groupIndex: 0,
                bindingIndex: 0
            }
        },
        Light0: {
            binding: {
                groupIndex: 1,
                bindingIndex: 0
            }
        },
        Light1: {
            binding: {
                groupIndex: 1,
                bindingIndex: 1
            }
        },
        Light2: {
            binding: {
                groupIndex: 1,
                bindingIndex: 2
            }
        },
        Light3: {
            binding: {
                groupIndex: 1,
                bindingIndex: 3
            }
        },
        Light4: {
            binding: {
                groupIndex: 1,
                bindingIndex: 4
            }
        },
        Light5: {
            binding: {
                groupIndex: 1,
                bindingIndex: 5
            }
        },
        Light6: {
            binding: {
                groupIndex: 1,
                bindingIndex: 6
            }
        },
        Light7: {
            binding: {
                groupIndex: 1,
                bindingIndex: 7
            }
        },
        Light8: {
            binding: {
                groupIndex: 1,
                bindingIndex: 8
            }
        },
        Light9: {
            binding: {
                groupIndex: 1,
                bindingIndex: 9
            }
        },
        Light10: {
            binding: {
                groupIndex: 1,
                bindingIndex: 10
            }
        },
        Light11: {
            binding: {
                groupIndex: 1,
                bindingIndex: 11
            }
        },
        Light12: {
            binding: {
                groupIndex: 1,
                bindingIndex: 12
            }
        },
        Light13: {
            binding: {
                groupIndex: 1,
                bindingIndex: 13
            }
        },
        Light14: {
            binding: {
                groupIndex: 1,
                bindingIndex: 14
            }
        },
        Light15: {
            binding: {
                groupIndex: 1,
                bindingIndex: 15
            }
        },
        Light16: {
            binding: {
                groupIndex: 1,
                bindingIndex: 16
            }
        },
        Light17: {
            binding: {
                groupIndex: 1,
                bindingIndex: 17
            }
        },
        Light18: {
            binding: {
                groupIndex: 1,
                bindingIndex: 18
            }
        },
        Light19: {
            binding: {
                groupIndex: 1,
                bindingIndex: 19
            }
        },
        Light20: {
            binding: {
                groupIndex: 1,
                bindingIndex: 20
            }
        },
        Light21: {
            binding: {
                groupIndex: 1,
                bindingIndex: 21
            }
        },
        Light22: {
            binding: {
                groupIndex: 1,
                bindingIndex: 22
            }
        },
        Light23: {
            binding: {
                groupIndex: 1,
                bindingIndex: 23
            }
        },
        Light24: {
            binding: {
                groupIndex: 1,
                bindingIndex: 24
            }
        },
        Light25: {
            binding: {
                groupIndex: 1,
                bindingIndex: 25
            }
        },
        Light26: {
            binding: {
                groupIndex: 1,
                bindingIndex: 26
            }
        },
        Light27: {
            binding: {
                groupIndex: 1,
                bindingIndex: 27
            }
        },
        Light28: {
            binding: {
                groupIndex: 1,
                bindingIndex: 28
            }
        },
        Light29: {
            binding: {
                groupIndex: 1,
                bindingIndex: 29
            }
        },
        Light30: {
            binding: {
                groupIndex: 1,
                bindingIndex: 30
            }
        },
        Light31: {
            binding: {
                groupIndex: 1,
                bindingIndex: 31
            }
        },
        Material: {
            binding: {
                groupIndex: 2,
                bindingIndex: 0
            }
        },
        Mesh: {
            binding: {
                groupIndex: 2,
                bindingIndex: 1
            }
        }
    },
    i
}()
  , WebGPUShaderProcessorGLSL = function(i) {
    __extends(e, i);
    function e() {
        var t = i !== null && i.apply(this, arguments) || this;
        return t._missingVaryings = [],
        t._textureArrayProcessing = [],
        t.shaderLanguage = ShaderLanguage.GLSL,
        t
    }
    return e.prototype._getArraySize = function(t, r, n) {
        var o = 0
          , a = t.indexOf("[")
          , s = t.indexOf("]");
        if (a > 0 && s > 0) {
            var l = t.substring(a + 1, s);
            o = +l,
            isNaN(o) && (o = +n[l.trim()]),
            t = t.substr(0, a)
        }
        return [t, r, o]
    }
    ,
    e.prototype.initializeShaders = function(t) {
        this.webgpuProcessingContext = t,
        this._missingVaryings.length = 0,
        this._textureArrayProcessing.length = 0
    }
    ,
    e.prototype.varyingProcessor = function(t, r, n, o) {
        this._preProcessors = n;
        var a = /\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm
          , s = a.exec(t);
        if (s != null) {
            var l = s[1], u = s[2], c;
            r ? (c = this.webgpuProcessingContext.availableVaryings[u],
            this._missingVaryings[c] = "",
            c === void 0 && Logger$2.Warn('Invalid fragment shader: The varying named "' + u + '" is not declared in the vertex shader! This declaration will be ignored.')) : (c = this.webgpuProcessingContext.getVaryingNextLocation(l, this._getArraySize(u, l, n)[2]),
            this.webgpuProcessingContext.availableVaryings[u] = c,
            this._missingVaryings[c] = "layout(location = " + c + ") in " + l + " " + u + ";"),
            t = t.replace(s[0], c === void 0 ? "" : "layout(location = " + c + ") " + (r ? "in" : "out") + " " + l + " " + u + ";")
        }
        return t
    }
    ,
    e.prototype.attributeProcessor = function(t, r, n) {
        this._preProcessors = r;
        var o = /\s*attribute\s+(\S+)\s+(\S+)\s*;/gm
          , a = o.exec(t);
        if (a != null) {
            var s = a[1]
              , l = a[2]
              , u = this.webgpuProcessingContext.getAttributeNextLocation(s, this._getArraySize(l, s, r)[2]);
            this.webgpuProcessingContext.availableAttributes[l] = u,
            this.webgpuProcessingContext.orderedAttributes[u] = l,
            t = t.replace(a[0], "layout(location = " + u + ") in " + s + " " + l + ";")
        }
        return t
    }
    ,
    e.prototype.uniformProcessor = function(t, r, n, o) {
        var a, s;
        this._preProcessors = n;
        var l = /\s*uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm
          , u = l.exec(t);
        if (u != null) {
            var c = u[1]
              , h = u[2];
            if (c.indexOf("sampler") === 0 || c.indexOf("sampler") === 1) {
                var f = 0;
                a = this._getArraySize(h, c, n),
                h = a[0],
                c = a[1],
                f = a[2];
                var d = this.webgpuProcessingContext.availableTextures[h];
                if (!d) {
                    d = {
                        autoBindSampler: !0,
                        isTextureArray: f > 0,
                        isStorageTexture: !1,
                        textures: [],
                        sampleType: TextureSampleType.Float
                    };
                    for (var _ = 0; _ < (f || 1); ++_)
                        d.textures.push(this.webgpuProcessingContext.getNextFreeUBOBinding())
                }
                var g = (s = WebGPUShaderProcessor._SamplerTypeByWebGLSamplerType[c]) !== null && s !== void 0 ? s : "sampler"
                  , m = !!WebGPUShaderProcessor._IsComparisonSamplerByWebGPUSamplerType[g]
                  , v = m ? SamplerBindingType.Comparison : SamplerBindingType.Filtering
                  , y = h + WebGPUShaderProcessor.AutoSamplerSuffix
                  , b = this.webgpuProcessingContext.availableSamplers[y];
                b || (b = {
                    binding: this.webgpuProcessingContext.getNextFreeUBOBinding(),
                    type: v
                });
                var T = c.charAt(0) === "u" ? "u" : c.charAt(0) === "i" ? "i" : "";
                T && (c = c.substr(1));
                var C = m ? TextureSampleType.Depth : T === "u" ? TextureSampleType.Uint : T === "i" ? TextureSampleType.Sint : TextureSampleType.Float;
                d.sampleType = C;
                var A = f > 0
                  , S = b.binding.groupIndex
                  , P = b.binding.bindingIndex
                  , R = WebGPUShaderProcessor._SamplerFunctionByWebGLSamplerType[c]
                  , M = WebGPUShaderProcessor._TextureTypeByWebGLSamplerType[c]
                  , x = WebGPUShaderProcessor._GpuTextureViewDimensionByWebGPUTextureType[M];
                if (!A)
                    f = 1,
                    t = "layout(set = " + S + ", binding = " + P + ") uniform " + T + g + " " + y + `;
                        layout(set = ` + d.textures[0].groupIndex + ", binding = " + d.textures[0].bindingIndex + ") uniform " + M + " " + h + `Texture;
                        #define ` + h + " " + T + R + "(" + h + "Texture, " + y + ")";
                else {
                    var I = [];
                    I.push("layout(set = " + S + ", binding = " + P + ") uniform " + T + g + " " + y + ";"),
                    t = `\r
`;
                    for (var _ = 0; _ < f; ++_) {
                        var w = d.textures[_].groupIndex
                          , O = d.textures[_].bindingIndex;
                        I.push("layout(set = " + w + ", binding = " + O + ") uniform " + M + " " + h + "Texture" + _ + ";"),
                        t += (_ > 0 ? `\r
` : "") + "#define " + h + _ + " " + T + R + "(" + h + "Texture" + _ + ", " + y + ")"
                    }
                    t = I.join(`\r
`) + t,
                    this._textureArrayProcessing.push(h)
                }
                this.webgpuProcessingContext.availableTextures[h] = d,
                this.webgpuProcessingContext.availableSamplers[y] = b,
                this._addSamplerBindingDescription(y, b, !r);
                for (var _ = 0; _ < f; ++_)
                    this._addTextureBindingDescription(h, d, _, x, null, !r)
            } else
                this._addUniformToLeftOverUBO(h, c, n),
                t = ""
        }
        return t
    }
    ,
    e.prototype.uniformBufferProcessor = function(t, r, n) {
        var o = /uniform\s+(\w+)/gm
          , a = o.exec(t);
        if (a != null) {
            var s = a[1]
              , l = this.webgpuProcessingContext.availableBuffers[s];
            if (!l) {
                var u = WebGPUShaderProcessingContext.KnownUBOs[s]
                  , c = void 0;
                u && u.binding.groupIndex !== -1 ? c = u.binding : c = this.webgpuProcessingContext.getNextFreeUBOBinding(),
                l = {
                    binding: c
                },
                this.webgpuProcessingContext.availableBuffers[s] = l
            }
            this._addBufferBindingDescription(s, l, BufferBindingType.Uniform, !r),
            t = t.replace("uniform", "layout(set = " + l.binding.groupIndex + ", binding = " + l.binding.bindingIndex + ") uniform")
        }
        return t
    }
    ,
    e.prototype.postProcessor = function(t, r, n, o, a) {
        var s = t.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1
          , l = /#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
        if (t = t.replace(l, ""),
        t = t.replace(/texture2D\s*\(/g, "texture("),
        n)
            t = t.replace(/texture2DLodEXT\s*\(/g, "textureLod("),
            t = t.replace(/textureCubeLodEXT\s*\(/g, "textureLod("),
            t = t.replace(/textureCube\s*\(/g, "texture("),
            t = t.replace(/gl_FragDepthEXT/g, "gl_FragDepth"),
            t = t.replace(/gl_FragColor/g, "glFragColor"),
            t = t.replace(/gl_FragData/g, "glFragData"),
            t = t.replace(/void\s+?main\s*\(/g, (s ? "" : `layout(location = 0) out vec4 glFragColor;
`) + "void main(");
        else {
            t = t.replace(/gl_InstanceID/g, "gl_InstanceIndex"),
            t = t.replace(/gl_VertexID/g, "gl_VertexIndex");
            var u = r.indexOf("#define MULTIVIEW") !== -1;
            if (u)
                return `#extension GL_OVR_multiview2 : require
layout (num_views = 2) in;
` + t
        }
        if (!n) {
            var c = t.lastIndexOf("}");
            t = t.substring(0, c),
            t += `gl_Position.y *= -1.;
`,
            a.isNDCHalfZRange || (t += `gl_Position.z = (gl_Position.z + gl_Position.w) / 2.0;
`),
            t += "}"
        }
        return t
    }
    ,
    e.prototype._applyTextureArrayProcessing = function(t, r) {
        for (var n = new RegExp(r + "\\s*\\[(.+)?\\]","gm"), o = n.exec(t); o != null; ) {
            var a = o[1]
              , s = +a;
            this._preProcessors && isNaN(s) && (s = +this._preProcessors[a.trim()]),
            t = t.replace(o[0], r + s),
            o = n.exec(t)
        }
        return t
    }
    ,
    e.prototype._generateLeftOverUBOCode = function(t, r) {
        for (var n = "layout(set = " + r.binding.groupIndex + ", binding = " + r.binding.bindingIndex + ") uniform " + t + ` {
    `, o = 0, a = this.webgpuProcessingContext.leftOverUniforms; o < a.length; o++) {
            var s = a[o];
            s.length > 0 ? n += "    " + s.type + " " + s.name + "[" + s.length + `];
` : n += "    " + s.type + " " + s.name + `;
`
        }
        return n += `};

`,
        n
    }
    ,
    e.prototype.finalizeShaders = function(t, r, n) {
        for (var o = 0; o < this._textureArrayProcessing.length; ++o) {
            var a = this._textureArrayProcessing[o];
            t = this._applyTextureArrayProcessing(t, a),
            r = this._applyTextureArrayProcessing(r, a)
        }
        for (var o = 0; o < this._missingVaryings.length; ++o) {
            var s = this._missingVaryings[o];
            s && s.length > 0 && (r = s + `
` + r)
        }
        var l = this._buildLeftOverUBO();
        return t = l + t,
        r = l + r,
        this._collectBindingNames(),
        this._preCreateBindGroupEntries(),
        this._preProcessors = null,
        {
            vertexCode: t,
            fragmentCode: r
        }
    }
    ,
    e
}(WebGPUShaderProcessor)
  , name$h = "bonesDeclaration"
  , shader$h = `#if NUM_BONE_INFLUENCERS>0
attribute matricesIndices : vec4<f32>;
attribute matricesWeights : vec4<f32>;
#if NUM_BONE_INFLUENCERS>4
attribute matricesIndicesExtra : vec4<f32>;
attribute matricesWeightsExtra : vec4<f32>;
#endif
#ifndef BAKED_VERTEX_ANIMATION_TEXTURE
#ifdef BONETEXTURE
var boneSampler : texture_2d<f32>;
uniform boneTextureWidth : f32;
#else
uniform mBones : array<mat4x4,BonesPerMesh>;
#ifdef BONES_VELOCITY_ENABLED
uniform mPreviousBones : array<mat4x4,BonesPerMesh>;
#endif
#endif
#ifdef BONETEXTURE
fn readMatrixFromRawSampler(smp : texture_2d<f32>,index : f32) -> mat4x4<f32>
{
let offset=i32(index)*4;
let m0=textureLoad(smp,vec2<i32>(offset+0,0),0);
let m1=textureLoad(smp,vec2<i32>(offset+1,0),0);
let m2=textureLoad(smp,vec2<i32>(offset+2,0),0);
let m3=textureLoad(smp,vec2<i32>(offset+3,0),0);
return mat4x4<f32>(m0,m1,m2,m3);
}
#endif
#endif
#endif`;
ShaderStore.IncludesShadersStoreWGSL[name$h] = shader$h;
var name$g = "bonesVertex"
  , shader$g = `#ifndef BAKED_VERTEX_ANIMATION_TEXTURE
#if NUM_BONE_INFLUENCERS>0
var influence : mat4x4<f32>;
#ifdef BONETEXTURE
influence=readMatrixFromRawSampler(boneSampler,matricesIndices[0])*matricesWeights[0];
#if NUM_BONE_INFLUENCERS>1
influence=influence+readMatrixFromRawSampler(boneSampler,matricesIndices[1])*matricesWeights[1];
#endif
#if NUM_BONE_INFLUENCERS>2
influence=influence+readMatrixFromRawSampler(boneSampler,matricesIndices[2])*matricesWeights[2];
#endif
#if NUM_BONE_INFLUENCERS>3
influence=influence+readMatrixFromRawSampler(boneSampler,matricesIndices[3])*matricesWeights[3];
#endif
#if NUM_BONE_INFLUENCERS>4
influence=influence+readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[0])*matricesWeightsExtra[0];
#endif
#if NUM_BONE_INFLUENCERS>5
influence=influence+readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[1])*matricesWeightsExtra[1];
#endif
#if NUM_BONE_INFLUENCERS>6
influence=influence+readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[2])*matricesWeightsExtra[2];
#endif
#if NUM_BONE_INFLUENCERS>7
influence=influence+readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[3])*matricesWeightsExtra[3];
#endif
#else
influence=uniforms.mBones[int(matricesIndices[0])]*matricesWeights[0];
#if NUM_BONE_INFLUENCERS>1
influence=influence+uniforms.mBones[int(matricesIndices[1])]*matricesWeights[1];
#endif
#if NUM_BONE_INFLUENCERS>2
influence=influence+uniforms.mBones[int(matricesIndices[2])]*matricesWeights[2];
#endif
#if NUM_BONE_INFLUENCERS>3
influence=influence+uniforms.mBones[int(matricesIndices[3])]*matricesWeights[3];
#endif
#if NUM_BONE_INFLUENCERS>4
influence=influence+uniforms.mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];
#endif
#if NUM_BONE_INFLUENCERS>5
influence=influence+uniforms.mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];
#endif
#if NUM_BONE_INFLUENCERS>6
influence=influence+uniforms.mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];
#endif
#if NUM_BONE_INFLUENCERS>7
influence=influence+uniforms.mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];
#endif
#endif
finalWorld=finalWorld*influence;
#endif
#endif`;
ShaderStore.IncludesShadersStoreWGSL[name$g] = shader$g;
var name$f = "bakedVertexAnimationDeclaration"
  , shader$f = `#ifdef BAKED_VERTEX_ANIMATION_TEXTURE
uniform bakedVertexAnimationTime: f32;
uniform bakedVertexAnimationTextureSizeInverted: vec2<f32>;
uniform bakedVertexAnimationSettings: vec4<f32>;
var bakedVertexAnimationTexture : texture_2d<f32>;
#ifdef INSTANCES
attribute bakedVertexAnimationSettingsInstanced : vec4<f32>;
attribute bakedVertexAnimationTimeInstanced : f32;
#endif
fn readMatrixFromRawSamplerVAT(smp : texture_2d<f32>,index : f32,frame : f32) -> mat4x4<f32>
{
let offset=i32(index)*4;
let frameUV=i32(frame);
let m0=textureLoad(smp,vec2<i32>(offset+0,frameUV),0);
let m1=textureLoad(smp,vec2<i32>(offset+1,frameUV),0);
let m2=textureLoad(smp,vec2<i32>(offset+2,frameUV),0);
let m3=textureLoad(smp,vec2<i32>(offset+3,frameUV),0);
return mat4x4<f32>(m0,m1,m2,m3);
}
#endif`;
ShaderStore.IncludesShadersStoreWGSL[name$f] = shader$f;
var name$e = "bakedVertexAnimation"
  , shader$e = `#ifdef BAKED_VERTEX_ANIMATION_TEXTURE
{

#ifdef INSTANCES
let VATStartFrame: f32=bakedVertexAnimationSettingsInstanced.x;
let VATEndFrame: f32=bakedVertexAnimationSettingsInstanced.y;
let VATOffsetFrame: f32=bakedVertexAnimationSettingsInstanced.z;
let VATSpeed: f32=bakedVertexAnimationSettingsInstanced.w;
let time: f32=bakedVertexAnimationTimeInstanced*VATSpeed/totalFrames;
#else
let VATStartFrame: f32=uniforms.bakedVertexAnimationSettings.x;
let VATEndFrame: f32=uniforms.bakedVertexAnimationSettings.y;
let VATOffsetFrame: f32=uniforms.bakedVertexAnimationSettings.z;
let VATSpeed: f32=uniforms.bakedVertexAnimationSettings.w;
let time: f32=uniforms.bakedVertexAnimationTime*VATSpeed/totalFrames;
#endif
let totalFrames: f32=VATEndFrame-VATStartFrame+1.0;

let frameCorrection: f32=select(1.0,0.0,time<1.0);
let numOfFrames: f32=totalFrames-frameCorrection;
var VATFrameNum: f32=fract(time)*numOfFrames;
VATFrameNum=(VATFrameNum+VATOffsetFrame) % numOfFrames;
VATFrameNum=floor(VATFrameNum);
VATFrameNum=VATFrameNum+VATStartFrame+frameCorrection;
var VATInfluence : mat4x4<f32>;
VATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[0],VATFrameNum)*matricesWeights[0];
#if NUM_BONE_INFLUENCERS>1
VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[1],VATFrameNum)*matricesWeights[1];
#endif
#if NUM_BONE_INFLUENCERS>2
VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[2],VATFrameNum)*matricesWeights[2];
#endif
#if NUM_BONE_INFLUENCERS>3
VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[3],VATFrameNum)*matricesWeights[3];
#endif
#if NUM_BONE_INFLUENCERS>4
VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[0],VATFrameNum)*matricesWeightsExtra[0];
#endif
#if NUM_BONE_INFLUENCERS>5
VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[1],VATFrameNum)*matricesWeightsExtra[1];
#endif
#if NUM_BONE_INFLUENCERS>6
VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[2],VATFrameNum)*matricesWeightsExtra[2];
#endif
#if NUM_BONE_INFLUENCERS>7
VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[3],VATFrameNum)*matricesWeightsExtra[3];
#endif
finalWorld=finalWorld*VATInfluence;
}
#endif`;
ShaderStore.IncludesShadersStoreWGSL[name$e] = shader$e;
var name$d = "clipPlaneFragment"
  , shader$d = `#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)


if (false) {}
#endif
#ifdef CLIPPLANE
elseif (fClipDistance>0.0)
{
discard;
}
#endif
#ifdef CLIPPLANE2
elseif (fClipDistance2>0.0)
{
discard;
}
#endif
#ifdef CLIPPLANE3
elseif (fClipDistance3>0.0)
{
discard;
}
#endif
#ifdef CLIPPLANE4
elseif (fClipDistance4>0.0)
{
discard;
}
#endif
#ifdef CLIPPLANE5
elseif (fClipDistance5>0.0)
{
discard;
}
#endif
#ifdef CLIPPLANE6
elseif (fClipDistance6>0.0)
{
discard;
}
#endif`;
ShaderStore.IncludesShadersStoreWGSL[name$d] = shader$d;
var name$c = "clipPlaneFragmentDeclaration"
  , shader$c = `#ifdef CLIPPLANE
varying fClipDistance: f32;
#endif
#ifdef CLIPPLANE2
varying fClipDistance2: f32;
#endif
#ifdef CLIPPLANE3
varying fClipDistance3: f32;
#endif
#ifdef CLIPPLANE4
varying fClipDistance4: f32;
#endif
#ifdef CLIPPLANE5
varying fClipDistance5: f32;
#endif
#ifdef CLIPPLANE6
varying fClipDistance6: f32;
#endif`;
ShaderStore.IncludesShadersStoreWGSL[name$c] = shader$c;
var name$b = "clipPlaneVertex"
  , shader$b = `#ifdef CLIPPLANE
fClipDistance=dot(worldPos,uniforms.vClipPlane);
#endif
#ifdef CLIPPLANE2
fClipDistance2=dot(worldPos,uniforms.vClipPlane2);
#endif
#ifdef CLIPPLANE3
fClipDistance3=dot(worldPos,uniforms.vClipPlane3);
#endif
#ifdef CLIPPLANE4
fClipDistance4=dot(worldPos,uniforms.vClipPlane4);
#endif
#ifdef CLIPPLANE5
fClipDistance5=dot(worldPos,uniforms.vClipPlane5);
#endif
#ifdef CLIPPLANE6
fClipDistance6=dot(worldPos,uniforms.vClipPlane6);
#endif`;
ShaderStore.IncludesShadersStoreWGSL[name$b] = shader$b;
var name$a = "clipPlaneVertexDeclaration"
  , shader$a = `#ifdef CLIPPLANE
uniform vClipPlane: vec4<f32>;
varying fClipDistance: f32;
#endif
#ifdef CLIPPLANE2
uniform vClipPlane2: vec4<f32>;
varying fClipDistance2: f32;
#endif
#ifdef CLIPPLANE3
uniform vClipPlane3: vec4<f32>;
varying fClipDistance3: f32;
#endif
#ifdef CLIPPLANE4
uniform vClipPlane4: vec4<f32>;
varying fClipDistance4: f32;
#endif
#ifdef CLIPPLANE5
uniform vClipPlane5: vec4<f32>;
varying fClipDistance5: f32;
#endif
#ifdef CLIPPLANE6
uniform vClipPlane6: vec4<f32>;
varying fClipDistance6: f32;
#endif`;
ShaderStore.IncludesShadersStoreWGSL[name$a] = shader$a;
var name$9 = "instancesDeclaration"
  , shader$9 = `#ifdef INSTANCES
attribute world0 : vec4<f32>;
attribute world1 : vec4<f32>;
attribute world2 : vec4<f32>;
attribute world3 : vec4<f32>;
#if defined(THIN_INSTANCES) && !defined(WORLD_UBO)
uniform world : mat4x4<f32>;
#endif
#if defined(VELOCITY) || defined(PREPASS_VELOCITY)
attribute previousWorld0 : vec4<f32>;
attribute previousWorld1 : vec4<f32>;
attribute previousWorld2 : vec4<f32>;
attribute previousWorld3 : vec4<f32>;
#ifdef THIN_INSTANCES
uniform previousWorld : mat4x4<f32>;
#endif
#endif
#else
#if !defined(WORLD_UBO)
uniform world : mat4x4<f32>;
#endif
#if defined(VELOCITY) || defined(PREPASS_VELOCITY)
uniform previousWorld : mat4x4<f32>;
#endif
#endif`;
ShaderStore.IncludesShadersStoreWGSL[name$9] = shader$9;
var name$8 = "instancesVertex"
  , shader$8 = `#ifdef INSTANCES
var finalWorld=mat4x4<f32>(world0,world1,world2,world3);
#if defined(PREPASS_VELOCITY) || defined(VELOCITY)
var finalPreviousWorld=mat4x4<f32>(previousWorld0,previousWorld1,previousWorld2,previousWorld3);
#endif
#ifdef THIN_INSTANCES
#if !defined(WORLD_UBO)
finalWorld=uniforms.world*finalWorld;
#else
finalWorld=mesh.world*finalWorld;
#endif
#if defined(PREPASS_VELOCITY) || defined(VELOCITY)
finalPreviousWorld=previousWorld*finalPreviousWorld;
#endif
#endif
#else
#if !defined(WORLD_UBO)
var finalWorld=uniforms.world;
#else
var finalWorld=mesh.world;
#endif
#if defined(PREPASS_VELOCITY) || defined(VELOCITY)
var finalPreviousWorld=previousWorld;
#endif
#endif`;
ShaderStore.IncludesShadersStoreWGSL[name$8] = shader$8;
var name$7 = "meshUboDeclaration"
  , shader$7 = `[[block]]
struct Mesh {
world : mat4x4<f32>;
visibility : f32;
};
var<uniform> mesh : Mesh;
#define WORLD_UBO
`;
ShaderStore.IncludesShadersStoreWGSL[name$7] = shader$7;
var name$6 = "morphTargetsVertex"
  , shader$6 = `#ifdef MORPHTARGETS
#ifdef MORPHTARGETS_TEXTURE
vertexID=f32(gl_VertexID)*uniforms.morphTargetTextureInfo.x;
positionUpdated=positionUpdated+(readVector3FromRawSampler({X},vertexID)-position)*uniforms.morphTargetInfluences[{X}];
vertexID=vertexID+1.0;
#ifdef MORPHTARGETS_NORMAL
normalUpdated=normalUpdated+(readVector3FromRawSampler({X},vertexID)-normal)*uniforms.morphTargetInfluences[{X}];
vertexID=vertexID+1.0;
#endif
#ifdef MORPHTARGETS_UV
uvUpdated=uvUpdated+(readVector3FromRawSampler({X},vertexID).xy-uv)*uniforms.morphTargetInfluences[{X}];
vertexID=vertexID+1.0;
#endif
#ifdef MORPHTARGETS_TANGENT
tangentUpdated.xyz=tangentUpdated.xyz+(readVector3FromRawSampler({X},vertexID)-tangent.xyz)*uniforms.morphTargetInfluences[{X}];
#endif
#else
positionUpdated=positionUpdated+(position{X}-position)*uniforms.morphTargetInfluences[{X}];
#ifdef MORPHTARGETS_NORMAL
normalUpdated+=(normal{X}-normal)*uniforms.morphTargetInfluences[{X}];
#endif
#ifdef MORPHTARGETS_TANGENT
tangentUpdated.xyz=tangentUpdated.xyz+(tangent{X}-tangent.xyz)*uniforms.morphTargetInfluences[{X}];
#endif
#ifdef MORPHTARGETS_UV
uvUpdated=uvUpdated+(uv_{X}-uv)*uniforms.morphTargetInfluences[{X}];
#endif
#endif
#endif`;
ShaderStore.IncludesShadersStoreWGSL[name$6] = shader$6;
var name$5 = "morphTargetsVertexDeclaration"
  , shader$5 = `#ifdef MORPHTARGETS
#ifndef MORPHTARGETS_TEXTURE
attribute position{X} : vec3<f32>;
#ifdef MORPHTARGETS_NORMAL
attribute normal{X} : vec3<f32>;
#endif
#ifdef MORPHTARGETS_TANGENT
attribute tangent{X} : vec3<f32>;
#endif
#ifdef MORPHTARGETS_UV
attribute uv_{X} : vec2<f32>;
#endif
#endif
#endif`;
ShaderStore.IncludesShadersStoreWGSL[name$5] = shader$5;
var name$4 = "morphTargetsVertexGlobal"
  , shader$4 = `#ifdef MORPHTARGETS
#ifdef MORPHTARGETS_TEXTURE
var vertexID : f32;
#endif
#endif`;
ShaderStore.IncludesShadersStoreWGSL[name$4] = shader$4;
var name$3 = "morphTargetsVertexGlobalDeclaration"
  , shader$3 = `#ifdef MORPHTARGETS
uniform morphTargetInfluences : array<f32,NUM_MORPH_INFLUENCERS>;
#ifdef MORPHTARGETS_TEXTURE
uniform morphTargetTextureIndices : array<f32,NUM_MORPH_INFLUENCERS>;
uniform morphTargetTextureInfo : vec3<f32>;
var morphTargets : texture_2d_array<f32>;
var morphTargetsSampler : sampler;
fn readVector3FromRawSampler(targetIndex : i32,vertexIndex : f32) -> vec3<f32>
{
let y=floor(vertexIndex/uniforms.morphTargetTextureInfo.y);
let x=vertexIndex-y*uniforms.morphTargetTextureInfo.y;
let textureUV=vec2<f32>((x+0.5)/uniforms.morphTargetTextureInfo.y,(y+0.5)/uniforms.morphTargetTextureInfo.z);
return textureSampleLevel(morphTargets,morphTargetsSampler,textureUV,i32(uniforms.morphTargetTextureIndices[targetIndex]),0.0).xyz;
}
#endif
#endif`;
ShaderStore.IncludesShadersStoreWGSL[name$3] = shader$3;
var name$2 = "sceneUboDeclaration"
  , shader$2 = `[[block]]
struct Scene {
viewProjection : mat4x4<f32>;
#ifdef MULTIVIEW
viewProjectionR : mat4x4<f32>;
#endif
view : mat4x4<f32>;
projection : mat4x4<f32>;
vEyePosition : vec4<f32>;
};
var<uniform> scene : Scene;
`;
ShaderStore.IncludesShadersStoreWGSL[name$2] = shader$2;
var builtInName_vertex_index = "gl_VertexID", builtInName_instance_index = "gl_InstanceID", builtInName_position = "gl_Position", builtInName_position_frag = "gl_FragCoord", builtInName_front_facing = "gl_FrontFacing", builtInName_frag_depth = "gl_FragDepth", builtInName_FragColor = "gl_FragColor", leftOverVarName = "uniforms", gpuTextureViewDimensionByWebGPUTextureFunction = {
    texture_1d: TextureViewDimension.E1d,
    texture_2d: TextureViewDimension.E2d,
    texture_2d_array: TextureViewDimension.E2dArray,
    texture_3d: TextureViewDimension.E3d,
    texture_cube: TextureViewDimension.Cube,
    texture_cube_array: TextureViewDimension.CubeArray,
    texture_multisampled_2d: TextureViewDimension.E2d,
    texture_depth_2d: TextureViewDimension.E2d,
    texture_depth_2d_array: TextureViewDimension.E2dArray,
    texture_depth_cube: TextureViewDimension.Cube,
    texture_depth_cube_array: TextureViewDimension.CubeArray,
    texture_depth_multisampled_2d: TextureViewDimension.E2d,
    texture_storage_1d: TextureViewDimension.E1d,
    texture_storage_2d: TextureViewDimension.E2d,
    texture_storage_2d_array: TextureViewDimension.E2dArray,
    texture_storage_3d: TextureViewDimension.E3d,
    texture_external: null
}, WebGPUShaderProcessorWGSL = function(i) {
    __extends(e, i);
    function e() {
        var t = i !== null && i.apply(this, arguments) || this;
        return t.shaderLanguage = ShaderLanguage.WGSL,
        t.uniformRegexp = /uniform\s+(\w+)\s*:\s*(.+)\s*;/,
        t.textureRegexp = /var\s+(\w+)\s*:\s*((array<\s*)?(texture_\w+)\s*(<\s*(.+)\s*>)?\s*(,\s*\w+\s*>\s*)?);/,
        t.noPrecision = !0,
        t
    }
    return e.prototype._getArraySize = function(t, r, n) {
        var o = 0
          , a = r.lastIndexOf(">");
        if (r.indexOf("array") >= 0 && a > 0) {
            for (var s = a; s > 0 && r.charAt(s) !== " " && r.charAt(s) !== ","; )
                s--;
            var l = r.substring(s + 1, a);
            for (o = +l,
            isNaN(o) && (o = +n[l.trim()]); s > 0 && (r.charAt(s) === " " || r.charAt(s) === ","); )
                s--;
            r = r.substring(r.indexOf("<") + 1, s + 1)
        }
        return [t, r, o]
    }
    ,
    e.prototype.initializeShaders = function(t) {
        this.webgpuProcessingContext = t,
        this._attributesWGSL = [],
        this._attributesDeclWGSL = [],
        this._attributeNamesWGSL = [],
        this._varyingsWGSL = [],
        this._varyingsDeclWGSL = [],
        this._varyingNamesWGSL = []
    }
    ,
    e.prototype.preProcessShaderCode = function(t) {
        return RemoveComments(t)
    }
    ,
    e.prototype.varyingProcessor = function(t, r, n, o) {
        var a = /\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s*:\s*(.+)\s*;/gm
          , s = a.exec(t);
        if (s !== null) {
            var l = s[2], u = s[1], c;
            r ? (c = this.webgpuProcessingContext.availableVaryings[u],
            c === void 0 && Logger$2.Warn('Invalid fragment shader: The varying named "' + u + '" is not declared in the vertex shader! This declaration will be ignored.')) : (c = this.webgpuProcessingContext.getVaryingNextLocation(l, this._getArraySize(u, l, n)[2]),
            this.webgpuProcessingContext.availableVaryings[u] = c,
            this._varyingsWGSL.push("[[location(" + c + ")]] " + u + " : " + l + ";"),
            this._varyingsDeclWGSL.push("var<private> " + u + " : " + l + ";"),
            this._varyingNamesWGSL.push(u)),
            t = ""
        }
        return t
    }
    ,
    e.prototype.attributeProcessor = function(t, r, n) {
        var o = /\s*attribute\s+(\S+)\s*:\s*(.+)\s*;/gm
          , a = o.exec(t);
        if (a !== null) {
            var s = a[2]
              , l = a[1]
              , u = this.webgpuProcessingContext.getAttributeNextLocation(s, this._getArraySize(l, s, r)[2]);
            this.webgpuProcessingContext.availableAttributes[l] = u,
            this.webgpuProcessingContext.orderedAttributes[u] = l,
            this._attributesWGSL.push("[[location(" + u + ")]] " + l + " : " + s + ";"),
            this._attributesDeclWGSL.push("var<private> " + l + " : " + s + ";"),
            this._attributeNamesWGSL.push(l),
            t = ""
        }
        return t
    }
    ,
    e.prototype.uniformProcessor = function(t, r, n, o) {
        var a = this.uniformRegexp.exec(t);
        if (a !== null) {
            var s = a[2]
              , l = a[1];
            this._addUniformToLeftOverUBO(l, s, n),
            t = ""
        }
        return t
    }
    ,
    e.prototype.textureProcessor = function(t, r, n, o) {
        var a = this.textureRegexp.exec(t);
        if (a !== null) {
            var s = a[1]
              , l = a[2]
              , u = !!a[3]
              , c = a[4]
              , h = c.indexOf("storage") > 0
              , f = a[6]
              , d = h ? f.substring(0, f.indexOf(",")).trim() : null
              , _ = u ? this._getArraySize(s, l, n)[2] : 0
              , g = this.webgpuProcessingContext.availableTextures[s];
            if (g)
                _ = g.textures.length;
            else {
                g = {
                    isTextureArray: _ > 0,
                    isStorageTexture: h,
                    textures: [],
                    sampleType: TextureSampleType.Float
                },
                _ = _ || 1;
                for (var m = 0; m < _; ++m)
                    g.textures.push(this.webgpuProcessingContext.getNextFreeUBOBinding())
            }
            this.webgpuProcessingContext.availableTextures[s] = g;
            var v = c.indexOf("depth") > 0
              , y = gpuTextureViewDimensionByWebGPUTextureFunction[c]
              , b = v ? TextureSampleType.Depth : f === "u32" ? TextureSampleType.Uint : f === "i32" ? TextureSampleType.Sint : TextureSampleType.Float;
            if (g.sampleType = b,
            y === void 0)
                throw `Can't get the texture dimension corresponding to the texture function "` + c + '"!';
            for (var m = 0; m < _; ++m) {
                var T = g.textures[m]
                  , C = T.groupIndex
                  , A = T.bindingIndex;
                m === 0 && (t = "[[group(" + C + "), binding(" + A + ")]] " + t),
                this._addTextureBindingDescription(s, g, m, y, d, !r)
            }
        }
        return t
    }
    ,
    e.prototype.postProcessor = function(t, r, n, o, a) {
        return t
    }
    ,
    e.prototype.finalizeShaders = function(t, r, n) {
        t = this._processSamplers(t, !0),
        r = this._processSamplers(r, !1),
        t = this._processCustomBuffers(t, !0),
        r = this._processCustomBuffers(r, !1);
        var o = this._buildLeftOverUBO();
        t = o + t,
        r = o + r,
        t = t.replace(/#define /g, "//#define ");
        var a = this._varyingsDeclWGSL.join(`
`) + `
`
          , s = "var<private> " + builtInName_vertex_index + ` : u32;
var<private> ` + builtInName_instance_index + ` : u32;
var<private> ` + builtInName_position + ` : vec4<f32>;
`
          , l = this._attributesDeclWGSL.join(`
`) + `
`
          , u = `struct VertexInputs {
  [[builtin(vertex_index)]] vertexIndex : u32;
  [[builtin(instance_index)]] instanceIndex : u32;
`;
        this._attributesWGSL.length > 0 && (u += this._attributesWGSL.join(`
`)),
        u += `
};
`;
        var c = `struct FragmentInputs {
  [[builtin(position)]] position : vec4<f32>;
`;
        this._varyingsWGSL.length > 0 && (c += this._varyingsWGSL.join(`
`)),
        c += `
};
`,
        t = s + u + l + c + a + t;
        for (var h = `  var output : FragmentInputs;
  ` + builtInName_vertex_index + ` = input.vertexIndex;
  ` + builtInName_instance_index + ` = input.instanceIndex;
`, f = 0; f < this._attributeNamesWGSL.length; ++f) {
            var d = this._attributeNamesWGSL[f];
            h += "  " + d + " = input." + d + `;
`
        }
        for (var _ = "  output.position = " + builtInName_position + `;
  output.position.y = -output.position.y;
`, f = 0; f < this._varyingNamesWGSL.length; ++f) {
            var g = this._varyingNamesWGSL[f];
            _ += "  output." + g + " = " + g + `;
`
        }
        _ += "  return output;",
        t = this._injectStartingAndEndingCode(t, h, _),
        r = r.replace(/#define /g, "//#define ");
        var m = "var<private> " + builtInName_position_frag + ` : vec4<f32>;
var<private> ` + builtInName_front_facing + ` : bool;
var<private> ` + builtInName_FragColor + ` : vec4<f32>;
var<private> ` + builtInName_frag_depth + ` : f32;
`
          , v = `struct FragmentInputs {
  [[builtin(position)]] position : vec4<f32>;
  [[builtin(front_facing)]] frontFacing : bool;
`;
        this._varyingsWGSL.length > 0 && (v += this._varyingsWGSL.join(`
`)),
        v += `
};
`;
        for (var y = `struct FragmentOutputs {
  [[location(0)]] color : vec4<f32>;
`, b = !1, T = 0; !b && (T = r.indexOf(builtInName_frag_depth, T),
        !(T < 0)); ) {
            var C = T;
            for (b = !0; T > 1 && r.charAt(T) !== `
`; ) {
                if (r.charAt(T) === "/" && r.charAt(T - 1) === "/") {
                    b = !1;
                    break
                }
                T--
            }
            T = C + 12
        }
        b && (y += `  [[builtin(frag_depth)]] fragDepth: f32;
`),
        y += `};
`,
        r = m + v + a + y + r;
        for (var A = `  var output : FragmentOutputs;
  ` + builtInName_position_frag + ` = input.position;
  ` + builtInName_front_facing + ` = input.frontFacing;
`, f = 0; f < this._varyingNamesWGSL.length; ++f) {
            var S = this._varyingNamesWGSL[f];
            A += "  " + S + " = input." + S + `;
`
        }
        var P = "  output.color = " + builtInName_FragColor + `;
`;
        return b && (P += "  output.fragDepth = " + builtInName_frag_depth + `;
`),
        P += "  return output;",
        r = this._injectStartingAndEndingCode(r, A, P),
        this._collectBindingNames(),
        this._preCreateBindGroupEntries(),
        {
            vertexCode: t,
            fragmentCode: r
        }
    }
    ,
    e.prototype._generateLeftOverUBOCode = function(t, r) {
        for (var n = "[[block]] struct " + t + ` {
`, o = 0, a = this.webgpuProcessingContext.leftOverUniforms; o < a.length; o++) {
            var s = a[o]
              , l = s.type.replace(/^(.*?)(<.*>)?$/, "$1")
              , u = WebGPUShaderProcessor.UniformSizes[l];
            s.length > 0 ? u <= 2 ? n += " [[align(16)]] " + s.name + " : [[stride(16)]] array<" + s.type + ", " + s.length + `>;
` : n += " " + s.name + " : array<" + s.type + ", " + s.length + `>;
` : n += "  " + s.name + " : " + s.type + `;
`
        }
        return n += `};
`,
        n += "[[group(" + r.binding.groupIndex + "), binding(" + r.binding.bindingIndex + ")]] var<uniform> " + leftOverVarName + " : " + t + `;
`,
        n
    }
    ,
    e.prototype._injectStartingAndEndingCode = function(t, r, n) {
        if (r) {
            var o = t.indexOf("fn main");
            if (o >= 0) {
                for (; o++ < t.length && t.charAt(o) != "{"; )
                    ;
                if (o < t.length) {
                    for (; o++ < t.length && t.charAt(o) != `
`; )
                        ;
                    if (o < t.length) {
                        var a = t.substring(0, o + 1)
                          , s = t.substring(o + 1);
                        t = a + r + s
                    }
                }
            }
        }
        if (n) {
            var l = t.lastIndexOf("}");
            t = t.substring(0, l),
            t += n + `
}`
        }
        return t
    }
    ,
    e.prototype._processSamplers = function(t, r) {
        for (var n = /var\s+(\w+Sampler)\s*:\s*(sampler|sampler_comparison)\s*;/gm; ; ) {
            var o = n.exec(t);
            if (o === null)
                break;
            var a = o[1]
              , s = o[2]
              , l = a.indexOf(WebGPUShaderProcessor.AutoSamplerSuffix) === a.length - WebGPUShaderProcessor.AutoSamplerSuffix.length ? a.substring(0, a.indexOf(WebGPUShaderProcessor.AutoSamplerSuffix)) : null
              , u = s === "sampler_comparison" ? SamplerBindingType.Comparison : SamplerBindingType.Filtering;
            if (l) {
                var c = this.webgpuProcessingContext.availableTextures[l];
                c && (c.autoBindSampler = !0)
            }
            var h = this.webgpuProcessingContext.availableSamplers[a];
            h || (h = {
                binding: this.webgpuProcessingContext.getNextFreeUBOBinding(),
                type: u
            },
            this.webgpuProcessingContext.availableSamplers[a] = h),
            this._addSamplerBindingDescription(a, h, r);
            var f = t.substring(0, o.index)
              , d = "[[group(" + h.binding.groupIndex + "), binding(" + h.binding.bindingIndex + ")]] "
              , _ = t.substring(o.index);
            t = f + d + _,
            n.lastIndex += d.length
        }
        return t
    }
    ,
    e.prototype._processCustomBuffers = function(t, r) {
        for (var n = /var<\s*(uniform|storage)\s*(,\s*(read|read_write)\s*)?>\s+(\S+)\s*:\s*(\S+)\s*;/gm; ; ) {
            var o = n.exec(t);
            if (o === null)
                break;
            var a = o[1]
              , s = o[3]
              , l = o[4]
              , u = o[5]
              , c = this.webgpuProcessingContext.availableBuffers[l];
            if (!c) {
                var h = a === "uniform" ? WebGPUShaderProcessingContext.KnownUBOs[u] : null
                  , f = void 0;
                h ? (l = u,
                f = h.binding,
                f.groupIndex === -1 && (f = this.webgpuProcessingContext.getNextFreeUBOBinding())) : f = this.webgpuProcessingContext.getNextFreeUBOBinding(),
                c = {
                    binding: f
                },
                this.webgpuProcessingContext.availableBuffers[l] = c
            }
            this._addBufferBindingDescription(l, this.webgpuProcessingContext.availableBuffers[l], s === "read_write" ? BufferBindingType.Storage : a === "storage" ? BufferBindingType.ReadOnlyStorage : BufferBindingType.Uniform, r);
            var d = c.binding.groupIndex
              , _ = c.binding.bindingIndex
              , g = t.substring(0, o.index)
              , m = "[[group(" + d + "), binding(" + _ + ")]] "
              , v = t.substring(o.index);
            t = g + m + v,
            n.lastIndex += m.length
        }
        return t
    }
    ,
    e
}(WebGPUShaderProcessor), WebGPUHardwareTexture = function() {
    function i(e) {
        e === void 0 && (e = null),
        this.format = TextureFormat.RGBA8Unorm,
        this.textureUsages = 0,
        this.textureAdditionalUsages = 0,
        this._webgpuTexture = e,
        this._webgpuMSAATexture = null,
        this.view = null
    }
    return Object.defineProperty(i.prototype, "underlyingResource", {
        get: function() {
            return this._webgpuTexture
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "msaaTexture", {
        get: function() {
            return this._webgpuMSAATexture
        },
        set: function(e) {
            this._webgpuMSAATexture = e
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.set = function(e) {
        this._webgpuTexture = e
    }
    ,
    i.prototype.setMSAATexture = function(e) {
        this._webgpuMSAATexture = e
    }
    ,
    i.prototype.setUsage = function(e, t, r, n, o) {
        t = e === InternalTextureSource.RenderTarget ? !1 : t,
        this.createView({
            format: this.format,
            dimension: r ? TextureViewDimension.Cube : TextureViewDimension.E2d,
            mipLevelCount: t ? Scalar.ILog2(Math.max(n, o)) + 1 : 1,
            baseArrayLayer: 0,
            baseMipLevel: 0,
            arrayLayerCount: r ? 6 : 1,
            aspect: TextureAspect.All
        })
    }
    ,
    i.prototype.createView = function(e) {
        this.view = this._webgpuTexture.createView(e)
    }
    ,
    i.prototype.reset = function() {
        this._webgpuTexture = null,
        this._webgpuMSAATexture = null,
        this.view = null
    }
    ,
    i.prototype.release = function() {
        var e, t, r;
        (e = this._webgpuTexture) === null || e === void 0 || e.destroy(),
        (t = this._webgpuMSAATexture) === null || t === void 0 || t.destroy(),
        (r = this._copyInvertYTempTexture) === null || r === void 0 || r.destroy(),
        this.reset()
    }
    ,
    i
}(), mipmapVertexSource = `
    const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f));
    const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f));

    layout(location = 0) out vec2 vTex;

    void main() {
        vTex = tex[gl_VertexIndex];
        gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);
    }
    `, mipmapFragmentSource = `
    layout(set = 0, binding = 0) uniform sampler imgSampler;
    layout(set = 0, binding = 1) uniform texture2D img;

    layout(location = 0) in vec2 vTex;
    layout(location = 0) out vec4 outColor;

    void main() {
        outColor = texture(sampler2D(img, imgSampler), vTex);
    }
    `, invertYPreMultiplyAlphaVertexSource = `
    #extension GL_EXT_samplerless_texture_functions : enable

    const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f));
    const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f));

    layout(set = 0, binding = 0) uniform texture2D img;

    #ifdef INVERTY
        layout(location = 0) out flat ivec2 vTextureSize;
    #endif

    void main() {
        #ifdef INVERTY
            vTextureSize = textureSize(img, 0);
        #endif
        gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);
    }
    `, invertYPreMultiplyAlphaFragmentSource = `
    #extension GL_EXT_samplerless_texture_functions : enable

    layout(set = 0, binding = 0) uniform texture2D img;

    #ifdef INVERTY
        layout(location = 0) in flat ivec2 vTextureSize;
    #endif
    layout(location = 0) out vec4 outColor;

    void main() {
    #ifdef INVERTY
        vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, vTextureSize.y - gl_FragCoord.y), 0);
    #else
        vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0);
    #endif
    #ifdef PREMULTIPLYALPHA
        color.rgb *= color.a;
    #endif
        outColor = color;
    }
    `, clearVertexSource = `
    const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f));

    void main() {
        gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);
    }
    `, clearFragmentSource = `
    layout(set = 0, binding = 0) uniform Uniforms {
        uniform vec4 color;
    };

    layout(location = 0) out vec4 outColor;

    void main() {
        outColor = color;
    }
    `, PipelineType;
(function(i) {
    i[i.MipMap = 0] = "MipMap",
    i[i.InvertYPremultiplyAlpha = 1] = "InvertYPremultiplyAlpha",
    i[i.Clear = 2] = "Clear"
}
)(PipelineType || (PipelineType = {}));
var shadersForPipelineType = [{
    vertex: mipmapVertexSource,
    fragment: mipmapFragmentSource
}, {
    vertex: invertYPreMultiplyAlphaVertexSource,
    fragment: invertYPreMultiplyAlphaFragmentSource
}, {
    vertex: clearVertexSource,
    fragment: clearFragmentSource
}], WebGPUTextureHelper = function() {
    function i(e, t, r, n) {
        this._pipelines = {},
        this._compiledShaders = [],
        this._deferredReleaseTextures = [],
        this._device = e,
        this._glslang = t,
        this._tintWASM = r,
        this._bufferManager = n,
        this._mipmapSampler = e.createSampler({
            minFilter: FilterMode.Linear
        }),
        this._getPipeline(TextureFormat.RGBA8Unorm)
    }
    return i.ComputeNumMipmapLevels = function(e, t) {
        return Scalar.ILog2(Math.max(e, t)) + 1
    }
    ,
    i.prototype._getPipeline = function(e, t, r) {
        t === void 0 && (t = PipelineType.MipMap);
        var n = t === PipelineType.MipMap ? 1 << 0 : t === PipelineType.InvertYPremultiplyAlpha ? ((r.invertY ? 1 : 0) << 1) + ((r.premultiplyAlpha ? 1 : 0) << 2) : t === PipelineType.Clear ? 1 << 3 : 0;
        this._pipelines[e] || (this._pipelines[e] = []);
        var o = this._pipelines[e][n];
        if (!o) {
            var a = `#version 450\r
`;
            t === PipelineType.InvertYPremultiplyAlpha && (r.invertY && (a += `#define INVERTY\r
`),
            r.premultiplyAlpha && (a += `#define PREMULTIPLYALPHA\r
`));
            var s = this._compiledShaders[n];
            if (!s) {
                var l = this._glslang.compileGLSL(a + shadersForPipelineType[t].vertex, "vertex")
                  , u = this._glslang.compileGLSL(a + shadersForPipelineType[t].fragment, "fragment");
                this._tintWASM && (l = this._tintWASM.convertSpirV2WGSL(l),
                u = this._tintWASM.convertSpirV2WGSL(u));
                var c = this._device.createShaderModule({
                    code: l
                })
                  , h = this._device.createShaderModule({
                    code: u
                });
                s = this._compiledShaders[n] = [c, h]
            }
            var f = this._device.createRenderPipeline({
                vertex: {
                    module: s[0],
                    entryPoint: "main"
                },
                fragment: {
                    module: s[1],
                    entryPoint: "main",
                    targets: [{
                        format: e
                    }]
                },
                primitive: {
                    topology: PrimitiveTopology.TriangleStrip,
                    stripIndexFormat: IndexFormat.Uint16
                }
            });
            o = this._pipelines[e][n] = [f, f.getBindGroupLayout(0)]
        }
        return o
    }
    ,
    i._GetTextureTypeFromFormat = function(e) {
        switch (e) {
        case TextureFormat.R8Unorm:
        case TextureFormat.R8Snorm:
        case TextureFormat.R8Uint:
        case TextureFormat.R8Sint:
        case TextureFormat.RG8Unorm:
        case TextureFormat.RG8Snorm:
        case TextureFormat.RG8Uint:
        case TextureFormat.RG8Sint:
        case TextureFormat.RGBA8Unorm:
        case TextureFormat.RGBA8UnormSRGB:
        case TextureFormat.RGBA8Snorm:
        case TextureFormat.RGBA8Uint:
        case TextureFormat.RGBA8Sint:
        case TextureFormat.BGRA8Unorm:
        case TextureFormat.BGRA8UnormSRGB:
        case TextureFormat.RGB10A2Unorm:
        case TextureFormat.RGB9E5UFloat:
        case TextureFormat.RG11B10UFloat:
        case TextureFormat.Depth24UnormStencil8:
        case TextureFormat.Depth32FloatStencil8:
        case TextureFormat.BC7RGBAUnorm:
        case TextureFormat.BC7RGBAUnormSRGB:
        case TextureFormat.BC6HRGBUFloat:
        case TextureFormat.BC6HRGBFloat:
        case TextureFormat.BC5RGUnorm:
        case TextureFormat.BC5RGSnorm:
        case TextureFormat.BC3RGBAUnorm:
        case TextureFormat.BC3RGBAUnormSRGB:
        case TextureFormat.BC2RGBAUnorm:
        case TextureFormat.BC2RGBAUnormSRGB:
        case TextureFormat.BC4RUnorm:
        case TextureFormat.BC4RSnorm:
        case TextureFormat.BC1RGBAUnorm:
        case TextureFormat.BC1RGBAUnormSRGB:
        case TextureFormat.ETC2RGB8Unorm:
        case TextureFormat.ETC2RGB8UnormSRGB:
        case TextureFormat.ETC2RGB8A1Unorm:
        case TextureFormat.ETC2RGB8A1UnormSRGB:
        case TextureFormat.ETC2RGBA8Unorm:
        case TextureFormat.ETC2RGBA8UnormSRGB:
        case TextureFormat.EACR11Unorm:
        case TextureFormat.EACR11Snorm:
        case TextureFormat.EACRG11Unorm:
        case TextureFormat.EACRG11Snorm:
        case TextureFormat.ASTC4x4Unorm:
        case TextureFormat.ASTC4x4UnormSRGB:
        case TextureFormat.ASTC5x4Unorm:
        case TextureFormat.ASTC5x4UnormSRGB:
        case TextureFormat.ASTC5x5Unorm:
        case TextureFormat.ASTC5x5UnormSRGB:
        case TextureFormat.ASTC6x5Unorm:
        case TextureFormat.ASTC6x5UnormSRGB:
        case TextureFormat.ASTC6x6Unorm:
        case TextureFormat.ASTC6x6UnormSRGB:
        case TextureFormat.ASTC8x5Unorm:
        case TextureFormat.ASTC8x5UnormSRGB:
        case TextureFormat.ASTC8x6Unorm:
        case TextureFormat.ASTC8x6UnormSRGB:
        case TextureFormat.ASTC8x8Unorm:
        case TextureFormat.ASTC8x8UnormSRGB:
        case TextureFormat.ASTC10x5Unorm:
        case TextureFormat.ASTC10x5UnormSRGB:
        case TextureFormat.ASTC10x6Unorm:
        case TextureFormat.ASTC10x6UnormSRGB:
        case TextureFormat.ASTC10x8Unorm:
        case TextureFormat.ASTC10x8UnormSRGB:
        case TextureFormat.ASTC10x10Unorm:
        case TextureFormat.ASTC10x10UnormSRGB:
        case TextureFormat.ASTC12x10Unorm:
        case TextureFormat.ASTC12x10UnormSRGB:
        case TextureFormat.ASTC12x12Unorm:
        case TextureFormat.ASTC12x12UnormSRGB:
            return 0;
        case TextureFormat.R16Uint:
        case TextureFormat.R16Sint:
        case TextureFormat.RG16Uint:
        case TextureFormat.RG16Sint:
        case TextureFormat.RGBA16Uint:
        case TextureFormat.RGBA16Sint:
        case TextureFormat.Depth16Unorm:
            return 5;
        case TextureFormat.R16Float:
        case TextureFormat.RG16Float:
        case TextureFormat.RGBA16Float:
            return 2;
        case TextureFormat.R32Uint:
        case TextureFormat.R32Sint:
        case TextureFormat.RG32Uint:
        case TextureFormat.RG32Sint:
        case TextureFormat.RGBA32Uint:
        case TextureFormat.RGBA32Sint:
            return 7;
        case TextureFormat.R32Float:
        case TextureFormat.RG32Float:
        case TextureFormat.RGBA32Float:
        case TextureFormat.Depth32Float:
            return 1;
        case TextureFormat.Stencil8:
            throw "No fixed size for Stencil8 format!";
        case TextureFormat.Depth24Plus:
            throw "No fixed size for Depth24Plus format!";
        case TextureFormat.Depth24PlusStencil8:
            throw "No fixed size for Depth24PlusStencil8 format!"
        }
        return 0
    }
    ,
    i._GetBlockInformationFromFormat = function(e) {
        switch (e) {
        case TextureFormat.R8Unorm:
        case TextureFormat.R8Snorm:
        case TextureFormat.R8Uint:
        case TextureFormat.R8Sint:
            return {
                width: 1,
                height: 1,
                length: 1
            };
        case TextureFormat.R16Uint:
        case TextureFormat.R16Sint:
        case TextureFormat.R16Float:
        case TextureFormat.RG8Unorm:
        case TextureFormat.RG8Snorm:
        case TextureFormat.RG8Uint:
        case TextureFormat.RG8Sint:
            return {
                width: 1,
                height: 1,
                length: 2
            };
        case TextureFormat.R32Uint:
        case TextureFormat.R32Sint:
        case TextureFormat.R32Float:
        case TextureFormat.RG16Uint:
        case TextureFormat.RG16Sint:
        case TextureFormat.RG16Float:
        case TextureFormat.RGBA8Unorm:
        case TextureFormat.RGBA8UnormSRGB:
        case TextureFormat.RGBA8Snorm:
        case TextureFormat.RGBA8Uint:
        case TextureFormat.RGBA8Sint:
        case TextureFormat.BGRA8Unorm:
        case TextureFormat.BGRA8UnormSRGB:
        case TextureFormat.RGB9E5UFloat:
        case TextureFormat.RGB10A2Unorm:
        case TextureFormat.RG11B10UFloat:
            return {
                width: 1,
                height: 1,
                length: 4
            };
        case TextureFormat.RG32Uint:
        case TextureFormat.RG32Sint:
        case TextureFormat.RG32Float:
        case TextureFormat.RGBA16Uint:
        case TextureFormat.RGBA16Sint:
        case TextureFormat.RGBA16Float:
            return {
                width: 1,
                height: 1,
                length: 8
            };
        case TextureFormat.RGBA32Uint:
        case TextureFormat.RGBA32Sint:
        case TextureFormat.RGBA32Float:
            return {
                width: 1,
                height: 1,
                length: 16
            };
        case TextureFormat.Stencil8:
            throw "No fixed size for Stencil8 format!";
        case TextureFormat.Depth16Unorm:
            return {
                width: 1,
                height: 1,
                length: 2
            };
        case TextureFormat.Depth24Plus:
            throw "No fixed size for Depth24Plus format!";
        case TextureFormat.Depth24PlusStencil8:
            throw "No fixed size for Depth24PlusStencil8 format!";
        case TextureFormat.Depth32Float:
            return {
                width: 1,
                height: 1,
                length: 4
            };
        case TextureFormat.Depth24UnormStencil8:
            return {
                width: 1,
                height: 1,
                length: 4
            };
        case TextureFormat.Depth32FloatStencil8:
            return {
                width: 1,
                height: 1,
                length: 5
            };
        case TextureFormat.BC7RGBAUnorm:
        case TextureFormat.BC7RGBAUnormSRGB:
        case TextureFormat.BC6HRGBUFloat:
        case TextureFormat.BC6HRGBFloat:
        case TextureFormat.BC5RGUnorm:
        case TextureFormat.BC5RGSnorm:
        case TextureFormat.BC3RGBAUnorm:
        case TextureFormat.BC3RGBAUnormSRGB:
        case TextureFormat.BC2RGBAUnorm:
        case TextureFormat.BC2RGBAUnormSRGB:
            return {
                width: 4,
                height: 4,
                length: 16
            };
        case TextureFormat.BC4RUnorm:
        case TextureFormat.BC4RSnorm:
        case TextureFormat.BC1RGBAUnorm:
        case TextureFormat.BC1RGBAUnormSRGB:
            return {
                width: 4,
                height: 4,
                length: 8
            };
        case TextureFormat.ETC2RGB8Unorm:
        case TextureFormat.ETC2RGB8UnormSRGB:
        case TextureFormat.ETC2RGB8A1Unorm:
        case TextureFormat.ETC2RGB8A1UnormSRGB:
        case TextureFormat.EACR11Unorm:
        case TextureFormat.EACR11Snorm:
            return {
                width: 4,
                height: 4,
                length: 8
            };
        case TextureFormat.ETC2RGBA8Unorm:
        case TextureFormat.ETC2RGBA8UnormSRGB:
        case TextureFormat.EACRG11Unorm:
        case TextureFormat.EACRG11Snorm:
            return {
                width: 4,
                height: 4,
                length: 16
            };
        case TextureFormat.ASTC4x4Unorm:
        case TextureFormat.ASTC4x4UnormSRGB:
            return {
                width: 4,
                height: 4,
                length: 16
            };
        case TextureFormat.ASTC5x4Unorm:
        case TextureFormat.ASTC5x4UnormSRGB:
            return {
                width: 5,
                height: 4,
                length: 16
            };
        case TextureFormat.ASTC5x5Unorm:
        case TextureFormat.ASTC5x5UnormSRGB:
            return {
                width: 5,
                height: 5,
                length: 16
            };
        case TextureFormat.ASTC6x5Unorm:
        case TextureFormat.ASTC6x5UnormSRGB:
            return {
                width: 6,
                height: 5,
                length: 16
            };
        case TextureFormat.ASTC6x6Unorm:
        case TextureFormat.ASTC6x6UnormSRGB:
            return {
                width: 6,
                height: 6,
                length: 16
            };
        case TextureFormat.ASTC8x5Unorm:
        case TextureFormat.ASTC8x5UnormSRGB:
            return {
                width: 8,
                height: 5,
                length: 16
            };
        case TextureFormat.ASTC8x6Unorm:
        case TextureFormat.ASTC8x6UnormSRGB:
            return {
                width: 8,
                height: 6,
                length: 16
            };
        case TextureFormat.ASTC8x8Unorm:
        case TextureFormat.ASTC8x8UnormSRGB:
            return {
                width: 8,
                height: 8,
                length: 16
            };
        case TextureFormat.ASTC10x5Unorm:
        case TextureFormat.ASTC10x5UnormSRGB:
            return {
                width: 10,
                height: 5,
                length: 16
            };
        case TextureFormat.ASTC10x6Unorm:
        case TextureFormat.ASTC10x6UnormSRGB:
            return {
                width: 10,
                height: 6,
                length: 16
            };
        case TextureFormat.ASTC10x8Unorm:
        case TextureFormat.ASTC10x8UnormSRGB:
            return {
                width: 10,
                height: 8,
                length: 16
            };
        case TextureFormat.ASTC10x10Unorm:
        case TextureFormat.ASTC10x10UnormSRGB:
            return {
                width: 10,
                height: 10,
                length: 16
            };
        case TextureFormat.ASTC12x10Unorm:
        case TextureFormat.ASTC12x10UnormSRGB:
            return {
                width: 12,
                height: 10,
                length: 16
            };
        case TextureFormat.ASTC12x12Unorm:
        case TextureFormat.ASTC12x12UnormSRGB:
            return {
                width: 12,
                height: 12,
                length: 16
            }
        }
        return {
            width: 1,
            height: 1,
            length: 4
        }
    }
    ,
    i._IsHardwareTexture = function(e) {
        return !!e.release
    }
    ,
    i._IsInternalTexture = function(e) {
        return !!e.dispose
    }
    ,
    i.GetCompareFunction = function(e) {
        switch (e) {
        case 519:
            return CompareFunction.Always;
        case 514:
            return CompareFunction.Equal;
        case 516:
            return CompareFunction.Greater;
        case 518:
            return CompareFunction.GreaterEqual;
        case 513:
            return CompareFunction.Less;
        case 515:
            return CompareFunction.LessEqual;
        case 512:
            return CompareFunction.Never;
        case 517:
            return CompareFunction.NotEqual;
        default:
            return CompareFunction.Less
        }
    }
    ,
    i.IsImageBitmap = function(e) {
        return e.close !== void 0
    }
    ,
    i.IsImageBitmapArray = function(e) {
        return Array.isArray(e) && e[0].close !== void 0
    }
    ,
    i.prototype.setCommandEncoder = function(e) {
        this._commandEncoderForCreation = e
    }
    ,
    i.IsCompressedFormat = function(e) {
        switch (e) {
        case TextureFormat.BC7RGBAUnormSRGB:
        case TextureFormat.BC7RGBAUnorm:
        case TextureFormat.BC6HRGBFloat:
        case TextureFormat.BC6HRGBUFloat:
        case TextureFormat.BC5RGSnorm:
        case TextureFormat.BC5RGUnorm:
        case TextureFormat.BC4RSnorm:
        case TextureFormat.BC4RUnorm:
        case TextureFormat.BC3RGBAUnormSRGB:
        case TextureFormat.BC3RGBAUnorm:
        case TextureFormat.BC2RGBAUnormSRGB:
        case TextureFormat.BC2RGBAUnorm:
        case TextureFormat.BC1RGBAUnormSRGB:
        case TextureFormat.BC1RGBAUnorm:
        case TextureFormat.ETC2RGB8Unorm:
        case TextureFormat.ETC2RGB8UnormSRGB:
        case TextureFormat.ETC2RGB8A1Unorm:
        case TextureFormat.ETC2RGB8A1UnormSRGB:
        case TextureFormat.ETC2RGBA8Unorm:
        case TextureFormat.ETC2RGBA8UnormSRGB:
        case TextureFormat.EACR11Unorm:
        case TextureFormat.EACR11Snorm:
        case TextureFormat.EACRG11Unorm:
        case TextureFormat.EACRG11Snorm:
        case TextureFormat.ASTC4x4Unorm:
        case TextureFormat.ASTC4x4UnormSRGB:
        case TextureFormat.ASTC5x4Unorm:
        case TextureFormat.ASTC5x4UnormSRGB:
        case TextureFormat.ASTC5x5Unorm:
        case TextureFormat.ASTC5x5UnormSRGB:
        case TextureFormat.ASTC6x5Unorm:
        case TextureFormat.ASTC6x5UnormSRGB:
        case TextureFormat.ASTC6x6Unorm:
        case TextureFormat.ASTC6x6UnormSRGB:
        case TextureFormat.ASTC8x5Unorm:
        case TextureFormat.ASTC8x5UnormSRGB:
        case TextureFormat.ASTC8x6Unorm:
        case TextureFormat.ASTC8x6UnormSRGB:
        case TextureFormat.ASTC8x8Unorm:
        case TextureFormat.ASTC8x8UnormSRGB:
        case TextureFormat.ASTC10x5Unorm:
        case TextureFormat.ASTC10x5UnormSRGB:
        case TextureFormat.ASTC10x6Unorm:
        case TextureFormat.ASTC10x6UnormSRGB:
        case TextureFormat.ASTC10x8Unorm:
        case TextureFormat.ASTC10x8UnormSRGB:
        case TextureFormat.ASTC10x10Unorm:
        case TextureFormat.ASTC10x10UnormSRGB:
        case TextureFormat.ASTC12x10Unorm:
        case TextureFormat.ASTC12x10UnormSRGB:
        case TextureFormat.ASTC12x12Unorm:
        case TextureFormat.ASTC12x12UnormSRGB:
            return !0
        }
        return !1
    }
    ,
    i.GetWebGPUTextureFormat = function(e, t, r) {
        switch (r === void 0 && (r = !1),
        t) {
        case 15:
            return TextureFormat.Depth16Unorm;
        case 13:
            return TextureFormat.Depth24PlusStencil8;
        case 14:
            return TextureFormat.Depth32Float;
        case 36492:
            return r ? TextureFormat.BC7RGBAUnormSRGB : TextureFormat.BC7RGBAUnorm;
        case 36495:
            return TextureFormat.BC6HRGBUFloat;
        case 36494:
            return TextureFormat.BC6HRGBFloat;
        case 33779:
            return r ? TextureFormat.BC3RGBAUnormSRGB : TextureFormat.BC3RGBAUnorm;
        case 33778:
            return r ? TextureFormat.BC2RGBAUnormSRGB : TextureFormat.BC2RGBAUnorm;
        case 33777:
        case 33776:
            return r ? TextureFormat.BC1RGBAUnormSRGB : TextureFormat.BC1RGBAUnorm;
        case 37808:
            return r ? TextureFormat.ASTC4x4UnormSRGB : TextureFormat.ASTC4x4Unorm;
        case 36196:
            return r ? TextureFormat.ETC2RGB8UnormSRGB : TextureFormat.ETC2RGB8Unorm
        }
        switch (e) {
        case 3:
            switch (t) {
            case 6:
                return TextureFormat.R8Snorm;
            case 7:
                return TextureFormat.RG8Snorm;
            case 4:
                throw "RGB format not supported in WebGPU";
            case 8:
                return TextureFormat.R8Sint;
            case 9:
                return TextureFormat.RG8Sint;
            case 10:
                throw "RGB_INTEGER format not supported in WebGPU";
            case 11:
                return TextureFormat.RGBA8Sint;
            default:
                return TextureFormat.RGBA8Snorm
            }
        case 0:
            switch (t) {
            case 6:
                return TextureFormat.R8Unorm;
            case 7:
                return TextureFormat.RG8Unorm;
            case 4:
                throw "TEXTUREFORMAT_RGB format not supported in WebGPU";
            case 5:
                return r ? TextureFormat.RGBA8UnormSRGB : TextureFormat.RGBA8Unorm;
            case 12:
                return r ? TextureFormat.BGRA8UnormSRGB : TextureFormat.BGRA8Unorm;
            case 8:
                return TextureFormat.R8Uint;
            case 9:
                return TextureFormat.RG8Uint;
            case 10:
                throw "RGB_INTEGER format not supported in WebGPU";
            case 11:
                return TextureFormat.RGBA8Uint;
            case 0:
                throw "TEXTUREFORMAT_ALPHA format not supported in WebGPU";
            case 1:
                throw "TEXTUREFORMAT_LUMINANCE format not supported in WebGPU";
            case 2:
                throw "TEXTUREFORMAT_LUMINANCE_ALPHA format not supported in WebGPU";
            default:
                return TextureFormat.RGBA8Unorm
            }
        case 4:
            switch (t) {
            case 8:
                return TextureFormat.R16Sint;
            case 9:
                return TextureFormat.RG16Sint;
            case 10:
                throw "TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";
            case 11:
                return TextureFormat.RGBA16Sint;
            default:
                return TextureFormat.RGBA16Sint
            }
        case 5:
            switch (t) {
            case 8:
                return TextureFormat.R16Uint;
            case 9:
                return TextureFormat.RG16Uint;
            case 10:
                throw "TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";
            case 11:
                return TextureFormat.RGBA16Uint;
            default:
                return TextureFormat.RGBA16Uint
            }
        case 6:
            switch (t) {
            case 8:
                return TextureFormat.R32Sint;
            case 9:
                return TextureFormat.RG32Sint;
            case 10:
                throw "TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";
            case 11:
                return TextureFormat.RGBA32Sint;
            default:
                return TextureFormat.RGBA32Sint
            }
        case 7:
            switch (t) {
            case 8:
                return TextureFormat.R32Uint;
            case 9:
                return TextureFormat.RG32Uint;
            case 10:
                throw "TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";
            case 11:
                return TextureFormat.RGBA32Uint;
            default:
                return TextureFormat.RGBA32Uint
            }
        case 1:
            switch (t) {
            case 6:
                return TextureFormat.R32Float;
            case 7:
                return TextureFormat.RG32Float;
            case 4:
                throw "TEXTUREFORMAT_RGB format not supported in WebGPU";
            case 5:
                return TextureFormat.RGBA32Float;
            default:
                return TextureFormat.RGBA32Float
            }
        case 2:
            switch (t) {
            case 6:
                return TextureFormat.R16Float;
            case 7:
                return TextureFormat.RG16Float;
            case 4:
                throw "TEXTUREFORMAT_RGB format not supported in WebGPU";
            case 5:
                return TextureFormat.RGBA16Float;
            default:
                return TextureFormat.RGBA16Float
            }
        case 10:
            throw "TEXTURETYPE_UNSIGNED_SHORT_5_6_5 format not supported in WebGPU";
        case 13:
            throw "TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV format not supported in WebGPU";
        case 14:
            throw "TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV format not supported in WebGPU";
        case 8:
            throw "TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 format not supported in WebGPU";
        case 9:
            throw "TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 format not supported in WebGPU";
        case 11:
            switch (t) {
            case 5:
                return TextureFormat.RGB10A2Unorm;
            case 11:
                throw "TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV";
            default:
                return TextureFormat.RGB10A2Unorm
            }
        }
        return r ? TextureFormat.RGBA8UnormSRGB : TextureFormat.RGBA8Unorm
    }
    ,
    i.GetNumChannelsFromWebGPUTextureFormat = function(e) {
        switch (e) {
        case TextureFormat.R8Unorm:
        case TextureFormat.R8Snorm:
        case TextureFormat.R8Uint:
        case TextureFormat.R8Sint:
        case TextureFormat.BC4RUnorm:
        case TextureFormat.BC4RSnorm:
        case TextureFormat.R16Uint:
        case TextureFormat.R16Sint:
        case TextureFormat.Depth16Unorm:
        case TextureFormat.R16Float:
        case TextureFormat.R32Uint:
        case TextureFormat.R32Sint:
        case TextureFormat.R32Float:
        case TextureFormat.Depth32Float:
        case TextureFormat.Stencil8:
        case TextureFormat.Depth24Plus:
        case TextureFormat.EACR11Unorm:
        case TextureFormat.EACR11Snorm:
            return 1;
        case TextureFormat.RG8Unorm:
        case TextureFormat.RG8Snorm:
        case TextureFormat.RG8Uint:
        case TextureFormat.RG8Sint:
        case TextureFormat.Depth24UnormStencil8:
        case TextureFormat.Depth32FloatStencil8:
        case TextureFormat.BC5RGUnorm:
        case TextureFormat.BC5RGSnorm:
        case TextureFormat.RG16Uint:
        case TextureFormat.RG16Sint:
        case TextureFormat.RG16Float:
        case TextureFormat.RG32Uint:
        case TextureFormat.RG32Sint:
        case TextureFormat.RG32Float:
        case TextureFormat.Depth24PlusStencil8:
        case TextureFormat.EACRG11Unorm:
        case TextureFormat.EACRG11Snorm:
            return 2;
        case TextureFormat.RGB9E5UFloat:
        case TextureFormat.RG11B10UFloat:
        case TextureFormat.BC6HRGBUFloat:
        case TextureFormat.BC6HRGBFloat:
        case TextureFormat.ETC2RGB8Unorm:
        case TextureFormat.ETC2RGB8UnormSRGB:
            return 3;
        case TextureFormat.RGBA8Unorm:
        case TextureFormat.RGBA8UnormSRGB:
        case TextureFormat.RGBA8Snorm:
        case TextureFormat.RGBA8Uint:
        case TextureFormat.RGBA8Sint:
        case TextureFormat.BGRA8Unorm:
        case TextureFormat.BGRA8UnormSRGB:
        case TextureFormat.RGB10A2Unorm:
        case TextureFormat.BC7RGBAUnorm:
        case TextureFormat.BC7RGBAUnormSRGB:
        case TextureFormat.BC3RGBAUnorm:
        case TextureFormat.BC3RGBAUnormSRGB:
        case TextureFormat.BC2RGBAUnorm:
        case TextureFormat.BC2RGBAUnormSRGB:
        case TextureFormat.BC1RGBAUnorm:
        case TextureFormat.BC1RGBAUnormSRGB:
        case TextureFormat.RGBA16Uint:
        case TextureFormat.RGBA16Sint:
        case TextureFormat.RGBA16Float:
        case TextureFormat.RGBA32Uint:
        case TextureFormat.RGBA32Sint:
        case TextureFormat.RGBA32Float:
        case TextureFormat.ETC2RGB8A1Unorm:
        case TextureFormat.ETC2RGB8A1UnormSRGB:
        case TextureFormat.ETC2RGBA8Unorm:
        case TextureFormat.ETC2RGBA8UnormSRGB:
        case TextureFormat.ASTC4x4Unorm:
        case TextureFormat.ASTC4x4UnormSRGB:
        case TextureFormat.ASTC5x4Unorm:
        case TextureFormat.ASTC5x4UnormSRGB:
        case TextureFormat.ASTC5x5Unorm:
        case TextureFormat.ASTC5x5UnormSRGB:
        case TextureFormat.ASTC6x5Unorm:
        case TextureFormat.ASTC6x5UnormSRGB:
        case TextureFormat.ASTC6x6Unorm:
        case TextureFormat.ASTC6x6UnormSRGB:
        case TextureFormat.ASTC8x5Unorm:
        case TextureFormat.ASTC8x5UnormSRGB:
        case TextureFormat.ASTC8x6Unorm:
        case TextureFormat.ASTC8x6UnormSRGB:
        case TextureFormat.ASTC8x8Unorm:
        case TextureFormat.ASTC8x8UnormSRGB:
        case TextureFormat.ASTC10x5Unorm:
        case TextureFormat.ASTC10x5UnormSRGB:
        case TextureFormat.ASTC10x6Unorm:
        case TextureFormat.ASTC10x6UnormSRGB:
        case TextureFormat.ASTC10x8Unorm:
        case TextureFormat.ASTC10x8UnormSRGB:
        case TextureFormat.ASTC10x10Unorm:
        case TextureFormat.ASTC10x10UnormSRGB:
        case TextureFormat.ASTC12x10Unorm:
        case TextureFormat.ASTC12x10UnormSRGB:
        case TextureFormat.ASTC12x12Unorm:
        case TextureFormat.ASTC12x12UnormSRGB:
            return 4
        }
        throw "Unknown format " + e + "!"
    }
    ,
    i.prototype.invertYPreMultiplyAlpha = function(e, t, r, n, o, a, s, l, u, c, h) {
        var f, d, _, g, m, v, y;
        o === void 0 && (o = !1),
        a === void 0 && (a = !1),
        s === void 0 && (s = 0),
        l === void 0 && (l = 0),
        u === void 0 && (u = 1);
        var b = c === void 0
          , T = this._getPipeline(n, PipelineType.InvertYPremultiplyAlpha, {
            invertY: o,
            premultiplyAlpha: a
        })
          , C = T[0]
          , A = T[1];
        s = Math.max(s, 0),
        b && (c = this._device.createCommandEncoder({})),
        (d = (f = c).pushDebugGroup) === null || d === void 0 || d.call(f, "internal process texture - invertY=" + o + " premultiplyAlpha=" + a);
        var S;
        if (i._IsHardwareTexture(e) ? (S = e.underlyingResource,
        o && !a && u === 1 && s === 0 || (e = void 0)) : (S = e,
        e = void 0),
        !!S) {
            var P = e
              , R = (_ = P == null ? void 0 : P._copyInvertYTempTexture) !== null && _ !== void 0 ? _ : this.createTexture({
                width: t,
                height: r,
                layers: 1
            }, !1, !1, !1, !1, !1, n, 1, c, TextureUsage.CopySrc | TextureUsage.RenderAttachment | TextureUsage.TextureBinding)
              , M = (g = P == null ? void 0 : P._copyInvertYRenderPassDescr) !== null && g !== void 0 ? g : {
                colorAttachments: [{
                    view: R.createView({
                        format: n,
                        dimension: TextureViewDimension.E2d,
                        baseMipLevel: 0,
                        mipLevelCount: 1,
                        arrayLayerCount: 1,
                        baseArrayLayer: 0
                    }),
                    loadValue: LoadOp.Load,
                    storeOp: StoreOp.Store
                }]
            }
              , x = c.beginRenderPass(M)
              , I = (m = P == null ? void 0 : P._copyInvertYBindGroupd) !== null && m !== void 0 ? m : this._device.createBindGroup({
                layout: A,
                entries: [{
                    binding: 0,
                    resource: S.createView({
                        format: n,
                        dimension: TextureViewDimension.E2d,
                        baseMipLevel: l,
                        mipLevelCount: 1,
                        arrayLayerCount: u,
                        baseArrayLayer: s
                    })
                }]
            });
            x.setPipeline(C),
            x.setBindGroup(0, I),
            x.draw(4, 1, 0, 0),
            x.endPass(),
            c.copyTextureToTexture({
                texture: R
            }, {
                texture: S,
                mipLevel: l,
                origin: {
                    x: 0,
                    y: 0,
                    z: s
                }
            }, {
                width: t,
                height: r,
                depthOrArrayLayers: 1
            }),
            P ? (P._copyInvertYTempTexture = R,
            P._copyInvertYRenderPassDescr = M,
            P._copyInvertYBindGroupd = I) : this._deferredReleaseTextures.push([R, null]),
            (y = (v = c).popDebugGroup) === null || y === void 0 || y.call(v),
            b && (this._device.queue.submit([c.finish()]),
            c = null)
        }
    }
    ,
    i.prototype.copyWithInvertY = function(e, t, r, n) {
        var o, a, s, l, u = n === void 0, c = this._getPipeline(t, PipelineType.InvertYPremultiplyAlpha, {
            invertY: !0,
            premultiplyAlpha: !1
        }), h = c[0], f = c[1];
        u && (n = this._device.createCommandEncoder({})),
        (a = (o = n).pushDebugGroup) === null || a === void 0 || a.call(o, "internal copy texture with invertY");
        var d = n.beginRenderPass(r)
          , _ = this._device.createBindGroup({
            layout: f,
            entries: [{
                binding: 0,
                resource: e
            }]
        });
        d.setPipeline(h),
        d.setBindGroup(0, _),
        d.draw(4, 1, 0, 0),
        d.endPass(),
        (l = (s = n).popDebugGroup) === null || l === void 0 || l.call(s),
        u && (this._device.queue.submit([n.finish()]),
        n = null)
    }
    ,
    i.prototype.createTexture = function(e, t, r, n, o, a, s, l, u, c, h) {
        t === void 0 && (t = !1),
        r === void 0 && (r = !1),
        n === void 0 && (n = !1),
        o === void 0 && (o = !1),
        a === void 0 && (a = !1),
        s === void 0 && (s = TextureFormat.RGBA8Unorm),
        l === void 0 && (l = 1),
        c === void 0 && (c = -1),
        h === void 0 && (h = 0);
        var f = e.layers || 1
          , d = {
            width: e.width,
            height: e.height,
            depthOrArrayLayers: f
        }
          , _ = i.IsCompressedFormat(s)
          , g = t ? i.ComputeNumMipmapLevels(e.width, e.height) : 1
          , m = c >= 0 ? c : TextureUsage.CopySrc | TextureUsage.CopyDst | TextureUsage.TextureBinding;
        h |= t && !_ ? TextureUsage.CopySrc | TextureUsage.RenderAttachment : 0,
        _ || (h |= TextureUsage.RenderAttachment | TextureUsage.CopyDst);
        var v = this._device.createTexture({
            size: d,
            dimension: a ? TextureDimension.E3d : TextureDimension.E2d,
            format: s,
            usage: m | h,
            sampleCount: l,
            mipLevelCount: g
        });
        return i.IsImageBitmap(e) && (this.updateTexture(e, v, e.width, e.height, f, s, 0, 0, n, o, 0, 0, u),
        t && r && this.generateMipmaps(v, s, g, 0, u)),
        v
    }
    ,
    i.prototype.createCubeTexture = function(e, t, r, n, o, a, s, l, u, c) {
        t === void 0 && (t = !1),
        r === void 0 && (r = !1),
        n === void 0 && (n = !1),
        o === void 0 && (o = !1),
        a === void 0 && (a = TextureFormat.RGBA8Unorm),
        s === void 0 && (s = 1),
        u === void 0 && (u = -1),
        c === void 0 && (c = 0);
        var h = i.IsImageBitmapArray(e) ? e[0].width : e.width
          , f = i.IsImageBitmapArray(e) ? e[0].height : e.height
          , d = i.IsCompressedFormat(a)
          , _ = t ? i.ComputeNumMipmapLevels(h, f) : 1
          , g = u >= 0 ? u : TextureUsage.CopySrc | TextureUsage.CopyDst | TextureUsage.TextureBinding;
        c |= t && !d ? TextureUsage.CopySrc | TextureUsage.RenderAttachment : 0,
        d || (c |= TextureUsage.RenderAttachment | TextureUsage.CopyDst);
        var m = this._device.createTexture({
            size: {
                width: h,
                height: f,
                depthOrArrayLayers: 6
            },
            dimension: TextureDimension.E2d,
            format: a,
            usage: g | c,
            sampleCount: s,
            mipLevelCount: _
        });
        return i.IsImageBitmapArray(e) && (this.updateCubeTextures(e, m, h, f, a, n, o, 0, 0, l),
        t && r && this.generateCubeMipmaps(m, a, _, l)),
        m
    }
    ,
    i.prototype.generateCubeMipmaps = function(e, t, r, n) {
        var o, a, s, l, u = n === void 0;
        u && (n = this._device.createCommandEncoder({})),
        (a = (o = n).pushDebugGroup) === null || a === void 0 || a.call(o, "create cube mipmaps - " + r + " levels");
        for (var c = 0; c < 6; ++c)
            this.generateMipmaps(e, t, r, c, n);
        (l = (s = n).popDebugGroup) === null || l === void 0 || l.call(s),
        u && (this._device.queue.submit([n.finish()]),
        n = null)
    }
    ,
    i.prototype.generateMipmaps = function(e, t, r, n, o) {
        var a, s, l, u, c, h, f, d;
        n === void 0 && (n = 0);
        var _ = o === void 0
          , g = this._getPipeline(t)
          , m = g[0]
          , v = g[1];
        n = Math.max(n, 0),
        _ && (o = this._device.createCommandEncoder({})),
        (s = (a = o).pushDebugGroup) === null || s === void 0 || s.call(a, "create mipmaps for face #" + n + " - " + r + " levels");
        var y;
        if (i._IsHardwareTexture(e) ? (y = e.underlyingResource,
        e._mipmapGenRenderPassDescr = e._mipmapGenRenderPassDescr || [],
        e._mipmapGenBindGroup = e._mipmapGenBindGroup || []) : (y = e,
        e = void 0),
        !!y) {
            for (var b = e, T = 1; T < r; ++T) {
                var C = (u = (l = b == null ? void 0 : b._mipmapGenRenderPassDescr[n]) === null || l === void 0 ? void 0 : l[T - 1]) !== null && u !== void 0 ? u : {
                    colorAttachments: [{
                        view: y.createView({
                            format: t,
                            dimension: TextureViewDimension.E2d,
                            baseMipLevel: T,
                            mipLevelCount: 1,
                            arrayLayerCount: 1,
                            baseArrayLayer: n
                        }),
                        loadValue: LoadOp.Load,
                        storeOp: StoreOp.Store
                    }]
                };
                b && (b._mipmapGenRenderPassDescr[n] = b._mipmapGenRenderPassDescr[n] || [],
                b._mipmapGenRenderPassDescr[n][T - 1] = C);
                var A = o.beginRenderPass(C)
                  , S = (h = (c = b == null ? void 0 : b._mipmapGenBindGroup[n]) === null || c === void 0 ? void 0 : c[T - 1]) !== null && h !== void 0 ? h : this._device.createBindGroup({
                    layout: v,
                    entries: [{
                        binding: 0,
                        resource: this._mipmapSampler
                    }, {
                        binding: 1,
                        resource: y.createView({
                            format: t,
                            dimension: TextureViewDimension.E2d,
                            baseMipLevel: T - 1,
                            mipLevelCount: 1,
                            arrayLayerCount: 1,
                            baseArrayLayer: n
                        })
                    }]
                });
                b && (b._mipmapGenBindGroup[n] = b._mipmapGenBindGroup[n] || [],
                b._mipmapGenBindGroup[n][T - 1] = S),
                A.setPipeline(m),
                A.setBindGroup(0, S),
                A.draw(4, 1, 0, 0),
                A.endPass()
            }
            (d = (f = o).popDebugGroup) === null || d === void 0 || d.call(f),
            _ && (this._device.queue.submit([o.finish()]),
            o = null)
        }
    }
    ,
    i.prototype.createGPUTextureForInternalTexture = function(e, t, r, n, o) {
        e._hardwareTexture || (e._hardwareTexture = new WebGPUHardwareTexture),
        t === void 0 && (t = e.width),
        r === void 0 && (r = e.height),
        n === void 0 && (n = e.depth);
        var a = e._hardwareTexture;
        a.format = i.GetWebGPUTextureFormat(e.type, e.format, e._useSRGBBuffer),
        a.textureUsages = e._source === InternalTextureSource.RenderTarget || e.source === InternalTextureSource.MultiRenderTarget ? TextureUsage.TextureBinding | TextureUsage.CopySrc | TextureUsage.RenderAttachment : e._source === InternalTextureSource.DepthStencil ? TextureUsage.TextureBinding | TextureUsage.RenderAttachment : -1,
        a.textureAdditionalUsages = (o != null ? o : 0) & 1 ? TextureUsage.StorageBinding : 0;
        var s = e.generateMipMaps
          , l = n || 1;
        if (e.isCube) {
            var u = this.createCubeTexture({
                width: t,
                height: r
            }, e.generateMipMaps, e.generateMipMaps, e.invertY, !1, a.format, 1, this._commandEncoderForCreation, a.textureUsages, a.textureAdditionalUsages);
            a.set(u),
            a.createView({
                format: a.format,
                dimension: TextureViewDimension.Cube,
                mipLevelCount: s ? i.ComputeNumMipmapLevels(t, r) : 1,
                baseArrayLayer: 0,
                baseMipLevel: 0,
                arrayLayerCount: 6,
                aspect: TextureAspect.All
            })
        } else {
            var u = this.createTexture({
                width: t,
                height: r,
                layers: l
            }, e.generateMipMaps, e.generateMipMaps, e.invertY, !1, e.is3D, a.format, 1, this._commandEncoderForCreation, a.textureUsages, a.textureAdditionalUsages);
            a.set(u),
            a.createView({
                format: a.format,
                dimension: e.is2DArray ? TextureViewDimension.E2dArray : e.is3D ? TextureDimension.E3d : TextureViewDimension.E2d,
                mipLevelCount: s ? i.ComputeNumMipmapLevels(t, r) : 1,
                baseArrayLayer: 0,
                baseMipLevel: 0,
                arrayLayerCount: e.is3D ? 1 : l,
                aspect: TextureAspect.All
            })
        }
        return e.width = e.baseWidth = t,
        e.height = e.baseHeight = r,
        e.depth = e.baseDepth = n,
        this.createMSAATexture(e, e.samples),
        a
    }
    ,
    i.prototype.createMSAATexture = function(e, t) {
        var r = e._hardwareTexture;
        if (r != null && r.msaaTexture && (this.releaseTexture(r.msaaTexture),
        r.msaaTexture = null),
        !(!r || (t != null ? t : 1) <= 1)) {
            var n = e.width
              , o = e.height
              , a = e.depth || 1;
            if (e.isCube) {
                var s = this.createCubeTexture({
                    width: n,
                    height: o
                }, !1, !1, e.invertY, !1, r.format, t, this._commandEncoderForCreation, r.textureUsages, r.textureAdditionalUsages);
                r.setMSAATexture(s)
            } else {
                var s = this.createTexture({
                    width: n,
                    height: o,
                    layers: a
                }, !1, !1, e.invertY, !1, e.is3D, r.format, t, this._commandEncoderForCreation, r.textureUsages, r.textureAdditionalUsages);
                r.setMSAATexture(s)
            }
        }
    }
    ,
    i.prototype.updateCubeTextures = function(e, t, r, n, o, a, s, l, u, c) {
        a === void 0 && (a = !1),
        s === void 0 && (s = !1),
        l === void 0 && (l = 0),
        u === void 0 && (u = 0);
        for (var h = [0, 3, 1, 4, 2, 5], f = 0; f < h.length; ++f) {
            var d = e[h[f]];
            this.updateTexture(d, t, r, n, 1, o, f, 0, a, s, l, u, c)
        }
    }
    ,
    i.prototype.updateTexture = function(e, t, r, n, o, a, s, l, u, c, h, f, d, _) {
        s === void 0 && (s = 0),
        l === void 0 && (l = 0),
        u === void 0 && (u = !1),
        c === void 0 && (c = !1),
        h === void 0 && (h = 0),
        f === void 0 && (f = 0);
        var g = i._IsInternalTexture(t) ? t._hardwareTexture.underlyingResource : t
          , m = i._GetBlockInformationFromFormat(a)
          , v = i._IsInternalTexture(t) ? t._hardwareTexture : t
          , y = {
            texture: g,
            origin: {
                x: h,
                y: f,
                z: Math.max(s, 0)
            },
            mipLevel: l,
            premultipliedAlpha: c
        }
          , b = {
            width: Math.ceil(r / m.width) * m.width,
            height: Math.ceil(n / m.height) * m.height,
            depthOrArrayLayers: o || 1
        };
        if (e.byteLength !== void 0) {
            e = e;
            var T = Math.ceil(r / m.width) * m.length
              , C = Math.ceil(T / 256) * 256 === T;
            if (C) {
                var A = d === void 0;
                A && (d = this._device.createCommandEncoder({}));
                var S = this._bufferManager.createRawBuffer(e.byteLength, BufferUsage.MapWrite | BufferUsage.CopySrc, !0)
                  , P = S.getMappedRange();
                new Uint8Array(P).set(e),
                S.unmap(),
                d.copyBufferToTexture({
                    buffer: S,
                    offset: 0,
                    bytesPerRow: T,
                    rowsPerImage: n
                }, y, b),
                A && (this._device.queue.submit([d.finish()]),
                d = null),
                this._bufferManager.releaseBuffer(S)
            } else
                this._device.queue.writeTexture(y, e, {
                    offset: 0,
                    bytesPerRow: T,
                    rowsPerImage: n
                }, b);
            (u || c) && this.invertYPreMultiplyAlpha(v, r, n, a, u, c, s, l, o || 1, d, _)
        } else if (e = e,
        u)
            if (y.premultipliedAlpha = !1,
            i._IsInternalTexture(t) && h === 0 && f === 0 && r === t.width && n === t.height)
                this._device.queue.copyExternalImageToTexture({
                    source: e
                }, y, b),
                this.invertYPreMultiplyAlpha(v, r, n, a, u, c, s, l, o || 1, void 0, _);
            else {
                d = this._device.createCommandEncoder({});
                var R = this.createTexture({
                    width: r,
                    height: n,
                    layers: 1
                }, !1, !1, !1, !1, !1, a, 1, d, TextureUsage.CopySrc | TextureUsage.TextureBinding);
                this._deferredReleaseTextures.push([R, null]),
                b.depthOrArrayLayers = 1,
                this._device.queue.copyExternalImageToTexture({
                    source: e
                }, {
                    texture: R
                }, b),
                b.depthOrArrayLayers = o || 1,
                this.invertYPreMultiplyAlpha(R, r, n, a, u, c, s, l, o || 1, d, _),
                d.copyTextureToTexture({
                    texture: R
                }, y, b),
                this._device.queue.submit([d.finish()]),
                d = null
            }
        else
            this._device.queue.copyExternalImageToTexture({
                source: e
            }, y, b)
    }
    ,
    i.prototype.readPixels = function(e, t, r, n, o, a, s, l, u, c) {
        s === void 0 && (s = 0),
        l === void 0 && (l = 0),
        u === void 0 && (u = null),
        c === void 0 && (c = !1);
        var h = i._GetBlockInformationFromFormat(a)
          , f = Math.ceil(n / h.width) * h.length
          , d = Math.ceil(f / 256) * 256
          , _ = d * o
          , g = this._bufferManager.createRawBuffer(_, BufferUsage.MapRead | BufferUsage.CopyDst)
          , m = this._device.createCommandEncoder({});
        return m.copyTextureToBuffer({
            texture: e,
            mipLevel: l,
            origin: {
                x: t,
                y: r,
                z: Math.max(s, 0)
            }
        }, {
            buffer: g,
            offset: 0,
            bytesPerRow: d
        }, {
            width: n,
            height: o,
            depthOrArrayLayers: 1
        }),
        this._device.queue.submit([m.finish()]),
        this._bufferManager.readDataFromBuffer(g, _, n, o, f, d, i._GetTextureTypeFromFormat(a), 0, u, !0, c)
    }
    ,
    i.prototype.releaseTexture = function(e) {
        if (i._IsInternalTexture(e)) {
            var t = e._hardwareTexture
              , r = e._irradianceTexture;
            this._deferredReleaseTextures.push([t, r])
        } else
            this._deferredReleaseTextures.push([e, null])
    }
    ,
    i.prototype.destroyDeferredTextures = function() {
        for (var e = 0; e < this._deferredReleaseTextures.length; ++e) {
            var t = this._deferredReleaseTextures[e]
              , r = t[0]
              , n = t[1];
            r && (i._IsHardwareTexture(r) ? r.release() : r.destroy()),
            n == null || n.dispose()
        }
        this._deferredReleaseTextures.length = 0
    }
    ,
    i
}(), WebGPUDataBuffer = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this) || this;
        return r._buffer = t,
        r
    }
    return Object.defineProperty(e.prototype, "underlyingResource", {
        get: function() {
            return this._buffer
        },
        enumerable: !1,
        configurable: !0
    }),
    e
}(DataBuffer), WebGPUBufferManager = function() {
    function i(e) {
        this._deferredReleaseBuffers = [],
        this._device = e
    }
    return i._IsGPUBuffer = function(e) {
        return e.underlyingResource === void 0
    }
    ,
    i.prototype.createRawBuffer = function(e, t, r) {
        r === void 0 && (r = !1);
        var n = e.byteLength !== void 0 ? e.byteLength + 3 & -4 : e + 3 & -4
          , o = {
            mappedAtCreation: r,
            size: n,
            usage: t
        };
        return this._device.createBuffer(o)
    }
    ,
    i.prototype.createBuffer = function(e, t) {
        var r = e.byteLength !== void 0
          , n = this.createRawBuffer(e, t)
          , o = new WebGPUDataBuffer(n);
        return o.references = 1,
        o.capacity = r ? e.byteLength : e,
        r && this.setSubData(o, 0, e),
        o
    }
    ,
    i.prototype.setRawData = function(e, t, r, n, o) {
        this._device.queue.writeBuffer(e, t, r.buffer, n, o)
    }
    ,
    i.prototype.setSubData = function(e, t, r, n, o) {
        n === void 0 && (n = 0),
        o === void 0 && (o = 0);
        var a = e.underlyingResource;
        o = o || r.byteLength,
        o = Math.min(o, e.capacity - t);
        var s = r.byteOffset + n
          , l = s + o
          , u = o + 3 & -4;
        if (u !== o) {
            var c = new Uint8Array(r.buffer.slice(s, l));
            r = new Uint8Array(u),
            r.set(c),
            n = 0,
            s = 0,
            l = u,
            o = u
        }
        for (var h = 1024 * 1024 * 15, f = 0; l - (s + f) > h; )
            this._device.queue.writeBuffer(a, t + f, r.buffer, s + f, h),
            f += h;
        this._device.queue.writeBuffer(a, t + f, r.buffer, s + f, o - f)
    }
    ,
    i.prototype._GetHalfFloatAsFloatRGBAArrayBuffer = function(e, t, r) {
        r || (r = new Float32Array(e));
        for (var n = new Uint16Array(t); e--; )
            r[e] = FromHalfFloat(n[e]);
        return r
    }
    ,
    i.prototype.readDataFromBuffer = function(e, t, r, n, o, a, s, l, u, c, h) {
        var f = this;
        s === void 0 && (s = 0),
        l === void 0 && (l = 0),
        u === void 0 && (u = null),
        c === void 0 && (c = !0),
        h === void 0 && (h = !1);
        var d = s === 1 ? 2 : s === 2 ? 1 : 0;
        return new Promise(function(_, g) {
            e.mapAsync(MapMode.Read, l, t).then(function() {
                var m = e.getMappedRange(l, t)
                  , v = u;
                if (h)
                    v === null ? v = allocateAndCopyTypedBuffer(s, t, !0, m) : v = allocateAndCopyTypedBuffer(s, v.buffer, void 0, m);
                else if (v === null)
                    switch (d) {
                    case 0:
                        v = new Uint8Array(t),
                        v.set(new Uint8Array(m));
                        break;
                    case 1:
                        v = f._GetHalfFloatAsFloatRGBAArrayBuffer(t / 2, m);
                        break;
                    case 2:
                        v = new Float32Array(t / 4),
                        v.set(new Float32Array(m));
                        break
                    }
                else
                    switch (d) {
                    case 0:
                        v = new Uint8Array(v.buffer),
                        v.set(new Uint8Array(m));
                        break;
                    case 1:
                        v = f._GetHalfFloatAsFloatRGBAArrayBuffer(t / 2, m, u);
                        break;
                    case 2:
                        v = new Float32Array(v.buffer),
                        v.set(new Float32Array(m));
                        break
                    }
                if (o !== a) {
                    d === 1 && !h && (o *= 2,
                    a *= 2);
                    for (var y = new Uint8Array(v.buffer), b = o, T = 0, C = 1; C < n; ++C) {
                        T = C * a;
                        for (var A = 0; A < o; ++A)
                            y[b++] = y[T++]
                    }
                    d !== 0 && !h ? v = new Float32Array(y.buffer,0,b / 4) : v = new Uint8Array(y.buffer,0,b)
                }
                e.unmap(),
                c && f.releaseBuffer(e),
                _(v)
            }, function(m) {
                return g(m)
            })
        }
        )
    }
    ,
    i.prototype.releaseBuffer = function(e) {
        return i._IsGPUBuffer(e) ? (this._deferredReleaseBuffers.push(e),
        !0) : (e.references--,
        e.references === 0 ? (this._deferredReleaseBuffers.push(e.underlyingResource),
        !0) : !1)
    }
    ,
    i.prototype.destroyDeferredBuffers = function() {
        for (var e = 0; e < this._deferredReleaseBuffers.length; ++e)
            this._deferredReleaseBuffers[e].destroy();
        this._deferredReleaseBuffers.length = 0
    }
    ,
    i
}(), WebGPURenderPassWrapper = function() {
    function i() {
        this.colorAttachmentGPUTextures = [],
        this.reset()
    }
    return i.prototype.reset = function(e) {
        e === void 0 && (e = !1),
        this.renderPass = null,
        e && (this.renderPassDescriptor = null,
        this.colorAttachmentViewDescriptor = null,
        this.depthAttachmentViewDescriptor = null,
        this.colorAttachmentGPUTextures = [],
        this.depthTextureFormat = void 0)
    }
    ,
    i
}(), filterToBits = [0 | 0 << 1 | 0 << 2, 0 | 0 << 1 | 0 << 2, 1 | 1 << 1 | 0 << 2, 1 | 1 << 1 | 1 << 2, 0 | 0 << 1 | 0 << 2, 0 | 1 << 1 | 0 << 2, 0 | 1 << 1 | 1 << 2, 0 | 1 << 1 | 0 << 2, 0 | 0 << 1 | 1 << 2, 1 | 0 << 1 | 0 << 2, 1 | 0 << 1 | 1 << 2, 1 | 1 << 1 | 0 << 2, 1 | 0 << 1 | 0 << 2], comparisonFunctionToBits = [0 << 3 | 0 << 4 | 0 << 5 | 0 << 6, 0 << 3 | 0 << 4 | 0 << 5 | 1 << 6, 0 << 3 | 0 << 4 | 1 << 5 | 0 << 6, 0 << 3 | 0 << 4 | 1 << 5 | 1 << 6, 0 << 3 | 1 << 4 | 0 << 5 | 0 << 6, 0 << 3 | 1 << 4 | 0 << 5 | 1 << 6, 0 << 3 | 1 << 4 | 1 << 5 | 0 << 6, 0 << 3 | 1 << 4 | 1 << 5 | 1 << 6, 1 << 3 | 0 << 4 | 0 << 5 | 0 << 6], filterNoMipToBits = [0 << 7, 1 << 7, 1 << 7, 0 << 7, 0 << 7, 0 << 7, 0 << 7, 1 << 7, 0 << 7, 0 << 7, 0 << 7, 0 << 7, 1 << 7], WebGPUCacheSampler = function() {
    function i(e) {
        this._samplers = {},
        this._device = e,
        this.disabled = !1
    }
    return i.GetSamplerHashCode = function(e) {
        var t, r, n, o = e._cachedAnisotropicFilteringLevel && e._cachedAnisotropicFilteringLevel > 1 ? 4 : 1, a = filterToBits[e.samplingMode] + comparisonFunctionToBits[(e._comparisonFunction || 514) - 512 + 1] + filterNoMipToBits[e.samplingMode] + (((t = e._cachedWrapU) !== null && t !== void 0 ? t : 1) << 8) + (((r = e._cachedWrapV) !== null && r !== void 0 ? r : 1) << 10) + (((n = e._cachedWrapR) !== null && n !== void 0 ? n : 1) << 12) + ((e.useMipMaps ? 1 : 0) << 14) + (o << 15);
        return a
    }
    ,
    i._GetSamplerFilterDescriptor = function(e, t) {
        var r, n, o, a, s, l = e.useMipMaps;
        switch (e.samplingMode) {
        case 11:
            r = FilterMode.Linear,
            n = FilterMode.Linear,
            o = FilterMode.Nearest,
            l || (a = s = 0);
            break;
        case 3:
        case 3:
            r = FilterMode.Linear,
            n = FilterMode.Linear,
            l ? o = FilterMode.Linear : (o = FilterMode.Nearest,
            a = s = 0);
            break;
        case 8:
            r = FilterMode.Nearest,
            n = FilterMode.Nearest,
            l ? o = FilterMode.Linear : (o = FilterMode.Nearest,
            a = s = 0);
            break;
        case 4:
            r = FilterMode.Nearest,
            n = FilterMode.Nearest,
            o = FilterMode.Nearest,
            l || (a = s = 0);
            break;
        case 5:
            r = FilterMode.Nearest,
            n = FilterMode.Linear,
            o = FilterMode.Nearest,
            l || (a = s = 0);
            break;
        case 6:
            r = FilterMode.Nearest,
            n = FilterMode.Linear,
            l ? o = FilterMode.Linear : (o = FilterMode.Nearest,
            a = s = 0);
            break;
        case 7:
            r = FilterMode.Nearest,
            n = FilterMode.Linear,
            o = FilterMode.Nearest,
            a = s = 0;
            break;
        case 1:
        case 1:
            r = FilterMode.Nearest,
            n = FilterMode.Nearest,
            o = FilterMode.Nearest,
            a = s = 0;
            break;
        case 9:
            r = FilterMode.Linear,
            n = FilterMode.Nearest,
            o = FilterMode.Nearest,
            l || (a = s = 0);
            break;
        case 10:
            r = FilterMode.Linear,
            n = FilterMode.Nearest,
            l ? o = FilterMode.Linear : (o = FilterMode.Nearest,
            a = s = 0);
            break;
        case 2:
        case 2:
            r = FilterMode.Linear,
            n = FilterMode.Linear,
            o = FilterMode.Nearest,
            a = s = 0;
            break;
        case 12:
            r = FilterMode.Linear,
            n = FilterMode.Nearest,
            o = FilterMode.Nearest,
            a = s = 0;
            break;
        default:
            r = FilterMode.Nearest,
            n = FilterMode.Nearest,
            o = FilterMode.Nearest,
            a = s = 0;
            break
        }
        return t > 1 && (a !== 0 || s !== 0) ? {
            magFilter: FilterMode.Linear,
            minFilter: FilterMode.Linear,
            mipmapFilter: FilterMode.Linear,
            anisotropyEnabled: !0
        } : {
            magFilter: r,
            minFilter: n,
            mipmapFilter: o,
            lodMinClamp: a,
            lodMaxClamp: s
        }
    }
    ,
    i._GetWrappingMode = function(e) {
        switch (e) {
        case 1:
            return AddressMode.Repeat;
        case 0:
            return AddressMode.ClampToEdge;
        case 2:
            return AddressMode.MirrorRepeat
        }
        return AddressMode.Repeat
    }
    ,
    i._GetSamplerWrappingDescriptor = function(e) {
        return {
            addressModeU: this._GetWrappingMode(e._cachedWrapU),
            addressModeV: this._GetWrappingMode(e._cachedWrapV),
            addressModeW: this._GetWrappingMode(e._cachedWrapR)
        }
    }
    ,
    i._GetSamplerDescriptor = function(e) {
        var t = e.useMipMaps && e._cachedAnisotropicFilteringLevel && e._cachedAnisotropicFilteringLevel > 1 ? 4 : 1
          , r = this._GetSamplerFilterDescriptor(e, t);
        return __assign(__assign(__assign({}, r), this._GetSamplerWrappingDescriptor(e)), {
            compare: e._comparisonFunction ? WebGPUTextureHelper.GetCompareFunction(e._comparisonFunction) : void 0,
            maxAnisotropy: r.anisotropyEnabled ? t : 1
        })
    }
    ,
    i.prototype.getSampler = function(e, t, r) {
        if (t === void 0 && (t = !1),
        r === void 0 && (r = 0),
        this.disabled)
            return this._device.createSampler(i._GetSamplerDescriptor(e));
        t ? r = 0 : r === 0 && (r = i.GetSamplerHashCode(e));
        var n = t ? void 0 : this._samplers[r];
        return n || (n = this._device.createSampler(i._GetSamplerDescriptor(e)),
        t || (this._samplers[r] = n)),
        n
    }
    ,
    i
}(), StatePosition;
(function(i) {
    i[i.StencilReadMask = 0] = "StencilReadMask",
    i[i.StencilWriteMask = 1] = "StencilWriteMask",
    i[i.DepthBias = 2] = "DepthBias",
    i[i.DepthBiasSlopeScale = 3] = "DepthBiasSlopeScale",
    i[i.MRTAttachments1 = 4] = "MRTAttachments1",
    i[i.MRTAttachments2 = 5] = "MRTAttachments2",
    i[i.DepthStencilState = 6] = "DepthStencilState",
    i[i.RasterizationState = 7] = "RasterizationState",
    i[i.ColorStates = 8] = "ColorStates",
    i[i.ShaderStage = 9] = "ShaderStage",
    i[i.TextureStage = 10] = "TextureStage",
    i[i.VertexState = 11] = "VertexState",
    i[i.NumStates = 12] = "NumStates"
}
)(StatePosition || (StatePosition = {}));
var textureFormatToIndex = {
    "": 0,
    r8unorm: 1,
    r8uint: 2,
    r8sint: 3,
    r16uint: 4,
    r16sint: 5,
    r16float: 6,
    rg8unorm: 7,
    rg8uint: 8,
    rg8sint: 9,
    r32uint: 10,
    r32sint: 11,
    r32float: 12,
    rg16uint: 13,
    rg16sint: 14,
    rg16float: 15,
    rgba8unorm: 16,
    "rgba8unorm-srgb": 17,
    rgba8uint: 18,
    rgba8sint: 19,
    bgra8unorm: 20,
    "bgra8unorm-srgb": 21,
    rgb10a2unorm: 22,
    rg32uint: 23,
    rg32sint: 24,
    rg32float: 25,
    rgba16uint: 26,
    rgba16sint: 27,
    rgba16float: 28,
    rgba32uint: 29,
    rgba32sint: 30,
    rgba32float: 31,
    stencil8: 32,
    depth16unorm: 33,
    depth24plus: 34,
    "depth24plus-stencil8": 35,
    depth32float: 36,
    "depth24unorm-stencil8": 37,
    "depth32float-stencil8": 38
}
  , alphaBlendFactorToIndex = {
    0: 1,
    1: 2,
    768: 3,
    769: 4,
    770: 5,
    771: 6,
    772: 7,
    773: 8,
    774: 9,
    775: 10,
    776: 11,
    32769: 12,
    32770: 13,
    32771: 12,
    32772: 13
}
  , stencilOpToIndex = {
    0: 0,
    7680: 1,
    7681: 2,
    7682: 3,
    7683: 4,
    5386: 5,
    34055: 6,
    34056: 7
}
  , WebGPUCacheRenderPipeline = function() {
    function i(e, t, r) {
        this._device = e,
        this._useTextureStage = r,
        this._states = new Array(30),
        this._statesLength = 0,
        this._stateDirtyLowestIndex = 0,
        this._emptyVertexBuffer = t,
        this._mrtFormats = [],
        this._parameter = {
            token: void 0,
            pipeline: null
        },
        this.disabled = !1,
        this.vertexBuffers = [],
        this._kMaxVertexBufferStride = e.limits.maxVertexBufferArrayStride || 2048,
        this.reset()
    }
    return i.prototype.reset = function() {
        this._isDirty = !0,
        this.vertexBuffers.length = 0,
        this.setAlphaToCoverage(!1),
        this.resetDepthCullingState(),
        this.setClampDepth(!1),
        this.setDepthBias(0),
        this._webgpuColorFormat = [TextureFormat.BGRA8Unorm],
        this.setColorFormat(TextureFormat.BGRA8Unorm),
        this.setMRTAttachments([], []),
        this.setAlphaBlendEnabled(!1),
        this.setAlphaBlendFactors([null, null, null, null], [null, null]),
        this.setWriteMask(15),
        this.setDepthStencilFormat(TextureFormat.Depth24PlusStencil8),
        this.setStencilEnabled(!1),
        this.resetStencilState(),
        this.setBuffers(null, null, null),
        this._setTextureState(0)
    }
    ,
    Object.defineProperty(i.prototype, "colorFormats", {
        get: function() {
            return this._mrtAttachments1 > 0 ? this._mrtFormats : this._webgpuColorFormat
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.getRenderPipeline = function(e, t, r, n) {
        if (n === void 0 && (n = 0),
        this.disabled) {
            var o = i._GetTopology(e);
            return this._setVertexState(t),
            this._parameter.pipeline = this._createRenderPipeline(t, o, r),
            i.NumCacheMiss++,
            i._NumPipelineCreationCurrentFrame++,
            this._parameter.pipeline
        }
        if (this._setShaderStage(t.uniqueId),
        this._setRasterizationState(e, r),
        this._setColorStates(),
        this._setDepthStencilState(),
        this._setVertexState(t),
        this._setTextureState(n),
        this.lastStateDirtyLowestIndex = this._stateDirtyLowestIndex,
        !this._isDirty && this._parameter.pipeline)
            return this._stateDirtyLowestIndex = this._statesLength,
            i.NumCacheHitWithoutHash++,
            this._parameter.pipeline;
        if (this._getRenderPipeline(this._parameter),
        this._isDirty = !1,
        this._stateDirtyLowestIndex = this._statesLength,
        this._parameter.pipeline)
            return i.NumCacheHitWithHash++,
            this._parameter.pipeline;
        var a = i._GetTopology(e);
        return this._parameter.pipeline = this._createRenderPipeline(t, a, r),
        this._setRenderPipeline(this._parameter),
        i.NumCacheMiss++,
        i._NumPipelineCreationCurrentFrame++,
        this._parameter.pipeline
    }
    ,
    i.prototype.endFrame = function() {
        i.NumPipelineCreationLastFrame = i._NumPipelineCreationCurrentFrame,
        i._NumPipelineCreationCurrentFrame = 0
    }
    ,
    i.prototype.setAlphaToCoverage = function(e) {
        this._alphaToCoverageEnabled = e
    }
    ,
    i.prototype.setFrontFace = function(e) {
        this._frontFace = e
    }
    ,
    i.prototype.setCullEnabled = function(e) {
        this._cullEnabled = e
    }
    ,
    i.prototype.setCullFace = function(e) {
        this._cullFace = e
    }
    ,
    i.prototype.setClampDepth = function(e) {
        this._clampDepth = e
    }
    ,
    i.prototype.resetDepthCullingState = function() {
        this.setDepthCullingState(!1, 2, 1, 0, 0, !0, !0, 519)
    }
    ,
    i.prototype.setDepthCullingState = function(e, t, r, n, o, a, s, l) {
        this._depthWriteEnabled = s,
        this._depthTestEnabled = a,
        this._depthCompare = (l != null ? l : 519) - 512,
        this._cullFace = r,
        this._cullEnabled = e,
        this._frontFace = t,
        this.setDepthBiasSlopeScale(n),
        this.setDepthBias(o)
    }
    ,
    i.prototype.setDepthBias = function(e) {
        this._depthBias !== e && (this._depthBias = e,
        this._states[StatePosition.DepthBias] = e,
        this._isDirty = !0,
        this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.DepthBias))
    }
    ,
    i.prototype.setDepthBiasSlopeScale = function(e) {
        this._depthBiasSlopeScale !== e && (this._depthBiasSlopeScale = e,
        this._states[StatePosition.DepthBiasSlopeScale] = e,
        this._isDirty = !0,
        this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.DepthBiasSlopeScale))
    }
    ,
    i.prototype.setColorFormat = function(e) {
        this._webgpuColorFormat[0] = e,
        this._colorFormat = textureFormatToIndex[e]
    }
    ,
    i.prototype.setMRTAttachments = function(e, t) {
        var r;
        if (e.length > 10)
            throw "Can't handle more than 10 attachments for a MRT in cache render pipeline!";
        this.mrtAttachments = e,
        this.mrtTextureArray = t;
        for (var n = [0, 0], o = 0, a = 0, s = 0, l = 0; l < e.length; ++l) {
            var u = e[l];
            if (u !== 0) {
                var c = t[u - 1]
                  , h = c == null ? void 0 : c._hardwareTexture;
                this._mrtFormats[s] = (r = h == null ? void 0 : h.format) !== null && r !== void 0 ? r : this._webgpuColorFormat[0],
                n[o] += textureFormatToIndex[this._mrtFormats[s]] << a,
                a += 6,
                s++,
                a >= 32 && (a = 0,
                o++)
            }
        }
        this._mrtFormats.length = s,
        (this._mrtAttachments1 !== n[0] || this._mrtAttachments2 !== n[1]) && (this._mrtAttachments1 = n[0],
        this._mrtAttachments2 = n[1],
        this._states[StatePosition.MRTAttachments1] = n[0],
        this._states[StatePosition.MRTAttachments2] = n[1],
        this._isDirty = !0,
        this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.MRTAttachments1))
    }
    ,
    i.prototype.setAlphaBlendEnabled = function(e) {
        this._alphaBlendEnabled = e
    }
    ,
    i.prototype.setAlphaBlendFactors = function(e, t) {
        this._alphaBlendFuncParams = e,
        this._alphaBlendEqParams = t
    }
    ,
    i.prototype.setWriteMask = function(e) {
        this._writeMask = e
    }
    ,
    i.prototype.setDepthStencilFormat = function(e) {
        this._webgpuDepthStencilFormat = e,
        this._depthStencilFormat = e === void 0 ? 0 : textureFormatToIndex[e]
    }
    ,
    i.prototype.setDepthTestEnabled = function(e) {
        this._depthTestEnabled = e
    }
    ,
    i.prototype.setDepthWriteEnabled = function(e) {
        this._depthWriteEnabled = e
    }
    ,
    i.prototype.setDepthCompare = function(e) {
        this._depthCompare = (e != null ? e : 519) - 512
    }
    ,
    i.prototype.setStencilEnabled = function(e) {
        this._stencilEnabled = e
    }
    ,
    i.prototype.setStencilCompare = function(e) {
        this._stencilFrontCompare = (e != null ? e : 519) - 512
    }
    ,
    i.prototype.setStencilDepthFailOp = function(e) {
        this._stencilFrontDepthFailOp = e === null ? 1 : stencilOpToIndex[e]
    }
    ,
    i.prototype.setStencilPassOp = function(e) {
        this._stencilFrontPassOp = e === null ? 2 : stencilOpToIndex[e]
    }
    ,
    i.prototype.setStencilFailOp = function(e) {
        this._stencilFrontFailOp = e === null ? 1 : stencilOpToIndex[e]
    }
    ,
    i.prototype.setStencilReadMask = function(e) {
        this._stencilReadMask !== e && (this._stencilReadMask = e,
        this._states[StatePosition.StencilReadMask] = e,
        this._isDirty = !0,
        this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.StencilReadMask))
    }
    ,
    i.prototype.setStencilWriteMask = function(e) {
        this._stencilWriteMask !== e && (this._stencilWriteMask = e,
        this._states[StatePosition.StencilWriteMask] = e,
        this._isDirty = !0,
        this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.StencilWriteMask))
    }
    ,
    i.prototype.resetStencilState = function() {
        this.setStencilState(!1, 519, 7680, 7681, 7680, 255, 255)
    }
    ,
    i.prototype.setStencilState = function(e, t, r, n, o, a, s) {
        this._stencilEnabled = e,
        this._stencilFrontCompare = (t != null ? t : 519) - 512,
        this._stencilFrontDepthFailOp = r === null ? 1 : stencilOpToIndex[r],
        this._stencilFrontPassOp = n === null ? 2 : stencilOpToIndex[n],
        this._stencilFrontFailOp = o === null ? 1 : stencilOpToIndex[o],
        this.setStencilReadMask(a),
        this.setStencilWriteMask(s)
    }
    ,
    i.prototype.setBuffers = function(e, t, r) {
        this._vertexBuffers = e,
        this._overrideVertexBuffers = r,
        this._indexBuffer = t
    }
    ,
    i._GetTopology = function(e) {
        switch (e) {
        case 0:
            return PrimitiveTopology.TriangleList;
        case 2:
            return PrimitiveTopology.PointList;
        case 1:
            return PrimitiveTopology.LineList;
        case 3:
            return PrimitiveTopology.PointList;
        case 4:
            return PrimitiveTopology.LineList;
        case 5:
            throw "LineLoop is an unsupported fillmode in WebGPU";
        case 6:
            return PrimitiveTopology.LineStrip;
        case 7:
            return PrimitiveTopology.TriangleStrip;
        case 8:
            throw "TriangleFan is an unsupported fillmode in WebGPU";
        default:
            return PrimitiveTopology.TriangleList
        }
    }
    ,
    i._GetAphaBlendOperation = function(e) {
        switch (e) {
        case 32774:
            return BlendOperation.Add;
        case 32778:
            return BlendOperation.Subtract;
        case 32779:
            return BlendOperation.ReverseSubtract;
        case 32775:
            return BlendOperation.Min;
        case 32776:
            return BlendOperation.Max;
        default:
            return BlendOperation.Add
        }
    }
    ,
    i._GetAphaBlendFactor = function(e) {
        switch (e) {
        case 0:
            return BlendFactor.Zero;
        case 1:
            return BlendFactor.One;
        case 768:
            return BlendFactor.Src;
        case 769:
            return BlendFactor.OneMinusSrc;
        case 770:
            return BlendFactor.SrcAlpha;
        case 771:
            return BlendFactor.OneMinusSrcAlpha;
        case 772:
            return BlendFactor.DstAlpha;
        case 773:
            return BlendFactor.OneMinusDstAlpha;
        case 774:
            return BlendFactor.Dst;
        case 775:
            return BlendFactor.OneMinusDst;
        case 776:
            return BlendFactor.SrcAlphaSaturated;
        case 32769:
            return BlendFactor.Constant;
        case 32770:
            return BlendFactor.OneMinusConstant;
        case 32771:
            return BlendFactor.Constant;
        case 32772:
            return BlendFactor.OneMinusConstant;
        default:
            return BlendFactor.One
        }
    }
    ,
    i._GetCompareFunction = function(e) {
        switch (e) {
        case 0:
            return CompareFunction.Never;
        case 1:
            return CompareFunction.Less;
        case 2:
            return CompareFunction.Equal;
        case 3:
            return CompareFunction.LessEqual;
        case 4:
            return CompareFunction.Greater;
        case 5:
            return CompareFunction.NotEqual;
        case 6:
            return CompareFunction.GreaterEqual;
        case 7:
            return CompareFunction.Always
        }
        return CompareFunction.Never
    }
    ,
    i._GetStencilOpFunction = function(e) {
        switch (e) {
        case 0:
            return StencilOperation.Zero;
        case 1:
            return StencilOperation.Keep;
        case 2:
            return StencilOperation.Replace;
        case 3:
            return StencilOperation.IncrementClamp;
        case 4:
            return StencilOperation.DecrementClamp;
        case 5:
            return StencilOperation.Invert;
        case 6:
            return StencilOperation.IncrementWrap;
        case 7:
            return StencilOperation.DecrementWrap
        }
        return StencilOperation.Keep
    }
    ,
    i._GetVertexInputDescriptorFormat = function(e) {
        var t = e.type
          , r = e.normalized
          , n = e.getSize();
        switch (t) {
        case VertexBuffer.BYTE:
            switch (n) {
            case 1:
            case 2:
                return r ? VertexFormat.Snorm8x2 : VertexFormat.Sint8x2;
            case 3:
            case 4:
                return r ? VertexFormat.Snorm8x4 : VertexFormat.Sint8x4
            }
            break;
        case VertexBuffer.UNSIGNED_BYTE:
            switch (n) {
            case 1:
            case 2:
                return r ? VertexFormat.Unorm8x2 : VertexFormat.Uint8x2;
            case 3:
            case 4:
                return r ? VertexFormat.Unorm8x4 : VertexFormat.Uint8x4
            }
            break;
        case VertexBuffer.SHORT:
            switch (n) {
            case 1:
            case 2:
                return r ? VertexFormat.Snorm16x2 : VertexFormat.Sint16x2;
            case 3:
            case 4:
                return r ? VertexFormat.Snorm16x4 : VertexFormat.Sint16x4
            }
            break;
        case VertexBuffer.UNSIGNED_SHORT:
            switch (n) {
            case 1:
            case 2:
                return r ? VertexFormat.Unorm16x2 : VertexFormat.Uint16x2;
            case 3:
            case 4:
                return r ? VertexFormat.Unorm16x4 : VertexFormat.Uint16x4
            }
            break;
        case VertexBuffer.INT:
            switch (n) {
            case 1:
                return VertexFormat.Sint32;
            case 2:
                return VertexFormat.Sint32x2;
            case 3:
                return VertexFormat.Sint32x3;
            case 4:
                return VertexFormat.Sint32x4
            }
            break;
        case VertexBuffer.UNSIGNED_INT:
            switch (n) {
            case 1:
                return VertexFormat.Uint32;
            case 2:
                return VertexFormat.Uint32x2;
            case 3:
                return VertexFormat.Uint32x3;
            case 4:
                return VertexFormat.Uint32x4
            }
            break;
        case VertexBuffer.FLOAT:
            switch (n) {
            case 1:
                return VertexFormat.Float32;
            case 2:
                return VertexFormat.Float32x2;
            case 3:
                return VertexFormat.Float32x3;
            case 4:
                return VertexFormat.Float32x4
            }
            break
        }
        throw new Error("Invalid Format '" + e.getKind() + "' - type=" + t + ", normalized=" + r + ", size=" + n)
    }
    ,
    i.prototype._getAphaBlendState = function() {
        return this._alphaBlendEnabled ? {
            srcFactor: i._GetAphaBlendFactor(this._alphaBlendFuncParams[2]),
            dstFactor: i._GetAphaBlendFactor(this._alphaBlendFuncParams[3]),
            operation: i._GetAphaBlendOperation(this._alphaBlendEqParams[1])
        } : null
    }
    ,
    i.prototype._getColorBlendState = function() {
        return this._alphaBlendEnabled ? {
            srcFactor: i._GetAphaBlendFactor(this._alphaBlendFuncParams[0]),
            dstFactor: i._GetAphaBlendFactor(this._alphaBlendFuncParams[1]),
            operation: i._GetAphaBlendOperation(this._alphaBlendEqParams[0])
        } : null
    }
    ,
    i.prototype._setShaderStage = function(e) {
        this._shaderId !== e && (this._shaderId = e,
        this._states[StatePosition.ShaderStage] = e,
        this._isDirty = !0,
        this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.ShaderStage))
    }
    ,
    i.prototype._setRasterizationState = function(e, t) {
        var r = this._frontFace
          , n = this._cullEnabled ? this._cullFace : 0
          , o = this._clampDepth ? 1 : 0
          , a = this._alphaToCoverageEnabled ? 1 : 0
          , s = r - 1 + (n << 1) + (o << 3) + (a << 4) + (e << 5) + (t << 8);
        this._rasterizationState !== s && (this._rasterizationState = s,
        this._states[StatePosition.RasterizationState] = this._rasterizationState,
        this._isDirty = !0,
        this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.RasterizationState))
    }
    ,
    i.prototype._setColorStates = function() {
        var e = ((this._writeMask ? 1 : 0) << 22) + (this._colorFormat << 23) + ((this._depthWriteEnabled ? 1 : 0) << 29);
        this._alphaBlendEnabled && (e += ((this._alphaBlendFuncParams[0] === null ? 2 : alphaBlendFactorToIndex[this._alphaBlendFuncParams[0]]) << 0) + ((this._alphaBlendFuncParams[1] === null ? 2 : alphaBlendFactorToIndex[this._alphaBlendFuncParams[1]]) << 4) + ((this._alphaBlendFuncParams[2] === null ? 2 : alphaBlendFactorToIndex[this._alphaBlendFuncParams[2]]) << 8) + ((this._alphaBlendFuncParams[3] === null ? 2 : alphaBlendFactorToIndex[this._alphaBlendFuncParams[3]]) << 12) + ((this._alphaBlendEqParams[0] === null ? 1 : this._alphaBlendEqParams[0] - 32773) << 16) + ((this._alphaBlendEqParams[1] === null ? 1 : this._alphaBlendEqParams[1] - 32773) << 19)),
        e !== this._colorStates && (this._colorStates = e,
        this._states[StatePosition.ColorStates] = this._colorStates,
        this._isDirty = !0,
        this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.ColorStates))
    }
    ,
    i.prototype._setDepthStencilState = function() {
        var e = this._stencilEnabled ? this._stencilFrontCompare + (this._stencilFrontDepthFailOp << 3) + (this._stencilFrontPassOp << 6) + (this._stencilFrontFailOp << 9) : 591
          , t = this._depthStencilFormat + ((this._depthTestEnabled ? this._depthCompare : 7) << 6) + (e << 10);
        this._depthStencilState !== t && (this._depthStencilState = t,
        this._states[StatePosition.DepthStencilState] = this._depthStencilState,
        this._isDirty = !0,
        this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.DepthStencilState))
    }
    ,
    i.prototype._setVertexState = function(e) {
        for (var t, r, n = this._statesLength, o = StatePosition.VertexState, a = e._pipelineContext, s = a.shaderProcessingContext.attributeNamesFromEffect, l = a.shaderProcessingContext.attributeLocationsFromEffect, u, c = 0, h = 0; h < s.length; h++) {
            var f = l[h]
              , d = (t = this._overrideVertexBuffers && this._overrideVertexBuffers[s[h]]) !== null && t !== void 0 ? t : this._vertexBuffers[s[h]];
            d || (d = this._emptyVertexBuffer);
            var _ = (r = d.getBuffer()) === null || r === void 0 ? void 0 : r.underlyingResource;
            if (d._validOffsetRange === void 0) {
                var g = d.byteOffset
                  , m = d.getSize(!0)
                  , v = d.byteStride;
                d._validOffsetRange = g <= this._kMaxVertexBufferStride - m && (v === 0 || g + m <= v)
            }
            u && u === _ && d._validOffsetRange || (this.vertexBuffers[c++] = d,
            u = d._validOffsetRange ? _ : null);
            var y = d.hashCode + (f << 7);
            this._isDirty = this._isDirty || this._states[o] !== y,
            this._states[o++] = y
        }
        this.vertexBuffers.length = c,
        this._statesLength = o,
        this._isDirty = this._isDirty || o !== n,
        this._isDirty && (this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.VertexState))
    }
    ,
    i.prototype._setTextureState = function(e) {
        this._textureState !== e && (this._textureState = e,
        this._states[StatePosition.TextureStage] = this._textureState,
        this._isDirty = !0,
        this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.TextureStage))
    }
    ,
    i.prototype._createPipelineLayout = function(e) {
        if (this._useTextureStage)
            return this._createPipelineLayoutWithTextureStage(e);
        for (var t = [], r = e.shaderProcessingContext.bindGroupLayoutEntries, n = 0; n < r.length; n++) {
            var o = r[n];
            t[n] = this._device.createBindGroupLayout({
                entries: o
            })
        }
        return e.bindGroupLayouts = t,
        this._device.createPipelineLayout({
            bindGroupLayouts: t
        })
    }
    ,
    i.prototype._createPipelineLayoutWithTextureStage = function(e) {
        for (var t, r = e.shaderProcessingContext, n = r.bindGroupLayoutEntries, o = 1, a = 0; a < n.length; a++)
            for (var s = n[a], l = 0; l < s.length; l++) {
                var u = n[a][l];
                if (u.texture) {
                    var c = r.bindGroupLayoutEntryInfo[a][u.binding].name
                      , h = r.availableTextures[c]
                      , f = h.autoBindSampler ? r.availableSamplers[c + WebGPUShaderProcessor.AutoSamplerSuffix] : null
                      , d = h.sampleType
                      , _ = (t = f == null ? void 0 : f.type) !== null && t !== void 0 ? t : SamplerBindingType.Filtering;
                    if (this._textureState & o && d !== TextureSampleType.Depth && (h.autoBindSampler && (_ = SamplerBindingType.NonFiltering),
                    d = TextureSampleType.UnfilterableFloat),
                    u.texture.sampleType = d,
                    f) {
                        var g = r.bindGroupLayoutEntryInfo[f.binding.groupIndex][f.binding.bindingIndex].index;
                        n[f.binding.groupIndex][g].sampler.type = _
                    }
                    o = o << 1
                }
            }
        for (var m = [], a = 0; a < n.length; ++a)
            m[a] = this._device.createBindGroupLayout({
                entries: n[a]
            });
        return e.bindGroupLayouts = m,
        this._device.createPipelineLayout({
            bindGroupLayouts: m
        })
    }
    ,
    i.prototype._getVertexInputDescriptor = function(e, t) {
        for (var r, n, o = [], a = e._pipelineContext, s = a.shaderProcessingContext.attributeNamesFromEffect, l = a.shaderProcessingContext.attributeLocationsFromEffect, u, c, h = 0; h < s.length; h++) {
            var f = l[h]
              , d = (r = this._overrideVertexBuffers && this._overrideVertexBuffers[s[h]]) !== null && r !== void 0 ? r : this._vertexBuffers[s[h]];
            d || (d = this._emptyVertexBuffer);
            var _ = (n = d.getBuffer()) === null || n === void 0 ? void 0 : n.underlyingResource
              , g = d.byteOffset
              , m = !d._validOffsetRange;
            if (!(u && c && u === _) || m) {
                var v = {
                    arrayStride: d.byteStride,
                    stepMode: d.getIsInstanced() ? InputStepMode.Instance : InputStepMode.Vertex,
                    attributes: []
                };
                o.push(v),
                c = v.attributes,
                m && (g = 0,
                _ = null)
            }
            c.push({
                shaderLocation: f,
                offset: g,
                format: i._GetVertexInputDescriptorFormat(d)
            }),
            u = _
        }
        return o
    }
    ,
    i.prototype._createRenderPipeline = function(e, t, r) {
        var n = e._pipelineContext
          , o = this._getVertexInputDescriptor(e, t)
          , a = this._createPipelineLayout(n)
          , s = []
          , l = this._getAphaBlendState()
          , u = this._getColorBlendState();
        if (this._mrtAttachments1 > 0)
            for (var c = 0; c < this._mrtFormats.length; ++c) {
                var h = {
                    format: this._mrtFormats[c],
                    writeMask: this._writeMask
                };
                l && u && (h.blend = {
                    alpha: l,
                    color: u
                }),
                s.push(h)
            }
        else {
            var h = {
                format: this._webgpuColorFormat[0],
                writeMask: this._writeMask
            };
            l && u && (h.blend = {
                alpha: l,
                color: u
            }),
            s.push(h)
        }
        var f = {
            compare: i._GetCompareFunction(this._stencilEnabled ? this._stencilFrontCompare : 7),
            depthFailOp: i._GetStencilOpFunction(this._stencilEnabled ? this._stencilFrontDepthFailOp : 1),
            failOp: i._GetStencilOpFunction(this._stencilEnabled ? this._stencilFrontFailOp : 1),
            passOp: i._GetStencilOpFunction(this._stencilEnabled ? this._stencilFrontPassOp : 1)
        }
          , d = void 0;
        return (t === PrimitiveTopology.LineStrip || t === PrimitiveTopology.TriangleStrip) && (d = !this._indexBuffer || this._indexBuffer.is32Bits ? IndexFormat.Uint32 : IndexFormat.Uint16),
        this._device.createRenderPipeline({
            layout: a,
            vertex: {
                module: n.stages.vertexStage.module,
                entryPoint: n.stages.vertexStage.entryPoint,
                buffers: o
            },
            primitive: {
                topology: t,
                stripIndexFormat: d,
                frontFace: this._frontFace === 1 ? FrontFace.CCW : FrontFace.CW,
                cullMode: this._cullEnabled ? this._cullFace === 2 ? CullMode.Front : CullMode.Back : CullMode.None
            },
            fragment: n.stages.fragmentStage ? {
                module: n.stages.fragmentStage.module,
                entryPoint: n.stages.fragmentStage.entryPoint,
                targets: s
            } : void 0,
            multisample: {
                count: r
            },
            depthStencil: this._webgpuDepthStencilFormat === void 0 ? void 0 : {
                depthWriteEnabled: this._depthWriteEnabled,
                depthCompare: this._depthTestEnabled ? i._GetCompareFunction(this._depthCompare) : CompareFunction.Always,
                format: this._webgpuDepthStencilFormat,
                stencilFront: f,
                stencilBack: f,
                stencilReadMask: this._stencilReadMask,
                stencilWriteMask: this._stencilWriteMask,
                depthBias: this._depthBias,
                depthBiasClamp: this._depthBiasClamp,
                depthBiasSlopeScale: this._depthBiasSlopeScale
            }
        })
    }
    ,
    i.NumCacheHitWithoutHash = 0,
    i.NumCacheHitWithHash = 0,
    i.NumCacheMiss = 0,
    i.NumPipelineCreationLastFrame = 0,
    i._NumPipelineCreationCurrentFrame = 0,
    i
}()
  , NodeState = function() {
    function i() {
        this.values = {}
    }
    return i.prototype.count = function() {
        var e = 0
          , t = this.pipeline ? 1 : 0;
        for (var r in this.values) {
            var n = this.values[r]
              , o = n.count()
              , a = o[0]
              , s = o[1];
            e += a,
            t += s,
            e++
        }
        return [e, t]
    }
    ,
    i
}()
  , WebGPUCacheRenderPipelineTree = function(i) {
    __extends(e, i);
    function e(t, r, n) {
        var o = i.call(this, t, r, n) || this;
        return o._nodeStack = [],
        o._nodeStack[0] = e._Cache,
        o
    }
    return e.GetNodeCounts = function() {
        var t = e._Cache.count();
        return {
            nodeCount: t[0],
            pipelineCount: t[1]
        }
    }
    ,
    e._GetPipelines = function(t, r, n, o) {
        if (t.pipeline) {
            var a = n.slice();
            a.length = o,
            r.push(a)
        }
        for (var s in t.values) {
            var l = t.values[s];
            n[o] = parseInt(s),
            e._GetPipelines(l, r, n, o + 1)
        }
    }
    ,
    e.GetPipelines = function() {
        var t = [];
        return e._GetPipelines(e._Cache, t, [], 0),
        t
    }
    ,
    e.prototype._getRenderPipeline = function(t) {
        for (var r = this._nodeStack[this._stateDirtyLowestIndex], n = this._stateDirtyLowestIndex; n < this._statesLength; ++n) {
            var o = r.values[this._states[n]];
            o || (o = new NodeState,
            r.values[this._states[n]] = o),
            r = o,
            this._nodeStack[n + 1] = r
        }
        t.token = r,
        t.pipeline = r.pipeline
    }
    ,
    e.prototype._setRenderPipeline = function(t) {
        t.token.pipeline = t.pipeline
    }
    ,
    e._Cache = new NodeState,
    e
}(WebGPUCacheRenderPipeline)
  , WebGPUStencilStateComposer = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, !1) || this;
        return r._cache = t,
        r.reset(),
        r
    }
    return Object.defineProperty(e.prototype, "func", {
        get: function() {
            return this._func
        },
        set: function(t) {
            this._func !== t && (this._func = t,
            this._cache.setStencilCompare(t))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "funcMask", {
        get: function() {
            return this._funcMask
        },
        set: function(t) {
            this._funcMask !== t && (this._funcMask = t,
            this._cache.setStencilReadMask(t))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "opStencilFail", {
        get: function() {
            return this._opStencilFail
        },
        set: function(t) {
            this._opStencilFail !== t && (this._opStencilFail = t,
            this._cache.setStencilFailOp(t))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "opDepthFail", {
        get: function() {
            return this._opDepthFail
        },
        set: function(t) {
            this._opDepthFail !== t && (this._opDepthFail = t,
            this._cache.setStencilDepthFailOp(t))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "opStencilDepthPass", {
        get: function() {
            return this._opStencilDepthPass
        },
        set: function(t) {
            this._opStencilDepthPass !== t && (this._opStencilDepthPass = t,
            this._cache.setStencilPassOp(t))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "mask", {
        get: function() {
            return this._mask
        },
        set: function(t) {
            this._mask !== t && (this._mask = t,
            this._cache.setStencilWriteMask(t))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "enabled", {
        get: function() {
            return this._enabled
        },
        set: function(t) {
            this._enabled !== t && (this._enabled = t,
            this._cache.setStencilEnabled(t))
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.reset = function() {
        i.prototype.reset.call(this),
        this._cache.resetStencilState()
    }
    ,
    e.prototype.apply = function(t) {
        var r, n = (r = this.stencilMaterial) === null || r === void 0 ? void 0 : r.enabled;
        this.enabled = n ? this.stencilMaterial.enabled : this.stencilGlobal.enabled,
        this.enabled && (this.func = n ? this.stencilMaterial.func : this.stencilGlobal.func,
        this.funcRef = n ? this.stencilMaterial.funcRef : this.stencilGlobal.funcRef,
        this.funcMask = n ? this.stencilMaterial.funcMask : this.stencilGlobal.funcMask,
        this.opStencilFail = n ? this.stencilMaterial.opStencilFail : this.stencilGlobal.opStencilFail,
        this.opDepthFail = n ? this.stencilMaterial.opDepthFail : this.stencilGlobal.opDepthFail,
        this.opStencilDepthPass = n ? this.stencilMaterial.opStencilDepthPass : this.stencilGlobal.opStencilDepthPass,
        this.mask = n ? this.stencilMaterial.mask : this.stencilGlobal.mask)
    }
    ,
    e
}(StencilStateComposer)
  , WebGPUDepthCullingState = function(i) {
    __extends(e, i);
    function e(t) {
        var r = i.call(this, !1) || this;
        return r._cache = t,
        r.reset(),
        r
    }
    return Object.defineProperty(e.prototype, "zOffset", {
        get: function() {
            return this._zOffset
        },
        set: function(t) {
            this._zOffset !== t && (this._zOffset = t,
            this._isZOffsetDirty = !0,
            this._cache.setDepthBiasSlopeScale(t))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "zOffsetUnits", {
        get: function() {
            return this._zOffsetUnits
        },
        set: function(t) {
            this._zOffsetUnits !== t && (this._zOffsetUnits = t,
            this._isZOffsetDirty = !0,
            this._cache.setDepthBias(t))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cullFace", {
        get: function() {
            return this._cullFace
        },
        set: function(t) {
            this._cullFace !== t && (this._cullFace = t,
            this._isCullFaceDirty = !0,
            this._cache.setCullFace(t != null ? t : 1))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "cull", {
        get: function() {
            return this._cull
        },
        set: function(t) {
            this._cull !== t && (this._cull = t,
            this._isCullDirty = !0,
            this._cache.setCullEnabled(!!t))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "depthFunc", {
        get: function() {
            return this._depthFunc
        },
        set: function(t) {
            this._depthFunc !== t && (this._depthFunc = t,
            this._isDepthFuncDirty = !0,
            this._cache.setDepthCompare(t))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "depthMask", {
        get: function() {
            return this._depthMask
        },
        set: function(t) {
            this._depthMask !== t && (this._depthMask = t,
            this._isDepthMaskDirty = !0,
            this._cache.setDepthWriteEnabled(t))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "depthTest", {
        get: function() {
            return this._depthTest
        },
        set: function(t) {
            this._depthTest !== t && (this._depthTest = t,
            this._isDepthTestDirty = !0,
            this._cache.setDepthTestEnabled(t))
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "frontFace", {
        get: function() {
            return this._frontFace
        },
        set: function(t) {
            this._frontFace !== t && (this._frontFace = t,
            this._isFrontFaceDirty = !0,
            this._cache.setFrontFace(t != null ? t : 2))
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.reset = function() {
        i.prototype.reset.call(this),
        this._cache.resetDepthCullingState()
    }
    ,
    e.prototype.apply = function(t) {}
    ,
    e
}(DepthCullingState)
  , ExternalTexture = function() {
    function i(e) {
        this.useMipMaps = !1,
        this.type = 16,
        this._video = e,
        this.uniqueId = InternalTexture._Counter++
    }
    return i.IsExternalTexture = function(e) {
        return e.underlyingResource !== void 0
    }
    ,
    i.prototype.getClassName = function() {
        return "ExternalTexture"
    }
    ,
    Object.defineProperty(i.prototype, "underlyingResource", {
        get: function() {
            return this._video
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.isReady = function() {
        return this._video.readyState >= this._video.HAVE_CURRENT_DATA
    }
    ,
    i.prototype.dispose = function() {}
    ,
    i
}()
  , WebGPUMaterialContext = function() {
    function i() {
        this.uniqueId = i._Counter++,
        this.updateId = 0,
        this.reset()
    }
    return Object.defineProperty(i.prototype, "forceBindGroupCreation", {
        get: function() {
            return this._numExternalTextures > 0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "hasFloatTextures", {
        get: function() {
            return this._numFloatTextures > 0
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.reset = function() {
        this.samplers = {},
        this.textures = {},
        this.isDirty = !0,
        this._numFloatTextures = 0,
        this._numExternalTextures = 0
    }
    ,
    i.prototype.setSampler = function(e, t) {
        var r = this.samplers[e]
          , n = -1;
        r ? n = r.hashCode : this.samplers[e] = r = {
            sampler: t,
            hashCode: 0
        },
        r.sampler = t,
        r.hashCode = t ? WebGPUCacheSampler.GetSamplerHashCode(t) : 0;
        var o = n !== r.hashCode;
        o && this.updateId++,
        this.isDirty || (this.isDirty = o)
    }
    ,
    i.prototype.setTexture = function(e, t) {
        var r, n, o, a = this.textures[e], s = -1;
        a ? s = (n = (r = a.texture) === null || r === void 0 ? void 0 : r.uniqueId) !== null && n !== void 0 ? n : -1 : this.textures[e] = a = {
            texture: t,
            isFloatTexture: !1,
            isExternalTexture: !1
        },
        a.isExternalTexture && this._numExternalTextures--,
        a.isFloatTexture && this._numFloatTextures--,
        t ? (a.isFloatTexture = t.type === 1,
        a.isExternalTexture = ExternalTexture.IsExternalTexture(t),
        a.isFloatTexture && this._numFloatTextures++,
        a.isExternalTexture && this._numExternalTextures++) : (a.isFloatTexture = !1,
        a.isExternalTexture = !1),
        a.texture = t;
        var l = s !== ((o = t == null ? void 0 : t.uniqueId) !== null && o !== void 0 ? o : -1);
        l && this.updateId++,
        this.isDirty || (this.isDirty = l)
    }
    ,
    i._Counter = 0,
    i
}()
  , WebGPUDrawContext = function() {
    function i(e) {
        this._bufferManager = e,
        this.uniqueId = i._Counter++,
        this._useInstancing = !1,
        this._currentInstanceCount = 0,
        this.reset()
    }
    return i.prototype.isDirty = function(e) {
        return this._isDirty || this.materialContextUpdateId !== e
    }
    ,
    i.prototype.resetIsDirty = function(e) {
        this._isDirty = !1,
        this.materialContextUpdateId = e
    }
    ,
    Object.defineProperty(i.prototype, "useInstancing", {
        get: function() {
            return this._useInstancing
        },
        set: function(e) {
            this._useInstancing !== e && (e ? (this.indirectDrawBuffer = this._bufferManager.createRawBuffer(40, BufferUsage.CopyDst | BufferUsage.Indirect),
            this._indirectDrawData = new Uint32Array(5),
            this._indirectDrawData[3] = 0,
            this._indirectDrawData[4] = 0) : (this.indirectDrawBuffer && this._bufferManager.releaseBuffer(this.indirectDrawBuffer),
            this.indirectDrawBuffer = void 0,
            this._indirectDrawData = void 0),
            this._useInstancing = e,
            this._currentInstanceCount = -1)
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.reset = function() {
        this.buffers = {},
        this._isDirty = !0,
        this.materialContextUpdateId = 0,
        this.fastBundle = void 0,
        this.bindGroups = void 0
    }
    ,
    i.prototype.setBuffer = function(e, t) {
        var r;
        this._isDirty || (this._isDirty = (t == null ? void 0 : t.uniqueId) !== ((r = this.buffers[e]) === null || r === void 0 ? void 0 : r.uniqueId)),
        this.buffers[e] = t
    }
    ,
    i.prototype.setIndirectData = function(e, t, r) {
        t === this._currentInstanceCount || !this.indirectDrawBuffer || !this._indirectDrawData || (this._currentInstanceCount = t,
        this._indirectDrawData[0] = e,
        this._indirectDrawData[1] = t,
        this._indirectDrawData[2] = r,
        this._bufferManager.setRawData(this.indirectDrawBuffer, 0, this._indirectDrawData, 0, 20))
    }
    ,
    i.prototype.dispose = function() {
        this.indirectDrawBuffer && (this._bufferManager.releaseBuffer(this.indirectDrawBuffer),
        this.indirectDrawBuffer = void 0,
        this._indirectDrawData = void 0),
        this.fastBundle = void 0,
        this.bindGroups = void 0,
        this.buffers = void 0
    }
    ,
    i._Counter = 0,
    i
}()
  , WebGPUBindGroupCacheNode = function() {
    function i() {
        this.values = {}
    }
    return i
}()
  , WebGPUCacheBindGroups = function() {
    function i(e, t, r) {
        this.disabled = !1,
        this._device = e,
        this._cacheSampler = t,
        this._engine = r
    }
    return Object.defineProperty(i, "Statistics", {
        get: function() {
            return {
                totalCreated: i.NumBindGroupsCreatedTotal,
                lastFrameCreated: i.NumBindGroupsCreatedLastFrame,
                lookupLastFrame: i.NumBindGroupsLookupLastFrame,
                noLookupLastFrame: i.NumBindGroupsNoLookupLastFrame
            }
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.endFrame = function() {
        i.NumBindGroupsCreatedLastFrame = i._NumBindGroupsCreatedCurrentFrame,
        i.NumBindGroupsLookupLastFrame = i._NumBindGroupsLookupCurrentFrame,
        i.NumBindGroupsNoLookupLastFrame = i._NumBindGroupsNoLookupCurrentFrame,
        i._NumBindGroupsCreatedCurrentFrame = 0,
        i._NumBindGroupsLookupCurrentFrame = 0,
        i._NumBindGroupsNoLookupCurrentFrame = 0
    }
    ,
    i.prototype.getBindGroups = function(e, t, r) {
        var n, o, a, s, l, u, c, h, f, d, _ = void 0, g = i._Cache, m = this.disabled || r.forceBindGroupCreation;
        if (!m) {
            if (!t.isDirty(r.updateId) && !r.isDirty)
                return i._NumBindGroupsNoLookupCurrentFrame++,
                t.bindGroups;
            for (var v = 0, y = e.shaderProcessingContext.bufferNames; v < y.length; v++) {
                var b = y[v]
                  , T = (o = (n = t.buffers[b]) === null || n === void 0 ? void 0 : n.uniqueId) !== null && o !== void 0 ? o : 0
                  , C = g.values[T];
                C || (C = new WebGPUBindGroupCacheNode,
                g.values[T] = C),
                g = C
            }
            for (var A = 0, S = e.shaderProcessingContext.samplerNames; A < S.length; A++) {
                var P = S[A]
                  , R = (s = (a = r.samplers[P]) === null || a === void 0 ? void 0 : a.hashCode) !== null && s !== void 0 ? s : 0
                  , C = g.values[R];
                C || (C = new WebGPUBindGroupCacheNode,
                g.values[R] = C),
                g = C
            }
            for (var M = 0, x = e.shaderProcessingContext.textureNames; M < x.length; M++) {
                var I = x[M]
                  , w = (c = (u = (l = r.textures[I]) === null || l === void 0 ? void 0 : l.texture) === null || u === void 0 ? void 0 : u.uniqueId) !== null && c !== void 0 ? c : 0
                  , C = g.values[w];
                C || (C = new WebGPUBindGroupCacheNode,
                g.values[w] = C),
                g = C
            }
            _ = g.bindGroups
        }
        if (t.resetIsDirty(r.updateId),
        r.isDirty = !1,
        _)
            return t.bindGroups = _,
            i._NumBindGroupsLookupCurrentFrame++,
            _;
        _ = [],
        t.bindGroups = _,
        m || (g.bindGroups = _),
        i.NumBindGroupsCreatedTotal++,
        i._NumBindGroupsCreatedCurrentFrame++;
        for (var O = e.bindGroupLayouts, D = 0; D < e.shaderProcessingContext.bindGroupLayoutEntries.length; D++) {
            for (var F = e.shaderProcessingContext.bindGroupLayoutEntries[D], V = e.shaderProcessingContext.bindGroupEntries[D], N = 0; N < F.length; N++) {
                var L = e.shaderProcessingContext.bindGroupLayoutEntries[D][N]
                  , k = e.shaderProcessingContext.bindGroupLayoutEntryInfo[D][L.binding]
                  , U = (h = k.nameInArrayOfTexture) !== null && h !== void 0 ? h : k.name;
                if (L.sampler) {
                    var z = r.samplers[U];
                    if (z) {
                        var H = z.sampler;
                        if (!H) {
                            this._engine.dbgSanityChecks && Logger$2.Error("Trying to bind a null sampler! entry=" + JSON.stringify(L) + ", name=" + U + ", bindingInfo=" + JSON.stringify(z, function($, Y) {
                                return $ === "texture" ? "<no dump>" : Y
                            }) + ", materialContext.uniqueId=" + r.uniqueId, 50);
                            continue
                        }
                        V[N].resource = this._cacheSampler.getSampler(H, !1, z.hashCode)
                    } else
                        Logger$2.Error('Sampler "' + U + '" could not be bound. entry=' + JSON.stringify(L) + ", materialContext=" + JSON.stringify(r, function($, Y) {
                            return $ === "texture" || $ === "sampler" ? "<no dump>" : Y
                        }), 50)
                } else if (L.texture || L.storageTexture) {
                    var z = r.textures[U];
                    if (z) {
                        if (this._engine.dbgSanityChecks && z.texture === null) {
                            Logger$2.Error("Trying to bind a null texture! entry=" + JSON.stringify(L) + ", bindingInfo=" + JSON.stringify(z, function(Y, K) {
                                return Y === "texture" ? "<no dump>" : K
                            }) + ", materialContext.uniqueId=" + r.uniqueId, 50);
                            continue
                        }
                        var G = z.texture._hardwareTexture;
                        if (this._engine.dbgSanityChecks && (!G || !G.view)) {
                            Logger$2.Error("Trying to bind a null gpu texture! entry=" + JSON.stringify(L) + ", name=" + U + ", bindingInfo=" + JSON.stringify(z, function(Y, K) {
                                return Y === "texture" ? "<no dump>" : K
                            }) + ", isReady=" + ((f = z.texture) === null || f === void 0 ? void 0 : f.isReady) + ", materialContext.uniqueId=" + r.uniqueId, 50);
                            continue
                        }
                        V[N].resource = G.view
                    } else
                        Logger$2.Error('Texture "' + U + '" could not be bound. entry=' + JSON.stringify(L) + ", materialContext=" + JSON.stringify(r, function(Y, K) {
                            return Y === "texture" || Y === "sampler" ? "<no dump>" : K
                        }), 50)
                } else if (L.externalTexture) {
                    var z = r.textures[U];
                    if (z) {
                        if (this._engine.dbgSanityChecks && z.texture === null) {
                            Logger$2.Error("Trying to bind a null external texture! entry=" + JSON.stringify(L) + ", name=" + U + ", bindingInfo=" + JSON.stringify(z, function(Y, K) {
                                return Y === "texture" ? "<no dump>" : K
                            }) + ", materialContext.uniqueId=" + r.uniqueId, 50);
                            continue
                        }
                        var W = z.texture.underlyingResource;
                        if (this._engine.dbgSanityChecks && !W) {
                            Logger$2.Error("Trying to bind a null gpu external texture! entry=" + JSON.stringify(L) + ", name=" + U + ", bindingInfo=" + JSON.stringify(z, function(Y, K) {
                                return Y === "texture" ? "<no dump>" : K
                            }) + ", isReady=" + ((d = z.texture) === null || d === void 0 ? void 0 : d.isReady) + ", materialContext.uniqueId=" + r.uniqueId, 50);
                            continue
                        }
                        V[N].resource = this._device.importExternalTexture({
                            source: W
                        })
                    } else
                        Logger$2.Error('Texture "' + U + '" could not be bound. entry=' + JSON.stringify(L) + ", materialContext=" + JSON.stringify(r, function(Y, K) {
                            return Y === "texture" || Y === "sampler" ? "<no dump>" : K
                        }), 50)
                } else if (L.buffer) {
                    var j = t.buffers[U];
                    if (j) {
                        var B = j.underlyingResource;
                        V[N].resource.buffer = B,
                        V[N].resource.size = j.capacity
                    } else
                        Logger$2.Error(`Can't find buffer "` + U + '". entry=' + JSON.stringify(L) + ", buffers=" + JSON.stringify(t.buffers) + ", drawContext.uniqueId=" + t.uniqueId, 50)
                }
            }
            var X = O[D];
            _[D] = this._device.createBindGroup({
                layout: X,
                entries: V
            })
        }
        return _
    }
    ,
    i.NumBindGroupsCreatedTotal = 0,
    i.NumBindGroupsCreatedLastFrame = 0,
    i.NumBindGroupsLookupLastFrame = 0,
    i.NumBindGroupsNoLookupLastFrame = 0,
    i._Cache = new WebGPUBindGroupCacheNode,
    i._NumBindGroupsCreatedCurrentFrame = 0,
    i._NumBindGroupsLookupCurrentFrame = 0,
    i._NumBindGroupsNoLookupCurrentFrame = 0,
    i
}()
  , name$1 = "clearQuadVertexShader"
  , shader$1 = `uniform float depthValue;
const vec2 pos[4]={
vec2(-1.0,1.0),
vec2(1.0,1.0),
vec2(-1.0,-1.0),
vec2(1.0,-1.0)
};
void main(void) {
gl_Position=vec4(pos[gl_VertexID],depthValue,1.0);
}
`;
ShaderStore.ShadersStore[name$1] = shader$1;
var name = "clearQuadPixelShader"
  , shader = `uniform vec4 color;
void main() {
gl_FragColor=color;
}
`;
ShaderStore.ShadersStore[name] = shader;
var WebGPUClearQuad = function() {
    function i(e, t, r) {
        this._bindGroups = {},
        this._bundleCache = {},
        this._device = e,
        this._engine = t,
        this._cacheRenderPipeline = new WebGPUCacheRenderPipelineTree(this._device,r,!t._caps.textureFloatLinearFiltering),
        this._cacheRenderPipeline.setDepthTestEnabled(!1),
        this._cacheRenderPipeline.setStencilReadMask(255),
        this._effect = t.createEffect("clearQuad", [], ["color", "depthValue"])
    }
    return i.prototype.setDepthStencilFormat = function(e) {
        this._depthTextureFormat = e,
        this._cacheRenderPipeline.setDepthStencilFormat(e)
    }
    ,
    i.prototype.setColorFormat = function(e) {
        this._cacheRenderPipeline.setColorFormat(e)
    }
    ,
    i.prototype.setMRTAttachments = function(e, t) {
        this._cacheRenderPipeline.setMRTAttachments(e, t)
    }
    ,
    i.prototype.clear = function(e, t, r, n, o) {
        var a, s;
        o === void 0 && (o = 1);
        var l, u = null, c = 0;
        if (e)
            l = e;
        else {
            if (c = (t ? t.r + t.g * 256 + t.b * 256 * 256 + t.a * 256 * 256 * 256 : 0) + (r ? Math.pow(2, 32) : 0) + (n ? Math.pow(2, 33) : 0) + (this._engine.useReverseDepthBuffer ? Math.pow(2, 34) : 0) + o * Math.pow(2, 35),
            u = this._bundleCache[c],
            u)
                return u;
            l = this._device.createRenderBundleEncoder({
                colorFormats: this._cacheRenderPipeline.colorFormats,
                depthStencilFormat: this._depthTextureFormat,
                sampleCount: o
            })
        }
        this._cacheRenderPipeline.setDepthWriteEnabled(!!r),
        this._cacheRenderPipeline.setStencilEnabled(!!n),
        this._cacheRenderPipeline.setStencilWriteMask(n ? 255 : 0),
        this._cacheRenderPipeline.setStencilCompare(n ? 519 : 512),
        this._cacheRenderPipeline.setStencilPassOp(n ? 7681 : 7680),
        this._cacheRenderPipeline.setWriteMask(t ? 15 : 0);
        var h = this._cacheRenderPipeline.getRenderPipeline(7, this._effect, o)
          , f = this._effect._pipelineContext;
        t && this._effect.setDirectColor4("color", t),
        this._effect.setFloat("depthValue", this._engine.useReverseDepthBuffer ? this._engine._clearReverseDepthValue : this._engine._clearDepthValue),
        (a = f.uniformBuffer) === null || a === void 0 || a.update();
        var d = (s = f.uniformBuffer) === null || s === void 0 ? void 0 : s.getBuffer()
          , _ = this._bindGroups[d.uniqueId];
        if (!_) {
            var g = f.bindGroupLayouts;
            _ = this._bindGroups[d.uniqueId] = [],
            _.push(this._device.createBindGroup({
                layout: g[0],
                entries: []
            })),
            WebGPUShaderProcessingContext._SimplifiedKnownBindings || _.push(this._device.createBindGroup({
                layout: g[1],
                entries: []
            })),
            _.push(this._device.createBindGroup({
                layout: g[WebGPUShaderProcessingContext._SimplifiedKnownBindings ? 1 : 2],
                entries: [{
                    binding: 0,
                    resource: {
                        buffer: d.underlyingResource,
                        size: d.capacity
                    }
                }]
            }))
        }
        l.setPipeline(h);
        for (var m = 0; m < _.length; ++m)
            l.setBindGroup(m, _[m]);
        return l.draw(4, 1, 0, 0),
        e || (u = l.finish(),
        this._bundleCache[c] = u),
        u
    }
    ,
    i
}()
  , WebGPURenderItemViewport = function() {
    function i(e, t, r, n) {
        this.x = Math.floor(e),
        this.y = Math.floor(t),
        this.w = Math.floor(r),
        this.h = Math.floor(n)
    }
    return i.prototype.run = function(e) {
        e.setViewport(this.x, this.y, this.w, this.h, 0, 1)
    }
    ,
    i.prototype.clone = function() {
        return new i(this.x,this.y,this.w,this.h)
    }
    ,
    i
}()
  , WebGPURenderItemScissor = function() {
    function i(e, t, r, n) {
        this.x = e,
        this.y = t,
        this.w = r,
        this.h = n
    }
    return i.prototype.run = function(e) {
        e.setScissorRect(this.x, this.y, this.w, this.h)
    }
    ,
    i.prototype.clone = function() {
        return new i(this.x,this.y,this.w,this.h)
    }
    ,
    i
}()
  , WebGPURenderItemStencilRef = function() {
    function i(e) {
        this.ref = e
    }
    return i.prototype.run = function(e) {
        e.setStencilReference(this.ref)
    }
    ,
    i.prototype.clone = function() {
        return new i(this.ref)
    }
    ,
    i
}()
  , WebGPURenderItemBlendColor = function() {
    function i(e) {
        this.color = e
    }
    return i.prototype.run = function(e) {
        e.setBlendConstant(this.color)
    }
    ,
    i.prototype.clone = function() {
        return new i(this.color)
    }
    ,
    i
}()
  , WebGPURenderItemBeginOcclusionQuery = function() {
    function i(e) {
        this.query = e
    }
    return i.prototype.run = function(e) {
        e.beginOcclusionQuery(this.query)
    }
    ,
    i.prototype.clone = function() {
        return new i(this.query)
    }
    ,
    i
}()
  , WebGPURenderItemEndOcclusionQuery = function() {
    function i() {}
    return i.prototype.run = function(e) {
        e.endOcclusionQuery()
    }
    ,
    i.prototype.clone = function() {
        return new i
    }
    ,
    i
}()
  , WebGPURenderItemBundles = function() {
    function i() {
        this.bundles = []
    }
    return i.prototype.run = function(e) {
        e.executeBundles(this.bundles)
    }
    ,
    i.prototype.clone = function() {
        var e = new i;
        return e.bundles = this.bundles,
        e
    }
    ,
    i
}()
  , WebGPUBundleList = function() {
    function i(e) {
        this.numDrawCalls = 0,
        this._device = e,
        this._list = new Array(10),
        this._listLength = 0
    }
    return i.prototype.addBundle = function(e) {
        if (!this._currentItemIsBundle) {
            var t = new WebGPURenderItemBundles;
            this._list[this._listLength++] = t,
            this._currentBundleList = t.bundles,
            this._currentItemIsBundle = !0
        }
        e && this._currentBundleList.push(e)
    }
    ,
    i.prototype._finishBundle = function() {
        this._currentItemIsBundle && this._bundleEncoder && (this._currentBundleList.push(this._bundleEncoder.finish()),
        this._bundleEncoder = void 0,
        this._currentItemIsBundle = !1)
    }
    ,
    i.prototype.addItem = function(e) {
        this._finishBundle(),
        this._list[this._listLength++] = e,
        this._currentItemIsBundle = !1
    }
    ,
    i.prototype.getBundleEncoder = function(e, t, r) {
        return this._currentItemIsBundle || (this.addBundle(),
        this._bundleEncoder = this._device.createRenderBundleEncoder({
            colorFormats: e,
            depthStencilFormat: t,
            sampleCount: r
        })),
        this._bundleEncoder
    }
    ,
    i.prototype.close = function() {
        this._finishBundle()
    }
    ,
    i.prototype.run = function(e) {
        this.close();
        for (var t = 0; t < this._listLength; ++t)
            this._list[t].run(e)
    }
    ,
    i.prototype.reset = function() {
        this._listLength = 0,
        this._currentItemIsBundle = !1,
        this.numDrawCalls = 0
    }
    ,
    i.prototype.clone = function() {
        this.close();
        var e = new i(this._device);
        e._list = new Array(this._listLength),
        e._listLength = this._listLength,
        e.numDrawCalls = this.numDrawCalls;
        for (var t = 0; t < this._listLength; ++t)
            e._list[t] = this._list[t].clone();
        return e
    }
    ,
    i
}()
  , WebGPUQuerySet = function() {
    function i(e, t, r, n, o) {
        o === void 0 && (o = !0),
        this._dstBuffers = [],
        this._device = r,
        this._bufferManager = n,
        this._count = e,
        this._canUseMultipleBuffers = o,
        this._querySet = r.createQuerySet({
            type: t,
            count: e
        }),
        this._queryBuffer = n.createRawBuffer(8 * e, BufferUsage.QueryResolve | BufferUsage.CopySrc),
        o || this._dstBuffers.push(this._bufferManager.createRawBuffer(8 * this._count, BufferUsage.MapRead | BufferUsage.CopyDst))
    }
    return Object.defineProperty(i.prototype, "querySet", {
        get: function() {
            return this._querySet
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype._getBuffer = function(e, t) {
        if (!this._canUseMultipleBuffers && this._dstBuffers.length === 0)
            return null;
        var r = this._device.createCommandEncoder(), n;
        return this._dstBuffers.length === 0 ? n = this._bufferManager.createRawBuffer(8 * this._count, BufferUsage.MapRead | BufferUsage.CopyDst) : (n = this._dstBuffers[this._dstBuffers.length - 1],
        this._dstBuffers.length--),
        r.resolveQuerySet(this._querySet, e, t, this._queryBuffer, 0),
        r.copyBufferToBuffer(this._queryBuffer, 0, n, 0, 8 * t),
        this._device.queue.submit([r.finish()]),
        n
    }
    ,
    i.prototype.readValues = function(e, t) {
        return e === void 0 && (e = 0),
        t === void 0 && (t = 1),
        __awaiter(this, void 0, void 0, function() {
            var r, n;
            return __generator(this, function(o) {
                switch (o.label) {
                case 0:
                    return r = this._getBuffer(e, t),
                    r === null ? [2, null] : [4, r.mapAsync(MapMode.Read)];
                case 1:
                    return o.sent(),
                    n = new BigUint64Array(r.getMappedRange()).slice(),
                    r.unmap(),
                    this._dstBuffers[this._dstBuffers.length] = r,
                    [2, n]
                }
            })
        })
    }
    ,
    i.prototype.readValue = function(e) {
        return e === void 0 && (e = 0),
        __awaiter(this, void 0, void 0, function() {
            var t, r, n;
            return __generator(this, function(o) {
                switch (o.label) {
                case 0:
                    return t = this._getBuffer(e, 1),
                    t === null ? [2, null] : [4, t.mapAsync(MapMode.Read)];
                case 1:
                    return o.sent(),
                    r = new BigUint64Array(t.getMappedRange()),
                    n = Number(r[0]),
                    t.unmap(),
                    this._dstBuffers[this._dstBuffers.length] = t,
                    [2, n]
                }
            })
        })
    }
    ,
    i.prototype.readTwoValuesAndSubtract = function(e) {
        return e === void 0 && (e = 0),
        __awaiter(this, void 0, void 0, function() {
            var t, r, n;
            return __generator(this, function(o) {
                switch (o.label) {
                case 0:
                    return t = this._getBuffer(e, 2),
                    t === null ? [2, null] : [4, t.mapAsync(MapMode.Read)];
                case 1:
                    return o.sent(),
                    r = new BigUint64Array(t.getMappedRange()),
                    n = Number(r[1] - r[0]),
                    t.unmap(),
                    this._dstBuffers[this._dstBuffers.length] = t,
                    [2, n]
                }
            })
        })
    }
    ,
    i.prototype.dispose = function() {
        this._querySet.destroy(),
        this._bufferManager.releaseBuffer(this._queryBuffer);
        for (var e = 0; e < this._dstBuffers.length; ++e)
            this._bufferManager.releaseBuffer(this._dstBuffers[e])
    }
    ,
    i
}()
  , WebGPUTimestampQuery = function() {
    function i(e, t) {
        this._enabled = !1,
        this._gpuFrameTimeCounter = new PerfCounter,
        this._measureDurationState = 0,
        this._device = e,
        this._bufferManager = t
    }
    return Object.defineProperty(i.prototype, "gpuFrameTimeCounter", {
        get: function() {
            return this._gpuFrameTimeCounter
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "enable", {
        get: function() {
            return this._enabled
        },
        set: function(e) {
            this._enabled !== e && (this._enabled = e,
            this._measureDurationState = 0,
            e ? this._measureDuration = new WebGPUDurationMeasure(this._device,this._bufferManager) : this._measureDuration.dispose())
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.startFrame = function(e) {
        this._enabled && this._measureDurationState === 0 && (this._measureDuration.start(e),
        this._measureDurationState = 1)
    }
    ,
    i.prototype.endFrame = function(e) {
        var t = this;
        this._measureDurationState === 1 && (this._measureDurationState = 2,
        this._measureDuration.stop(e).then(function(r) {
            r !== null && r >= 0 && (t._gpuFrameTimeCounter.fetchNewFrame(),
            t._gpuFrameTimeCounter.addCount(r, !0)),
            t._measureDurationState = 0
        }))
    }
    ,
    i
}()
  , WebGPUDurationMeasure = function() {
    function i(e, t) {
        this._querySet = new WebGPUQuerySet(2,QueryType.Timestamp,e,t)
    }
    return i.prototype.start = function(e) {
        e.writeTimestamp(this._querySet.querySet, 0)
    }
    ,
    i.prototype.stop = function(e) {
        return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(t) {
                return e.writeTimestamp(this._querySet.querySet, 1),
                [2, this._querySet.readTwoValuesAndSubtract(0)]
            })
        })
    }
    ,
    i.prototype.dispose = function() {
        this._querySet.dispose()
    }
    ,
    i
}()
  , WebGPUOcclusionQuery = function() {
    function i(e, t, r, n, o) {
        n === void 0 && (n = 50),
        o === void 0 && (o = 100),
        this._availableIndices = [],
        this._engine = e,
        this._device = t,
        this._bufferManager = r,
        this._frameLastBuffer = -1,
        this._currentTotalIndices = 0,
        this._countIncrement = o,
        this._allocateNewIndices(n)
    }
    return Object.defineProperty(i.prototype, "querySet", {
        get: function() {
            return this._querySet.querySet
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "hasQueries", {
        get: function() {
            return this._currentTotalIndices !== this._availableIndices.length
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "canBeginQuery", {
        get: function() {
            var e = this._engine._getCurrentRenderPassIndex();
            switch (e) {
            case 0:
                return this._engine._mainRenderPassWrapper.renderPassDescriptor.occlusionQuerySet !== void 0;
            case 1:
                return this._engine._rttRenderPassWrapper.renderPassDescriptor.occlusionQuerySet !== void 0
            }
            return !1
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.createQuery = function() {
        this._availableIndices.length === 0 && this._allocateNewIndices();
        var e = this._availableIndices[this._availableIndices.length - 1];
        return this._availableIndices.length--,
        e
    }
    ,
    i.prototype.deleteQuery = function(e) {
        this._availableIndices[this._availableIndices.length - 1] = e
    }
    ,
    i.prototype.isQueryResultAvailable = function(e) {
        return this._retrieveQueryBuffer(),
        !!this._lastBuffer && e < this._lastBuffer.length
    }
    ,
    i.prototype.getQueryResult = function(e) {
        var t, r;
        return Number((r = (t = this._lastBuffer) === null || t === void 0 ? void 0 : t[e]) !== null && r !== void 0 ? r : -1)
    }
    ,
    i.prototype._retrieveQueryBuffer = function() {
        var e = this;
        this._lastBuffer && this._frameLastBuffer === this._engine.frameId || this._frameLastBuffer !== this._engine.frameId && (this._frameLastBuffer = this._engine.frameId,
        this._querySet.readValues(0, this._currentTotalIndices).then(function(t) {
            e._lastBuffer = t
        }))
    }
    ,
    i.prototype._allocateNewIndices = function(e) {
        e = e != null ? e : this._countIncrement,
        this._delayQuerySetDispose();
        for (var t = 0; t < e; ++t)
            this._availableIndices.push(this._currentTotalIndices + t);
        this._currentTotalIndices += e,
        this._querySet = new WebGPUQuerySet(this._currentTotalIndices,QueryType.Occlusion,this._device,this._bufferManager,!1)
    }
    ,
    i.prototype._delayQuerySetDispose = function() {
        var e = this._querySet;
        e && setTimeout(function() {
            return e.dispose
        }, 1e3)
    }
    ,
    i.prototype.dispose = function() {
        var e;
        (e = this._querySet) === null || e === void 0 || e.dispose(),
        this._availableIndices = []
    }
    ,
    i
}()
  , WebGPUTintWASM = function() {
    function i() {
        this._twgsl = null
    }
    return i.prototype.initTwgsl = function(e) {
        return __awaiter(this, void 0, void 0, function() {
            var t;
            return __generator(this, function(r) {
                switch (r.label) {
                case 0:
                    return e = e || {},
                    e = __assign(__assign({}, i._twgslDefaultOptions), e),
                    e.twgsl ? (this._twgsl = e.twgsl,
                    [2, Promise.resolve()]) : e.jsPath && e.wasmPath ? IsWindowObjectExist() ? [4, Tools.LoadScriptAsync(e.jsPath)] : [3, 2] : [3, 3];
                case 1:
                    return r.sent(),
                    [3, 3];
                case 2:
                    importScripts(e.jsPath),
                    r.label = 3;
                case 3:
                    return self.twgsl ? (t = this,
                    [4, self.twgsl(e.wasmPath)]) : [3, 5];
                case 4:
                    return t._twgsl = r.sent(),
                    [2, Promise.resolve()];
                case 5:
                    return [2, Promise.reject("twgsl is not available.")]
                }
            })
        })
    }
    ,
    i.prototype.convertSpirV2WGSL = function(e) {
        return this._twgsl.convertSpirV2WGSL(e)
    }
    ,
    i._twgslDefaultOptions = {
        jsPath: "https://preview.babylonjs.com/twgsl/twgsl.js",
        wasmPath: "https://preview.babylonjs.com/twgsl/twgsl.wasm"
    },
    i
}()
  , WebGPUSnapshotRendering = function() {
    function i(e, t, r, n) {
        this._record = !1,
        this._play = !1,
        this._mainPassBundleList = [],
        this._enabled = !1,
        this._engine = e,
        this._mode = t,
        this._bundleList = r,
        this._bundleListRenderTarget = n
    }
    return Object.defineProperty(i.prototype, "enabled", {
        get: function() {
            return this._enabled
        },
        set: function(e) {
            this._mainPassBundleList.length = 0,
            this._record = this._enabled = e,
            this._play = !1,
            e && (this._modeSaved = this._mode,
            this._mode = 0)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "play", {
        get: function() {
            return this._play
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "record", {
        get: function() {
            return this._record
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "mode", {
        get: function() {
            return this._mode
        },
        set: function(e) {
            this._record ? this._modeSaved = e : this._mode = e
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.endMainRenderPass = function() {
        this._record && this._mainPassBundleList.push(this._bundleList.clone())
    }
    ,
    i.prototype.endRenderTargetPass = function(e, t) {
        var r, n, o, a;
        if (this._play)
            (n = (r = t._bundleLists) === null || r === void 0 ? void 0 : r[t._currentLayer]) === null || n === void 0 || n.run(e),
            this._mode === 1 && this._engine._reportDrawCall((a = (o = t._bundleLists) === null || o === void 0 ? void 0 : o[t._currentLayer]) === null || a === void 0 ? void 0 : a.numDrawCalls);
        else if (this._record)
            t._bundleLists || (t._bundleLists = []),
            t._bundleLists[t._currentLayer] = this._bundleListRenderTarget.clone(),
            t._bundleLists[t._currentLayer].run(e),
            this._bundleListRenderTarget.reset();
        else
            return !1;
        return !0
    }
    ,
    i.prototype.endFrame = function(e) {
        if (this._record && (this._mainPassBundleList.push(this._bundleList.clone()),
        this._record = !1,
        this._play = !0,
        this._mode = this._modeSaved),
        e !== null && this._play)
            for (var t = 0; t < this._mainPassBundleList.length; ++t)
                this._mainPassBundleList[t].run(e),
                this._mode === 1 && this._engine._reportDrawCall(this._mainPassBundleList[t].numDrawCalls)
    }
    ,
    i.prototype.reset = function() {
        this.enabled = !1,
        this.enabled = !0
    }
    ,
    i
}()
  , WebGPUEngine = function(i) {
    __extends(e, i);
    function e(t, r) {
        r === void 0 && (r = {});
        var n, o, a, s, l = i.call(this, null) || this;
        if (l._uploadEncoderDescriptor = {
            label: "upload"
        },
        l._renderEncoderDescriptor = {
            label: "render"
        },
        l._renderTargetEncoderDescriptor = {
            label: "renderTarget"
        },
        l._clearDepthValue = 1,
        l._clearReverseDepthValue = 0,
        l._clearStencilValue = 0,
        l._defaultSampleCount = 4,
        l._glslang = null,
        l._tintWASM = null,
        l._compiledComputeEffects = {},
        l._counters = {
            numEnableEffects: 0,
            numEnableDrawWrapper: 0,
            numBundleCreationNonCompatMode: 0,
            numBundleReuseNonCompatMode: 0
        },
        l.countersLastFrame = {
            numEnableEffects: 0,
            numEnableDrawWrapper: 0,
            numBundleCreationNonCompatMode: 0,
            numBundleReuseNonCompatMode: 0
        },
        l.numMaxUncapturedErrors = 20,
        l._commandBuffers = [null, null, null],
        l._currentRenderPass = null,
        l._mainRenderPassWrapper = new WebGPURenderPassWrapper,
        l._mainRenderPassCopyWrapper = new WebGPURenderPassWrapper,
        l._rttRenderPassWrapper = new WebGPURenderPassWrapper,
        l._pendingDebugCommands = [],
        l._onAfterUnbindFrameBufferObservable = new Observable,
        l._currentOverrideVertexBuffers = null,
        l._currentIndexBuffer = null,
        l.__colorWrite = !0,
        l._forceEnableEffect = !1,
        l.dbgShowShaderCode = !1,
        l.dbgSanityChecks = !0,
        l.dbgVerboseLogsForFirstFrames = !1,
        l.dbgVerboseLogsNumFrames = 10,
        l.dbgLogIfNotDrawWrapper = !0,
        l.dbgShowEmptyEnableEffectCalls = !0,
        l._viewportsCurrent = [{
            x: 0,
            y: 0,
            w: 0,
            h: 0
        }, {
            x: 0,
            y: 0,
            w: 0,
            h: 0
        }],
        l._scissorsCurrent = [{
            x: 0,
            y: 0,
            w: 0,
            h: 0
        }, {
            x: 0,
            y: 0,
            w: 0,
            h: 0
        }],
        l._scissorCached = {
            x: 0,
            y: 0,
            z: 0,
            w: 0
        },
        l._stencilRefsCurrent = [-1, -1],
        l._blendColorsCurrent = [[null, null, null, null], [null, null, null, null]],
        l.isNDCHalfZRange = !0,
        l.hasOriginBottomLeft = !1,
        r.deviceDescriptor = r.deviceDescriptor || {},
        r.swapChainFormat = r.swapChainFormat || TextureFormat.BGRA8Unorm,
        r.antialiasing = r.antialiasing === void 0 ? !0 : r.antialiasing,
        r.stencil = (n = r.stencil) !== null && n !== void 0 ? n : !0,
        r.enableGPUDebugMarkers = (o = r.enableGPUDebugMarkers) !== null && o !== void 0 ? o : !1,
        Logger$2.Log("Babylon.js v" + Engine.Version + " - " + l.description + " engine"),
        !navigator.gpu)
            return Logger$2.Error("WebGPU is not supported by your browser."),
            l;
        l._isWebGPU = !0,
        l._shaderPlatformName = "WEBGPU",
        r.deterministicLockstep === void 0 && (r.deterministicLockstep = !1),
        r.lockstepMaxSteps === void 0 && (r.lockstepMaxSteps = 4),
        r.audioEngine === void 0 && (r.audioEngine = !0),
        l._deterministicLockstep = r.deterministicLockstep,
        l._lockstepMaxSteps = r.lockstepMaxSteps,
        l._timeStep = r.timeStep || 1 / 60,
        l._doNotHandleContextLost = !!r.doNotHandleContextLost,
        l._canvas = t,
        l._options = r,
        l.premultipliedAlpha = (a = r.premultipliedAlpha) !== null && a !== void 0 ? a : !0;
        var u = IsWindowObjectExist() && window.devicePixelRatio || 1
          , c = r.limitDeviceRatio || u
          , h = (s = r.adaptToDeviceRatio) !== null && s !== void 0 ? s : !1;
        return l._hardwareScalingLevel = h ? 1 / Math.min(c, u) : 1,
        l._mainPassSampleCount = r.antialiasing ? l._defaultSampleCount : 1,
        l._isStencilEnable = r.stencil,
        l._sharedInit(t, !!r.doNotHandleTouchAction, r.audioEngine),
        l._shaderProcessor = new WebGPUShaderProcessorGLSL,
        l._shaderProcessorWGSL = new WebGPUShaderProcessorWGSL,
        l._invertYFinalFramebuffer = (!!l._options.forceCopyForInvertYFinalFramebuffer || !l._canvas.style) && !l._options.disableCopyForInvertYFinalFramebuffer,
        l._invertYFinalFramebuffer || l._canvas.style && (l._canvas.style.transform = "scaleY(-1)"),
        l
    }
    return Object.defineProperty(e.prototype, "snapshotRenderingMode", {
        get: function() {
            return this._snapshotRendering.mode
        },
        set: function(t) {
            this._snapshotRendering.mode = t
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.snapshotRenderingReset = function() {
        this._snapshotRendering.reset()
    }
    ,
    Object.defineProperty(e.prototype, "snapshotRendering", {
        get: function() {
            return this._snapshotRendering.enabled
        },
        set: function(t) {
            this._snapshotRendering.enabled = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "disableCacheSamplers", {
        get: function() {
            return this._cacheSampler ? this._cacheSampler.disabled : !1
        },
        set: function(t) {
            this._cacheSampler && (this._cacheSampler.disabled = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "disableCacheRenderPipelines", {
        get: function() {
            return this._cacheRenderPipeline ? this._cacheRenderPipeline.disabled : !1
        },
        set: function(t) {
            this._cacheRenderPipeline && (this._cacheRenderPipeline.disabled = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "disableCacheBindGroups", {
        get: function() {
            return this._cacheBindGroups ? this._cacheBindGroups.disabled : !1
        },
        set: function(t) {
            this._cacheBindGroups && (this._cacheBindGroups.disabled = t)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e, "IsSupportedAsync", {
        get: function() {
            return navigator.gpu ? navigator.gpu.requestAdapter().then(function(t) {
                return !!t
            }, function(t) {
                return !1
            }).catch(function(t) {
                return !1
            }) : Promise.resolve(!1)
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e, "IsSupported", {
        get: function() {
            return Logger$2.Warn("You must call IsSupportedAsync for WebGPU!"),
            !1
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "supportsUniformBuffers", {
        get: function() {
            return !0
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "supportedExtensions", {
        get: function() {
            return this._adapterSupportedExtensions
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "enabledExtensions", {
        get: function() {
            return this._deviceEnabledExtensions
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "name", {
        get: function() {
            return "WebGPU"
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "description", {
        get: function() {
            var t = this.name + this.version;
            return t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "version", {
        get: function() {
            return 1
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype.getInfo = function() {
        return {
            vendor: "unknown vendor",
            renderer: "unknown renderer",
            version: "unknown version"
        }
    }
    ,
    Object.defineProperty(e.prototype, "compatibilityMode", {
        get: function() {
            return this._compatibilityMode
        },
        set: function(t) {
            this._compatibilityMode = t
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(e.prototype, "currentSampleCount", {
        get: function() {
            return this._currentRenderTarget ? this._currentRenderTarget.samples : this._mainPassSampleCount
        },
        enumerable: !1,
        configurable: !0
    }),
    e.CreateAsync = function(t, r) {
        r === void 0 && (r = {});
        var n = new e(t,r);
        return new Promise(function(o) {
            n.initAsync(r.glslangOptions, r.twgslOptions).then(function() {
                return o(n)
            })
        }
        )
    }
    ,
    e.prototype.initAsync = function(t, r) {
        var n = this, o;
        return this._initGlslang(t != null ? t : (o = this._options) === null || o === void 0 ? void 0 : o.glslangOptions).then(function(a) {
            var s;
            return n._glslang = a,
            n._tintWASM = e.UseTWGSL ? new WebGPUTintWASM : null,
            n._tintWASM ? n._tintWASM.initTwgsl(r != null ? r : (s = n._options) === null || s === void 0 ? void 0 : s.twgslOptions).then(function() {
                return navigator.gpu.requestAdapter(n._options)
            }, function(l) {
                throw Logger$2.Error("Can not initialize twgsl!"),
                Logger$2.Error(l),
                Error("WebGPU initializations stopped.")
            }) : navigator.gpu.requestAdapter(n._options)
        }, function(a) {
            throw Logger$2.Error("Can not initialize glslang!"),
            Logger$2.Error(a),
            Error("WebGPU initializations stopped.")
        }).then(function(a) {
            var s;
            if (a) {
                n._adapter = a,
                n._adapterSupportedExtensions = [],
                (s = n._adapter.features) === null || s === void 0 || s.forEach(function(_) {
                    return n._adapterSupportedExtensions.push(_)
                });
                var l = n._options.deviceDescriptor;
                if (l != null && l.requiredFeatures) {
                    for (var u = l.requiredFeatures, c = [], h = 0, f = u; h < f.length; h++) {
                        var d = f[h];
                        n._adapterSupportedExtensions.indexOf(d) !== -1 && c.push(d)
                    }
                    l.requiredFeatures = c
                }
                return n._adapter.requestDevice(n._options.deviceDescriptor)
            } else
                throw "Could not retrieve a WebGPU adapter (adapter is null)."
        }).then(function(a) {
            var s, l;
            n._device = a,
            n._deviceEnabledExtensions = [],
            (s = n._device.features) === null || s === void 0 || s.forEach(function(c) {
                return n._deviceEnabledExtensions.push(c)
            });
            var u = -1;
            n._device.addEventListener("uncapturederror", function(c) {
                ++u < n.numMaxUncapturedErrors ? Logger$2.Warn("WebGPU uncaptured error (" + (u + 1) + "): " + c.error + " - " + c.error.message) : u++ === n.numMaxUncapturedErrors && Logger$2.Warn("WebGPU uncaptured error: too many warnings (" + n.numMaxUncapturedErrors + "), no more warnings will be reported to the console for this engine.")
            }),
            n._doNotHandleContextLost || (l = n._device.lost) === null || l === void 0 || l.then(function(c) {
                n._contextWasLost = !0,
                Logger$2.Warn("WebGPU context lost. " + c),
                n.onContextLostObservable.notifyObservers(n),
                n._restoreEngineAfterContextLost(n.initAsync.bind(n))
            })
        }, function(a) {
            Logger$2.Error("Could not retrieve a WebGPU device."),
            Logger$2.Error(a)
        }).then(function() {
            n._bufferManager = new WebGPUBufferManager(n._device),
            n._textureHelper = new WebGPUTextureHelper(n._device,n._glslang,n._tintWASM,n._bufferManager),
            n._cacheSampler = new WebGPUCacheSampler(n._device),
            n._cacheBindGroups = new WebGPUCacheBindGroups(n._device,n._cacheSampler,n),
            n._timestampQuery = new WebGPUTimestampQuery(n._device,n._bufferManager),
            n._occlusionQuery = n._device.createQuerySet ? new WebGPUOcclusionQuery(n,n._device,n._bufferManager) : void 0,
            n._bundleList = new WebGPUBundleList(n._device),
            n._bundleListRenderTarget = new WebGPUBundleList(n._device),
            n._snapshotRendering = new WebGPUSnapshotRendering(n,n._snapshotRenderingMode,n._bundleList,n._bundleListRenderTarget),
            n.dbgVerboseLogsForFirstFrames && n._count === void 0 && (n._count = 0,
            console.log("%c frame #" + n._count + " - begin", "background: #ffff00")),
            n._uploadEncoder = n._device.createCommandEncoder(n._uploadEncoderDescriptor),
            n._renderEncoder = n._device.createCommandEncoder(n._renderEncoderDescriptor),
            n._renderTargetEncoder = n._device.createCommandEncoder(n._renderTargetEncoderDescriptor),
            n._emptyVertexBuffer = new VertexBuffer(n,[0],"",!1,!1,1,!1,0,1),
            n._initializeLimits(),
            n._cacheRenderPipeline = new WebGPUCacheRenderPipelineTree(n._device,n._emptyVertexBuffer,!n._caps.textureFloatLinearFiltering),
            n._depthCullingState = new WebGPUDepthCullingState(n._cacheRenderPipeline),
            n._stencilStateComposer = new WebGPUStencilStateComposer(n._cacheRenderPipeline),
            n._stencilStateComposer.stencilGlobal = n._stencilState,
            n._depthCullingState.depthTest = !0,
            n._depthCullingState.depthFunc = 515,
            n._depthCullingState.depthMask = !0,
            n._textureHelper.setCommandEncoder(n._uploadEncoder),
            n._clearQuad = new WebGPUClearQuad(n._device,n,n._emptyVertexBuffer),
            n._defaultDrawContext = n.createDrawContext(),
            n._currentDrawContext = n._defaultDrawContext,
            n._defaultMaterialContext = n.createMaterialContext(),
            n._currentMaterialContext = n._defaultMaterialContext,
            n._initializeContextAndSwapChain(),
            n._initializeMainAttachments(),
            n.resize()
        }).catch(function(a) {
            Logger$2.Error("Can not create WebGPU Device and/or context."),
            Logger$2.Error(a),
            console.trace && console.trace()
        })
    }
    ,
    e.prototype._initGlslang = function(t) {
        return t = t || {},
        t = __assign(__assign({}, e._glslangDefaultOptions), t),
        t.glslang ? Promise.resolve(t.glslang) : self.glslang ? self.glslang(t.wasmPath) : t.jsPath && t.wasmPath ? IsWindowObjectExist() ? Tools.LoadScriptAsync(t.jsPath).then(function() {
            return self.glslang(t.wasmPath)
        }) : (importScripts(t.jsPath),
        self.glslang(t.wasmPath)) : Promise.reject("gslang is not available.")
    }
    ,
    e.prototype._initializeLimits = function() {
        this._caps = {
            maxTexturesImageUnits: 16,
            maxVertexTextureImageUnits: 16,
            maxCombinedTexturesImageUnits: 32,
            maxTextureSize: 8192,
            maxCubemapTextureSize: 2048,
            maxRenderTextureSize: 8192,
            maxVertexAttribs: 16,
            maxVaryingVectors: 15,
            maxFragmentUniformVectors: 1024,
            maxVertexUniformVectors: 1024,
            standardDerivatives: !0,
            astc: null,
            s3tc: this._deviceEnabledExtensions.indexOf(FeatureName.TextureCompressionBC) >= 0 ? !0 : void 0,
            pvrtc: null,
            etc1: null,
            etc2: null,
            bptc: this._deviceEnabledExtensions.indexOf(FeatureName.TextureCompressionBC) >= 0 ? !0 : void 0,
            maxAnisotropy: 4,
            uintIndices: !0,
            fragmentDepthSupported: !0,
            highPrecisionShaderSupported: !0,
            colorBufferFloat: !0,
            textureFloat: !0,
            textureFloatLinearFiltering: !1,
            textureFloatRender: !0,
            textureHalfFloat: !0,
            textureHalfFloatLinearFiltering: !0,
            textureHalfFloatRender: !0,
            textureLOD: !0,
            drawBuffersExtension: !0,
            depthTextureExtension: !0,
            vertexArrayObject: !1,
            instancedArrays: !0,
            timerQuery: typeof BigUint64Array != "undefined" && this.enabledExtensions.indexOf(FeatureName.TimestampQuery) !== -1 ? !0 : void 0,
            supportOcclusionQuery: typeof BigUint64Array != "undefined",
            canUseTimestampForTimerQuery: !0,
            multiview: !1,
            oculusMultiview: !1,
            parallelShaderCompile: void 0,
            blendMinMax: !0,
            maxMSAASamples: 4,
            canUseGLInstanceID: !0,
            canUseGLVertexID: !0,
            supportComputeShaders: !0,
            supportSRGBBuffers: !0
        },
        this._caps.parallelShaderCompile = null,
        this._features = {
            forceBitmapOverHTMLImageElement: !0,
            supportRenderAndCopyToLodForFloatTextures: !0,
            supportDepthStencilTexture: !0,
            supportShadowSamplers: !0,
            uniformBufferHardCheckMatrix: !1,
            allowTexturePrefiltering: !0,
            trackUbosInFrame: !0,
            checkUbosContentBeforeUpload: !0,
            supportCSM: !0,
            basisNeedsPOT: !1,
            support3DTextures: !0,
            needTypeSuffixInShaderConstants: !0,
            supportMSAA: !0,
            supportSSAO2: !0,
            supportExtendedTextureFormats: !0,
            supportSwitchCaseInShader: !0,
            supportSyncTextureRead: !1,
            needsInvertingBitmap: !1,
            useUBOBindingCache: !1,
            needShaderCodeInlining: !0,
            needToAlwaysBindUniformBuffers: !0,
            supportRenderPasses: !0,
            _collectUbosUpdatedInFrame: !1
        }
    }
    ,
    e.prototype._initializeContextAndSwapChain = function() {
        this._context = this._canvas.getContext("webgpu"),
        this._configureContext(this._canvas.width, this._canvas.height),
        this._colorFormat = this._options.swapChainFormat,
        this._mainRenderPassWrapper.colorAttachmentGPUTextures = [new WebGPUHardwareTexture],
        this._mainRenderPassWrapper.colorAttachmentGPUTextures[0].format = this._colorFormat,
        this._invertYFinalFramebuffer && (this._mainRenderPassCopyWrapper.colorAttachmentGPUTextures = [new WebGPUHardwareTexture],
        this._mainRenderPassCopyWrapper.colorAttachmentGPUTextures[0].format = this._colorFormat)
    }
    ,
    e.prototype._initializeMainAttachments = function() {
        var t, r;
        this._mainTextureExtends = {
            width: this.getRenderWidth(),
            height: this.getRenderHeight(),
            depthOrArrayLayers: 1
        };
        var n;
        if (this._options.antialiasing) {
            var o = {
                size: this._mainTextureExtends,
                mipLevelCount: 1,
                sampleCount: this._mainPassSampleCount,
                dimension: TextureDimension.E2d,
                format: this._options.swapChainFormat,
                usage: TextureUsage.RenderAttachment
            };
            (t = this._mainTexture) === null || t === void 0 || t.destroy(),
            this._mainTexture = this._device.createTexture(o),
            n = [{
                view: this._mainTexture.createView(),
                loadValue: new Color4(0,0,0,1),
                storeOp: StoreOp.Store
            }]
        } else
            n = [{
                view: void 0,
                loadValue: new Color4(0,0,0,1),
                storeOp: StoreOp.Store
            }];
        if (this._invertYFinalFramebuffer) {
            var a = {
                size: this._mainTextureExtends,
                mipLevelCount: 1,
                sampleCount: 1,
                dimension: TextureDimension.E2d,
                format: this._options.swapChainFormat,
                usage: TextureUsage.RenderAttachment | TextureUsage.TextureBinding
            };
            (r = this._mainTextureLastCopy) === null || r === void 0 || r.destroy(),
            this._mainTextureLastCopy = this._device.createTexture(a),
            this._options.antialiasing ? n[0].resolveTarget = this._mainTextureLastCopy.createView() : n[0].view = this._mainTextureLastCopy.createView(),
            this._mainRenderPassCopyWrapper.renderPassDescriptor = {
                colorAttachments: [{
                    view: void 0,
                    loadValue: new Color4(0,0,0,1),
                    storeOp: StoreOp.Store
                }]
            }
        }
        this._mainRenderPassWrapper.depthTextureFormat = this.isStencilEnable ? TextureFormat.Depth24PlusStencil8 : TextureFormat.Depth32Float,
        this._setDepthTextureFormat(this._mainRenderPassWrapper);
        var s = {
            size: this._mainTextureExtends,
            mipLevelCount: 1,
            sampleCount: this._mainPassSampleCount,
            dimension: TextureDimension.E2d,
            format: this._mainRenderPassWrapper.depthTextureFormat,
            usage: TextureUsage.RenderAttachment
        };
        this._depthTexture && this._depthTexture.destroy(),
        this._depthTexture = this._device.createTexture(s);
        var l = {
            view: this._depthTexture.createView(),
            depthLoadValue: this._clearDepthValue,
            depthStoreOp: StoreOp.Store,
            stencilLoadValue: this._clearStencilValue,
            stencilStoreOp: StoreOp.Store
        };
        this._mainRenderPassWrapper.renderPassDescriptor = {
            colorAttachments: n,
            depthStencilAttachment: l
        },
        this._mainRenderPassWrapper.renderPass !== null && this._endMainRenderPass()
    }
    ,
    e.prototype._configureContext = function(t, r) {
        this._context.configure({
            device: this._device,
            format: this._options.swapChainFormat,
            usage: TextureUsage.RenderAttachment | TextureUsage.CopySrc,
            compositingAlphaMode: this.premultipliedAlpha ? CanvasCompositingAlphaMode.Premultiplied : CanvasCompositingAlphaMode.Opaque,
            size: {
                width: t,
                height: r,
                depthOrArrayLayers: 1
            }
        })
    }
    ,
    e.prototype.setSize = function(t, r, n) {
        return n === void 0 && (n = !1),
        i.prototype.setSize.call(this, t, r, n) ? (this.dbgVerboseLogsForFirstFrames && (this._count === void 0 && (this._count = 0),
        (!this._count || this._count < this.dbgVerboseLogsNumFrames) && console.log("frame #" + this._count + " - setSize called -", t, r)),
        this._configureContext(t, r),
        this._initializeMainAttachments(),
        this.snapshotRendering && this.snapshotRenderingReset(),
        !0) : !1
    }
    ,
    e.prototype._getShaderProcessor = function(t) {
        return t === ShaderLanguage.WGSL ? this._shaderProcessorWGSL : this._shaderProcessor
    }
    ,
    e.prototype._getShaderProcessingContext = function(t) {
        return new WebGPUShaderProcessingContext(t)
    }
    ,
    e.prototype.applyStates = function() {
        this._stencilStateComposer.apply(),
        this._cacheRenderPipeline.setAlphaBlendEnabled(this._alphaState.alphaBlend)
    }
    ,
    e.prototype.wipeCaches = function(t) {
        this.preventCacheWipeBetweenFrames && !t || (this._forceEnableEffect = !0,
        this._currentIndexBuffer = null,
        this._currentOverrideVertexBuffers = null,
        this._cacheRenderPipeline.setBuffers(null, null, null),
        t && (this._stencilStateComposer.reset(),
        this._depthCullingState.reset(),
        this._depthCullingState.depthFunc = 515,
        this._alphaState.reset(),
        this._alphaMode = 1,
        this._alphaEquation = 0,
        this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters, this._alphaState._blendEquationParameters),
        this._cacheRenderPipeline.setAlphaBlendEnabled(!1),
        this.setColorWrite(!0)),
        this._cachedVertexBuffers = null,
        this._cachedIndexBuffer = null,
        this._cachedEffectForVertexBuffers = null)
    }
    ,
    e.prototype.setColorWrite = function(t) {
        this.__colorWrite = t,
        this._cacheRenderPipeline.setWriteMask(t ? 15 : 0)
    }
    ,
    e.prototype.getColorWrite = function() {
        return this.__colorWrite
    }
    ,
    e.prototype._resetCurrentViewport = function(t) {
        this._viewportsCurrent[t].x = 0,
        this._viewportsCurrent[t].y = 0,
        this._viewportsCurrent[t].w = 0,
        this._viewportsCurrent[t].h = 0,
        t === 1 && (this._viewportCached.x = 0,
        this._viewportCached.y = 0,
        this._viewportCached.z = 0,
        this._viewportCached.w = 0)
    }
    ,
    e.prototype._mustUpdateViewport = function(t) {
        var r = t === this._mainRenderPassWrapper.renderPass ? 0 : 1
          , n = this._viewportCached.x
          , o = this._viewportCached.y
          , a = this._viewportCached.z
          , s = this._viewportCached.w
          , l = this._viewportsCurrent[r].x !== n || this._viewportsCurrent[r].y !== o || this._viewportsCurrent[r].w !== a || this._viewportsCurrent[r].h !== s;
        return l && (this._viewportsCurrent[r].x = this._viewportCached.x,
        this._viewportsCurrent[r].y = this._viewportCached.y,
        this._viewportsCurrent[r].w = this._viewportCached.z,
        this._viewportsCurrent[r].h = this._viewportCached.w),
        l
    }
    ,
    e.prototype._applyViewport = function(t) {
        t.setViewport(Math.floor(this._viewportCached.x), Math.floor(this._viewportCached.y), Math.floor(this._viewportCached.z), Math.floor(this._viewportCached.w), 0, 1),
        this.dbgVerboseLogsForFirstFrames && (this._count === void 0 && (this._count = 0),
        (!this._count || this._count < this.dbgVerboseLogsNumFrames) && console.log("frame #" + this._count + " - viewport applied - (", this._viewportCached.x, this._viewportCached.y, this._viewportCached.z, this._viewportCached.w, ") current pass is main pass=" + (t === this._mainRenderPassWrapper.renderPass)))
    }
    ,
    e.prototype._viewport = function(t, r, n, o) {
        this._viewportCached.x = t,
        this._viewportCached.y = r,
        this._viewportCached.z = n,
        this._viewportCached.w = o
    }
    ,
    e.prototype._resetCurrentScissor = function(t) {
        this._scissorsCurrent[t].x = 0,
        this._scissorsCurrent[t].y = 0,
        this._scissorsCurrent[t].w = 0,
        this._scissorsCurrent[t].h = 0
    }
    ,
    e.prototype._mustUpdateScissor = function(t) {
        var r = t === this._mainRenderPassWrapper.renderPass ? 0 : 1
          , n = this._scissorCached.x
          , o = this._scissorCached.y
          , a = this._scissorCached.z
          , s = this._scissorCached.w
          , l = this._scissorsCurrent[r].x !== n || this._scissorsCurrent[r].y !== o || this._scissorsCurrent[r].w !== a || this._scissorsCurrent[r].h !== s;
        return l && (this._scissorsCurrent[r].x = this._scissorCached.x,
        this._scissorsCurrent[r].y = this._scissorCached.y,
        this._scissorsCurrent[r].w = this._scissorCached.z,
        this._scissorsCurrent[r].h = this._scissorCached.w),
        l
    }
    ,
    e.prototype._applyScissor = function(t) {
        t.setScissorRect(this._scissorCached.x, this._scissorCached.y, this._scissorCached.z, this._scissorCached.w),
        this.dbgVerboseLogsForFirstFrames && (this._count === void 0 && (this._count = 0),
        (!this._count || this._count < this.dbgVerboseLogsNumFrames) && console.log("frame #" + this._count + " - scissor applied - (", this._scissorCached.x, this._scissorCached.y, this._scissorCached.z, this._scissorCached.w, ") current pass is main pass=" + (t === this._mainRenderPassWrapper.renderPass)))
    }
    ,
    e.prototype._scissorIsActive = function() {
        return this._scissorCached.x !== 0 || this._scissorCached.y !== 0 || this._scissorCached.z !== 0 || this._scissorCached.w !== 0
    }
    ,
    e.prototype.enableScissor = function(t, r, n, o) {
        this._scissorCached.x = t,
        this._scissorCached.y = r,
        this._scissorCached.z = n,
        this._scissorCached.w = o
    }
    ,
    e.prototype.disableScissor = function() {
        this._scissorCached.x = 0,
        this._scissorCached.y = 0,
        this._scissorCached.z = 0,
        this._scissorCached.w = 0,
        this._resetCurrentScissor(0),
        this._resetCurrentScissor(1)
    }
    ,
    e.prototype._resetCurrentStencilRef = function(t) {
        this._stencilRefsCurrent[t] = -1
    }
    ,
    e.prototype._mustUpdateStencilRef = function(t) {
        var r = t === this._mainRenderPassWrapper.renderPass ? 0 : 1
          , n = this._stencilStateComposer.funcRef !== this._stencilRefsCurrent[r];
        return n && (this._stencilRefsCurrent[r] = this._stencilStateComposer.funcRef),
        n
    }
    ,
    e.prototype._applyStencilRef = function(t) {
        var r;
        t.setStencilReference((r = this._stencilStateComposer.funcRef) !== null && r !== void 0 ? r : 0)
    }
    ,
    e.prototype._resetCurrentColorBlend = function(t) {
        this._blendColorsCurrent[t][0] = this._blendColorsCurrent[t][1] = this._blendColorsCurrent[t][2] = this._blendColorsCurrent[t][3] = null
    }
    ,
    e.prototype._mustUpdateBlendColor = function(t) {
        var r = t === this._mainRenderPassWrapper.renderPass ? 0 : 1
          , n = this._alphaState._blendConstants
          , o = n[0] !== this._blendColorsCurrent[r][0] || n[1] !== this._blendColorsCurrent[r][1] || n[2] !== this._blendColorsCurrent[r][2] || n[3] !== this._blendColorsCurrent[r][3];
        return o && (this._blendColorsCurrent[r][0] = n[0],
        this._blendColorsCurrent[r][1] = n[1],
        this._blendColorsCurrent[r][2] = n[2],
        this._blendColorsCurrent[r][3] = n[3]),
        o
    }
    ,
    e.prototype._applyBlendColor = function(t) {
        t.setBlendConstant(this._alphaState._blendConstants)
    }
    ,
    e.prototype.clear = function(t, r, n, o) {
        o === void 0 && (o = !1),
        t && t.a === void 0 && (t.a = 1);
        var a = this._scissorIsActive();
        this.dbgVerboseLogsForFirstFrames && (this._count === void 0 && (this._count = 0),
        (!this._count || this._count < this.dbgVerboseLogsNumFrames) && console.log("frame #" + this._count + " - clear called - backBuffer=", r, " depth=", n, " stencil=", o, " scissor is active=", a)),
        this._currentRenderTarget ? a ? (this._rttRenderPassWrapper.renderPass || this._startRenderTargetRenderPass(this._currentRenderTarget, !1, r ? t : null, n, o),
        this.compatibilityMode ? this._applyScissor(this._currentRenderPass) : this._bundleListRenderTarget.addItem(new WebGPURenderItemScissor(this._scissorCached.x,this._scissorCached.y,this._scissorCached.z,this._scissorCached.w)),
        this._clearFullQuad(r ? t : null, n, o)) : (this._currentRenderPass && this._endRenderTargetRenderPass(),
        this._startRenderTargetRenderPass(this._currentRenderTarget, !0, r ? t : null, n, o)) : ((!this._mainRenderPassWrapper.renderPass || !a) && this._startMainRenderPass(!a, r ? t : null, n, o),
        a && (this.compatibilityMode ? this._applyScissor(this._currentRenderPass) : this._bundleList.addItem(new WebGPURenderItemScissor(this._scissorCached.x,this._scissorCached.y,this._scissorCached.z,this._scissorCached.w)),
        this._clearFullQuad(r ? t : null, n, o)))
    }
    ,
    e.prototype._clearFullQuad = function(t, r, n) {
        var o, a, s, l = this.compatibilityMode ? this._getCurrentRenderPass() : null, u = this._getCurrentRenderPassIndex(), c = u === 0 ? this._bundleList : this._bundleListRenderTarget;
        this._clearQuad.setColorFormat(this._colorFormat),
        this._clearQuad.setDepthStencilFormat(this._depthTextureFormat),
        this._clearQuad.setMRTAttachments((o = this._cacheRenderPipeline.mrtAttachments) !== null && o !== void 0 ? o : [], (a = this._cacheRenderPipeline.mrtTextureArray) !== null && a !== void 0 ? a : []),
        this.compatibilityMode ? l.setStencilReference(this._clearStencilValue) : c.addItem(new WebGPURenderItemStencilRef(this._clearStencilValue));
        var h = this._clearQuad.clear(l, t, r, n, this.currentSampleCount);
        this.compatibilityMode ? this._applyStencilRef(l) : (c.addBundle(h),
        c.addItem(new WebGPURenderItemStencilRef((s = this._stencilStateComposer.funcRef) !== null && s !== void 0 ? s : 0)),
        this._reportDrawCall())
    }
    ,
    e.prototype.createVertexBuffer = function(t) {
        var r;
        t instanceof Array ? r = new Float32Array(t) : t instanceof ArrayBuffer ? r = new Uint8Array(t) : r = t;
        var n = this._bufferManager.createBuffer(r, BufferUsage.Vertex | BufferUsage.CopyDst);
        return n
    }
    ,
    e.prototype.createDynamicVertexBuffer = function(t) {
        return this.createVertexBuffer(t)
    }
    ,
    e.prototype.createIndexBuffer = function(t, r) {
        var n = !0, o;
        t instanceof Uint32Array || t instanceof Int32Array ? o = t : t instanceof Uint16Array ? (o = t,
        n = !1) : t.length > 65535 ? o = new Uint32Array(t) : (o = new Uint16Array(t),
        n = !1);
        var a = this._bufferManager.createBuffer(o, BufferUsage.Index | BufferUsage.CopyDst);
        return a.is32Bits = n,
        a
    }
    ,
    e.prototype._createBuffer = function(t, r) {
        var n;
        t instanceof Array ? n = new Float32Array(t) : t instanceof ArrayBuffer ? n = new Uint8Array(t) : n = t;
        var o = 0;
        return r & 1 && (o |= BufferUsage.CopySrc),
        r & 2 && (o |= BufferUsage.CopyDst),
        r & 4 && (o |= BufferUsage.Uniform),
        r & 8 && (o |= BufferUsage.Vertex),
        r & 16 && (o |= BufferUsage.Index),
        r & 32 && (o |= BufferUsage.Storage),
        this._bufferManager.createBuffer(n, o)
    }
    ,
    e.prototype.bindBuffersDirectly = function(t, r, n, o, a) {
        throw "Not implemented on WebGPU"
    }
    ,
    e.prototype.updateAndBindInstancesBuffer = function(t, r, n) {
        throw "Not implemented on WebGPU"
    }
    ,
    e.prototype.bindBuffers = function(t, r, n, o) {
        this._currentIndexBuffer = r,
        this._currentOverrideVertexBuffers = o != null ? o : null,
        this._cacheRenderPipeline.setBuffers(t, r, this._currentOverrideVertexBuffers)
    }
    ,
    e.prototype._releaseBuffer = function(t) {
        return this._bufferManager.releaseBuffer(t)
    }
    ,
    e.prototype.createEffect = function(t, r, n, o, a, s, l, u, c, h) {
        var f;
        h === void 0 && (h = ShaderLanguage.GLSL);
        var d = t.vertexElement || t.vertex || t.vertexToken || t.vertexSource || t
          , _ = t.fragmentElement || t.fragment || t.fragmentToken || t.fragmentSource || t
          , g = this._getGlobalDefines()
          , m = (f = a != null ? a : r.defines) !== null && f !== void 0 ? f : "";
        g && (m += `
` + g);
        var v = d + "+" + _ + "@" + m;
        if (this._compiledEffects[v]) {
            var y = this._compiledEffects[v];
            return l && y.isReady() && l(y),
            y
        }
        var b = new Effect(t,r,n,o,this,a,s,l,u,c,v,h);
        return this._compiledEffects[v] = b,
        b
    }
    ,
    e.prototype._compileRawShaderToSpirV = function(t, r) {
        return this._glslang.compileGLSL(t, r)
    }
    ,
    e.prototype._compileShaderToSpirV = function(t, r, n, o) {
        return this._compileRawShaderToSpirV(o + (n ? n + `
` : "") + t, r)
    }
    ,
    e.prototype._getWGSLShader = function(t, r, n, o) {
        return n ? n = "//" + n.split(`
`).join(`
//`) + `
` : n = "",
        n + t
    }
    ,
    e.prototype._createPipelineStageDescriptor = function(t, r, n) {
        return this._tintWASM && n === ShaderLanguage.GLSL && (t = this._tintWASM.convertSpirV2WGSL(t),
        r = this._tintWASM.convertSpirV2WGSL(r)),
        {
            vertexStage: {
                module: this._device.createShaderModule({
                    code: t
                }),
                entryPoint: "main"
            },
            fragmentStage: {
                module: this._device.createShaderModule({
                    code: r
                }),
                entryPoint: "main"
            }
        }
    }
    ,
    e.prototype._compileRawPipelineStageDescriptor = function(t, r, n) {
        var o = n === ShaderLanguage.GLSL ? this._compileRawShaderToSpirV(t, "vertex") : t
          , a = n === ShaderLanguage.GLSL ? this._compileRawShaderToSpirV(r, "fragment") : r;
        return this._createPipelineStageDescriptor(o, a, n)
    }
    ,
    e.prototype._compilePipelineStageDescriptor = function(t, r, n, o) {
        this.onBeforeShaderCompilationObservable.notifyObservers(this);
        var a = `#version 450
`
          , s = o === ShaderLanguage.GLSL ? this._compileShaderToSpirV(t, "vertex", n, a) : this._getWGSLShader(t, "vertex", n, a)
          , l = o === ShaderLanguage.GLSL ? this._compileShaderToSpirV(r, "fragment", n, a) : this._getWGSLShader(r, "fragment", n, a)
          , u = this._createPipelineStageDescriptor(s, l, o);
        return this.onAfterShaderCompilationObservable.notifyObservers(this),
        u
    }
    ,
    e.prototype.createRawShaderProgram = function(t, r, n, o, a) {
        throw "Not available on WebGPU"
    }
    ,
    e.prototype.createShaderProgram = function(t, r, n, o, a, s) {
        throw "Not available on WebGPU"
    }
    ,
    e.prototype.inlineShaderCode = function(t) {
        var r = new ShaderCodeInliner(t);
        return r.debug = !1,
        r.processCode(),
        r.code
    }
    ,
    e.prototype.createPipelineContext = function(t) {
        return new WebGPUPipelineContext(t,this)
    }
    ,
    e.prototype.createMaterialContext = function() {
        return new WebGPUMaterialContext
    }
    ,
    e.prototype.createDrawContext = function() {
        return new WebGPUDrawContext(this._bufferManager)
    }
    ,
    e.prototype._preparePipelineContext = function(t, r, n, o, a, s, l, u, c, h) {
        var f = t
          , d = f.shaderProcessingContext.shaderLanguage;
        this.dbgShowShaderCode && (console.log(u),
        console.log(r),
        console.log(n)),
        f.sources = {
            fragment: n,
            vertex: r,
            rawVertex: a,
            rawFragment: s
        },
        o ? f.stages = this._compileRawPipelineStageDescriptor(r, n, d) : f.stages = this._compilePipelineStageDescriptor(r, n, u, d)
    }
    ,
    e.prototype.getAttributes = function(t, r) {
        for (var n = new Array(r.length), o = t, a = 0; a < r.length; a++) {
            var s = r[a]
              , l = o.shaderProcessingContext.availableAttributes[s];
            l !== void 0 && (n[a] = l)
        }
        return n
    }
    ,
    e.prototype.enableEffect = function(t) {
        if (!!t) {
            var r = !0;
            if (!DrawWrapper.IsWrapper(t))
                r = t !== this._currentEffect,
                this._currentEffect = t,
                this._currentMaterialContext = this._defaultMaterialContext,
                this._currentDrawContext = this._defaultDrawContext,
                this._counters.numEnableEffects++,
                this.dbgLogIfNotDrawWrapper && Logger$2.Warn("enableEffect has been called with an Effect and not a Wrapper! effect.uniqueId=" + t.uniqueId + ", effect.name=" + t.name + ", effect.name.vertex=" + t.name.vertex + ", effect.name.fragment=" + t.name.fragment, 10);
            else if (!t.effect || t.effect === this._currentEffect && t.materialContext === this._currentMaterialContext && t.drawContext === this._currentDrawContext && !this._forceEnableEffect) {
                if (!t.effect && this.dbgShowEmptyEnableEffectCalls)
                    throw console.error("drawWrapper=", t),
                    "Invalid call to enableEffect: the effect property is empty!";
                return
            } else if (r = t.effect !== this._currentEffect,
            this._currentEffect = t.effect,
            this._currentMaterialContext = t.materialContext,
            this._currentDrawContext = t.drawContext,
            this._counters.numEnableDrawWrapper++,
            !this._currentMaterialContext)
                throw console.error("drawWrapper=", t),
                "Invalid call to enableEffect: the materialContext property is empty!";
            this._stencilStateComposer.stencilMaterial = void 0,
            this._forceEnableEffect = r || this._forceEnableEffect ? !1 : this._forceEnableEffect,
            r && (this._currentEffect.onBind && this._currentEffect.onBind(this._currentEffect),
            this._currentEffect._onBindObservable && this._currentEffect._onBindObservable.notifyObservers(this._currentEffect))
        }
    }
    ,
    e.prototype._releaseEffect = function(t) {
        this._compiledEffects[t._key] && (delete this._compiledEffects[t._key],
        this._deletePipelineContext(t.getPipelineContext()))
    }
    ,
    e.prototype.releaseEffects = function() {
        for (var t in this._compiledEffects) {
            var r = this._compiledEffects[t].getPipelineContext();
            this._deletePipelineContext(r)
        }
        this._compiledEffects = {}
    }
    ,
    e.prototype._deletePipelineContext = function(t) {
        var r = t;
        r && t.dispose()
    }
    ,
    Object.defineProperty(e.prototype, "needPOTTextures", {
        get: function() {
            return !1
        },
        enumerable: !1,
        configurable: !0
    }),
    e.prototype._createHardwareTexture = function() {
        return new WebGPUHardwareTexture
    }
    ,
    e.prototype._releaseTexture = function(t) {
        var r = this._internalTexturesCache.indexOf(t);
        r !== -1 && this._internalTexturesCache.splice(r, 1),
        this._textureHelper.releaseTexture(t)
    }
    ,
    e.prototype._getRGBABufferInternalSizedFormat = function(t, r) {
        return 5
    }
    ,
    e.prototype.updateTextureComparisonFunction = function(t, r) {
        t._comparisonFunction = r
    }
    ,
    e.prototype._createInternalTexture = function(t, r, n, o) {
        var a, s;
        n === void 0 && (n = !0),
        o === void 0 && (o = InternalTextureSource.Unknown);
        var l = {};
        r !== void 0 && typeof r == "object" ? (l.generateMipMaps = r.generateMipMaps,
        l.type = r.type === void 0 ? 0 : r.type,
        l.samplingMode = r.samplingMode === void 0 ? 3 : r.samplingMode,
        l.format = r.format === void 0 ? 5 : r.format,
        l.samples = (a = r.samples) !== null && a !== void 0 ? a : 1,
        l.creationFlags = (s = r.creationFlags) !== null && s !== void 0 ? s : 0) : (l.generateMipMaps = r,
        l.type = 0,
        l.samplingMode = 3,
        l.format = 5,
        l.samples = 1,
        l.creationFlags = 0),
        (l.type === 1 && !this._caps.textureFloatLinearFiltering || l.type === 2 && !this._caps.textureHalfFloatLinearFiltering) && (l.samplingMode = 1),
        l.type === 1 && !this._caps.textureFloat && (l.type = 0,
        Logger$2.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));
        var u = new InternalTexture(this,o)
          , c = t.width || t
          , h = t.height || t
          , f = t.layers || 0;
        return u.baseWidth = c,
        u.baseHeight = h,
        u.width = c,
        u.height = h,
        u.depth = f,
        u.isReady = !0,
        u.samples = l.samples,
        u.generateMipMaps = !!l.generateMipMaps,
        u.samplingMode = l.samplingMode,
        u.type = l.type,
        u.format = l.format,
        u.is2DArray = f > 0,
        u._cachedWrapU = 0,
        u._cachedWrapV = 0,
        this._internalTexturesCache.push(u),
        n || this._textureHelper.createGPUTextureForInternalTexture(u, c, h, f || 1, l.creationFlags),
        u
    }
    ,
    e.prototype.createTexture = function(t, r, n, o, a, s, l, u, c, h, f, d, _, g, m) {
        var v = this;
        return a === void 0 && (a = 3),
        s === void 0 && (s = null),
        l === void 0 && (l = null),
        u === void 0 && (u = null),
        c === void 0 && (c = null),
        h === void 0 && (h = null),
        f === void 0 && (f = null),
        this._createTextureBase(t, r, n, o, a, s, l, function(y, b, T, C, A, S, P, R, M) {
            var x, I = C;
            if (y.baseWidth = I.width,
            y.baseHeight = I.height,
            y.width = I.width,
            y.height = I.height,
            y.format = h != null ? h : -1,
            R(y.width, y.height, I, b, y, function() {}),
            !((x = y._hardwareTexture) === null || x === void 0) && x.underlyingResource)
                !S && !P && v._generateMipmaps(y, v._uploadEncoder);
            else {
                var w = v._textureHelper.createGPUTextureForInternalTexture(y, I.width, I.height, void 0, g);
                WebGPUTextureHelper.IsImageBitmap(I) && (v._textureHelper.updateTexture(I, y, I.width, I.height, y.depth, w.format, 0, 0, A, !1, 0, 0, v._uploadEncoder),
                !S && !P && v._generateMipmaps(y, v._uploadEncoder))
            }
            T && T._removePendingData(y),
            y.isReady = !0,
            y.onLoadedObservable.notifyObservers(y),
            y.onLoadedObservable.clear()
        }, function() {
            return !1
        }, u, c, h, f, d, _, m)
    }
    ,
    e.prototype.generateMipMapsForCubemap = function(t, r) {
        var n;
        if (t.generateMipMaps) {
            var o = (n = t._hardwareTexture) === null || n === void 0 ? void 0 : n.underlyingResource;
            o || this._textureHelper.createGPUTextureForInternalTexture(t),
            this._generateMipmaps(t, t.source === InternalTextureSource.RenderTarget || t.source === InternalTextureSource.MultiRenderTarget ? this._renderTargetEncoder : void 0)
        }
    }
    ,
    e.prototype.updateTextureSamplingMode = function(t, r, n) {
        n === void 0 && (n = !1),
        n && (r.generateMipMaps = !0,
        this._generateMipmaps(r)),
        r.samplingMode = t
    }
    ,
    e.prototype.updateTextureWrappingMode = function(t, r, n, o) {
        n === void 0 && (n = null),
        o === void 0 && (o = null),
        r !== null && (t._cachedWrapU = r),
        n !== null && (t._cachedWrapV = n),
        (t.is2DArray || t.is3D) && o !== null && (t._cachedWrapR = o)
    }
    ,
    e.prototype.updateTextureDimensions = function(t, r, n, o) {
        if (o === void 0 && (o = 1),
        !!t._hardwareTexture && !(t.width === r && t.height === n && t.depth === o)) {
            var a = t._hardwareTexture.textureAdditionalUsages;
            t._hardwareTexture.release(),
            this._textureHelper.createGPUTextureForInternalTexture(t, r, n, o, a)
        }
    }
    ,
    e.prototype._setInternalTexture = function(t, r, n, o) {
        if (n = n != null ? n : t,
        this._currentEffect) {
            var a = this._currentEffect._pipelineContext
              , s = a.shaderProcessingContext.availableTextures[n];
            if (this._currentMaterialContext.setTexture(t, r),
            s && s.autoBindSampler) {
                var l = n + WebGPUShaderProcessor.AutoSamplerSuffix;
                this._currentMaterialContext.setSampler(l, r)
            }
        }
    }
    ,
    e.prototype.setTexture = function(t, r, n, o) {
        this._setTexture(t, n, !1, !1, o, o)
    }
    ,
    e.prototype.setTextureArray = function(t, r, n, o) {
        for (var a = 0; a < n.length; a++)
            this._setTexture(-1, n[a], !0, !1, o + a.toString(), o, a)
    }
    ,
    e.prototype._setTexture = function(t, r, n, o, a, s, l) {
        if (o === void 0 && (o = !1),
        a === void 0 && (a = ""),
        l === void 0 && (l = 0),
        s = s != null ? s : a,
        this._currentEffect) {
            if (!r)
                return this._currentMaterialContext.setTexture(a, null),
                !1;
            if (r.video)
                r.update();
            else if (r.delayLoadState === 4)
                return r.delayLoad(),
                !1;
            var u = null;
            if (o ? u = r.depthStencilTexture : r.isReady() ? u = r.getInternalTexture() : r.isCube ? u = this.emptyCubeTexture : r.is3D ? u = this.emptyTexture3D : r.is2DArray ? u = this.emptyTexture2DArray : u = this.emptyTexture,
            u && !u.isMultiview) {
                if (u.isCube && u._cachedCoordinatesMode !== r.coordinatesMode) {
                    u._cachedCoordinatesMode = r.coordinatesMode;
                    var c = r.coordinatesMode !== 3 && r.coordinatesMode !== 5 ? 1 : 0;
                    r.wrapU = c,
                    r.wrapV = c
                }
                u._cachedWrapU = r.wrapU,
                u._cachedWrapV = r.wrapV,
                u.is3D && (u._cachedWrapR = r.wrapR),
                this._setAnisotropicLevel(0, u, r.anisotropicFilteringLevel)
            }
            this._setInternalTexture(a, u, s, l)
        } else
            this.dbgVerboseLogsForFirstFrames && (this._count === void 0 && (this._count = 0),
            (!this._count || this._count < this.dbgVerboseLogsNumFrames) && console.log("frame #" + this._count + " - _setTexture called with a null _currentEffect! texture=", r));
        return !0
    }
    ,
    e.prototype._setAnisotropicLevel = function(t, r, n) {
        r._cachedAnisotropicFilteringLevel !== n && (r._cachedAnisotropicFilteringLevel = Math.min(n, this._caps.maxAnisotropy))
    }
    ,
    e.prototype._bindTexture = function(t, r, n) {
        t !== void 0 && this._setInternalTexture(n, r)
    }
    ,
    e.prototype.generateMipmaps = function(t) {
        this._generateMipmaps(t, this._renderTargetEncoder)
    }
    ,
    e.prototype._generateMipmaps = function(t, r) {
        var n = t._hardwareTexture;
        if (!!n) {
            r = r != null ? r : this._currentRenderTarget && !this._currentRenderPass ? this._renderTargetEncoder : this._currentRenderPass ? this._uploadEncoder : this._renderEncoder;
            var o = t._hardwareTexture.format
              , a = WebGPUTextureHelper.ComputeNumMipmapLevels(t.width, t.height);
            this.dbgVerboseLogsForFirstFrames && (this._count === void 0 && (this._count = 0),
            (!this._count || this._count < this.dbgVerboseLogsNumFrames) && console.log("frame #" + this._count + " - generate mipmaps called - width=", t.width, "height=", t.height, "isCube=", t.isCube)),
            t.isCube ? this._textureHelper.generateCubeMipmaps(n, o, a, r) : this._textureHelper.generateMipmaps(n, o, a, 0, r)
        }
    }
    ,
    e.prototype.updateTextureData = function(t, r, n, o, a, s, l, u) {
        var c;
        l === void 0 && (l = 0),
        u === void 0 && (u = 0);
        var h = t._hardwareTexture;
        !((c = t._hardwareTexture) === null || c === void 0) && c.underlyingResource || (h = this._textureHelper.createGPUTextureForInternalTexture(t));
        var f = new Uint8Array(r.buffer,r.byteOffset,r.byteLength);
        this._textureHelper.updateTexture(f, t, a, s, t.depth, h.format, l, u, t.invertY, !1, n, o, this._uploadEncoder)
    }
    ,
    e.prototype._uploadCompressedDataToTextureDirectly = function(t, r, n, o, a, s, l) {
        var u;
        s === void 0 && (s = 0),
        l === void 0 && (l = 0);
        var c = t._hardwareTexture;
        !((u = t._hardwareTexture) === null || u === void 0) && u.underlyingResource || (t.format = r,
        c = this._textureHelper.createGPUTextureForInternalTexture(t, n, o));
        var h = new Uint8Array(a.buffer,a.byteOffset,a.byteLength);
        this._textureHelper.updateTexture(h, t, n, o, t.depth, c.format, s, l, !1, !1, 0, 0, this._uploadEncoder)
    }
    ,
    e.prototype._uploadDataToTextureDirectly = function(t, r, n, o, a, s) {
        var l;
        n === void 0 && (n = 0),
        o === void 0 && (o = 0),
        s === void 0 && (s = !1);
        var u = Math.round(Math.log(t.width) * Math.LOG2E)
          , c = Math.round(Math.log(t.height) * Math.LOG2E)
          , h = s ? t.width : Math.pow(2, Math.max(u - o, 0))
          , f = s ? t.height : Math.pow(2, Math.max(c - o, 0))
          , d = t._hardwareTexture;
        !((l = t._hardwareTexture) === null || l === void 0) && l.underlyingResource || (d = this._textureHelper.createGPUTextureForInternalTexture(t, h, f));
        var _ = new Uint8Array(r.buffer,r.byteOffset,r.byteLength);
        this._textureHelper.updateTexture(_, t, h, f, t.depth, d.format, n, o, t.invertY, !1, 0, 0, this._uploadEncoder)
    }
    ,
    e.prototype._uploadArrayBufferViewToTexture = function(t, r, n, o) {
        n === void 0 && (n = 0),
        o === void 0 && (o = 0),
        this._uploadDataToTextureDirectly(t, r, n, o)
    }
    ,
    e.prototype._uploadImageToTexture = function(t, r, n, o) {
        var a;
        n === void 0 && (n = 0),
        o === void 0 && (o = 0);
        var s = t._hardwareTexture;
        !((a = t._hardwareTexture) === null || a === void 0) && a.underlyingResource || (s = this._textureHelper.createGPUTextureForInternalTexture(t));
        var l = r
          , u = Math.ceil(t.width / (1 << o))
          , c = Math.ceil(t.height / (1 << o));
        this._textureHelper.updateTexture(l, t, u, c, t.depth, s.format, n, o, t.invertY, !1, 0, 0, this._uploadEncoder)
    }
    ,
    e.prototype.readPixels = function(t, r, n, o, a, s) {
        s === void 0 && (s = !0);
        var l = this._rttRenderPassWrapper.renderPass ? this._rttRenderPassWrapper : this._mainRenderPassWrapper
          , u = l.colorAttachmentGPUTextures[0].underlyingResource
          , c = l.colorAttachmentGPUTextures[0].format;
        return u ? (s && this.flushFramebuffer(),
        this._textureHelper.readPixels(u, t, r, n, o, c)) : Promise.resolve(new Uint8Array(0))
    }
    ,
    e.prototype.beginFrame = function() {
        i.prototype.beginFrame.call(this)
    }
    ,
    e.prototype.endFrame = function() {
        if (this._snapshotRendering.endFrame(this._mainRenderPassWrapper.renderPass),
        this._endMainRenderPass(),
        this._timestampQuery.endFrame(this._renderEncoder),
        this._invertYFinalFramebuffer && this._mainRenderPassCopyWrapper.renderPassDescriptor.colorAttachments[0].view && this._textureHelper.copyWithInvertY(this._mainTextureLastCopy.createView(), this._mainRenderPassWrapper.colorAttachmentGPUTextures[0].format, this._mainRenderPassCopyWrapper.renderPassDescriptor, this._renderEncoder),
        this.flushFramebuffer(!1),
        this.dbgVerboseLogsForFirstFrames && (this._count === void 0 && (this._count = 0),
        (!this._count || this._count < this.dbgVerboseLogsNumFrames) && console.log("frame #" + this._count + " - counters")),
        this._textureHelper.destroyDeferredTextures(),
        this._bufferManager.destroyDeferredBuffers(),
        this._features._collectUbosUpdatedInFrame) {
            if (this.dbgVerboseLogsForFirstFrames && (this._count === void 0 && (this._count = 0),
            !this._count || this._count < this.dbgVerboseLogsNumFrames)) {
                var t = [];
                for (var r in UniformBuffer._updatedUbosInFrame)
                    t.push(r + ":" + UniformBuffer._updatedUbosInFrame[r]);
                console.log("frame #" + this._count + " - updated ubos -", t.join(", "))
            }
            UniformBuffer._updatedUbosInFrame = {}
        }
        this.countersLastFrame.numEnableEffects = this._counters.numEnableEffects,
        this.countersLastFrame.numEnableDrawWrapper = this._counters.numEnableDrawWrapper,
        this.countersLastFrame.numBundleCreationNonCompatMode = this._counters.numBundleCreationNonCompatMode,
        this.countersLastFrame.numBundleReuseNonCompatMode = this._counters.numBundleReuseNonCompatMode,
        this._counters.numEnableEffects = 0,
        this._counters.numEnableDrawWrapper = 0,
        this._counters.numBundleCreationNonCompatMode = 0,
        this._counters.numBundleReuseNonCompatMode = 0,
        this._cacheRenderPipeline.endFrame(),
        this._cacheBindGroups.endFrame(),
        this._pendingDebugCommands.length = 0,
        i.prototype.endFrame.call(this),
        this.dbgVerboseLogsForFirstFrames && (this._count === void 0 && (this._count = 0),
        this._count < this.dbgVerboseLogsNumFrames && console.log("%c frame #" + this._count + " - end", "background: #ffff00"),
        this._count < this.dbgVerboseLogsNumFrames && (this._count++,
        this._count !== this.dbgVerboseLogsNumFrames && console.log("%c frame #" + this._count + " - begin", "background: #ffff00")))
    }
    ,
    e.prototype.flushFramebuffer = function(t) {
        t === void 0 && (t = !0);
        var r = !this._currentRenderPass
          , n = 0;
        this._currentRenderPass && this._currentRenderTarget && (n |= 1,
        this._endRenderTargetRenderPass()),
        this._mainRenderPassWrapper.renderPass && (n |= 2,
        this._endMainRenderPass()),
        this._commandBuffers[0] = this._uploadEncoder.finish(),
        this._commandBuffers[1] = this._renderTargetEncoder.finish(),
        this._commandBuffers[2] = this._renderEncoder.finish(),
        this._device.queue.submit(this._commandBuffers),
        this._uploadEncoder = this._device.createCommandEncoder(this._uploadEncoderDescriptor),
        this._renderEncoder = this._device.createCommandEncoder(this._renderEncoderDescriptor),
        this._renderTargetEncoder = this._device.createCommandEncoder(this._renderTargetEncoderDescriptor),
        this._timestampQuery.startFrame(this._uploadEncoder),
        this._textureHelper.setCommandEncoder(this._uploadEncoder),
        this._bundleList.reset(),
        this._bundleListRenderTarget.reset(),
        t && (n & 2 && this._startMainRenderPass(!1),
        n & 1 && this._startRenderTargetRenderPass(this._currentRenderTarget, !1, null, !1, !1),
        r && this._currentRenderTarget && (this._currentRenderPass = null))
    }
    ,
    e.prototype._currentFrameBufferIsDefaultFrameBuffer = function() {
        return this._currentRenderTarget === null
    }
    ,
    e.prototype._startRenderTargetRenderPass = function(t, r, n, o, a) {
        var s, l, u, c = t._depthStencilTexture, h = c == null ? void 0 : c._hardwareTexture, f = h == null ? void 0 : h.underlyingResource, d = h == null ? void 0 : h.msaaTexture, _ = f == null ? void 0 : f.createView(this._rttRenderPassWrapper.depthAttachmentViewDescriptor), g = d == null ? void 0 : d.createView(this._rttRenderPassWrapper.depthAttachmentViewDescriptor), m = [];
        this.useReverseDepthBuffer && this.setDepthFunctionToGreaterOrEqual();
        var v = r && n || LoadOp.Load
          , y = r && o ? this.useReverseDepthBuffer ? this._clearReverseDepthValue : this._clearDepthValue : LoadOp.Load
          , b = r && a ? this._clearStencilValue : LoadOp.Load;
        if (t._attachments && t.isMulti) {
            (!this._mrtAttachments || this._mrtAttachments.length === 0) && (this._mrtAttachments = t._attachments);
            for (var T = 0; T < this._mrtAttachments.length; ++T) {
                var C = this._mrtAttachments[T];
                if (C !== 0) {
                    var A = t.textures[C - 1]
                      , S = A == null ? void 0 : A._hardwareTexture
                      , P = S == null ? void 0 : S.underlyingResource;
                    if (S && P) {
                        var R = __assign(__assign({}, this._rttRenderPassWrapper.colorAttachmentViewDescriptor), {
                            format: S.format
                        })
                          , M = S.msaaTexture
                          , x = P.createView(R)
                          , I = M == null ? void 0 : M.createView(R);
                        m.push({
                            view: I || x,
                            resolveTarget: M ? x : void 0,
                            loadValue: v,
                            storeOp: StoreOp.Store
                        })
                    }
                }
            }
            this._cacheRenderPipeline.setMRTAttachments(this._mrtAttachments, t.textures)
        } else {
            var w = t.texture
              , O = w._hardwareTexture
              , D = O.underlyingResource
              , M = O.msaaTexture
              , x = D.createView(this._rttRenderPassWrapper.colorAttachmentViewDescriptor)
              , I = M == null ? void 0 : M.createView(this._rttRenderPassWrapper.colorAttachmentViewDescriptor);
            m.push({
                view: I || x,
                resolveTarget: M ? x : void 0,
                loadValue: v,
                storeOp: StoreOp.Store
            })
        }
        if ((s = this._debugPushGroup) === null || s === void 0 || s.call(this, "render target pass", 1),
        this._rttRenderPassWrapper.renderPassDescriptor = {
            colorAttachments: m,
            depthStencilAttachment: c && f ? {
                view: g || _,
                depthLoadValue: y,
                depthStoreOp: StoreOp.Store,
                stencilLoadValue: t._depthStencilTextureWithStencil ? b : LoadOp.Load,
                stencilStoreOp: StoreOp.Store
            } : void 0,
            occlusionQuerySet: !((l = this._occlusionQuery) === null || l === void 0) && l.hasQueries ? this._occlusionQuery.querySet : void 0
        },
        this._rttRenderPassWrapper.renderPass = this._renderTargetEncoder.beginRenderPass(this._rttRenderPassWrapper.renderPassDescriptor),
        this.dbgVerboseLogsForFirstFrames && (this._count === void 0 && (this._count = 0),
        !this._count || this._count < this.dbgVerboseLogsNumFrames)) {
            var w = t.texture;
            console.log("frame #" + this._count + " - render target begin pass - internalTexture.uniqueId=", w.uniqueId, "width=", w.width, "height=", w.height, this._rttRenderPassWrapper.renderPassDescriptor)
        }
        this._currentRenderPass = this._rttRenderPassWrapper.renderPass,
        (u = this._debugFlushPendingCommands) === null || u === void 0 || u.call(this),
        this._resetCurrentViewport(1),
        this._resetCurrentScissor(1),
        this._resetCurrentStencilRef(1),
        this._resetCurrentColorBlend(1)
    }
    ,
    e.prototype._endRenderTargetRenderPass = function() {
        var t, r, n;
        if (this._currentRenderPass) {
            var o = this._currentRenderTarget.texture._hardwareTexture;
            !this._snapshotRendering.endRenderTargetPass(this._currentRenderPass, o) && !this.compatibilityMode && (this._bundleListRenderTarget.run(this._currentRenderPass),
            this._bundleListRenderTarget.reset()),
            this._currentRenderPass.endPass(),
            this.dbgVerboseLogsForFirstFrames && (this._count === void 0 && (this._count = 0),
            (!this._count || this._count < this.dbgVerboseLogsNumFrames) && console.log("frame #" + this._count + " - render target end pass - internalTexture.uniqueId=", (r = (t = this._currentRenderTarget) === null || t === void 0 ? void 0 : t.texture) === null || r === void 0 ? void 0 : r.uniqueId)),
            (n = this._debugPopGroup) === null || n === void 0 || n.call(this, 1),
            this._resetCurrentViewport(1),
            this._resetCurrentScissor(1),
            this._resetCurrentStencilRef(1),
            this._resetCurrentColorBlend(1),
            this._currentRenderPass = null,
            this._rttRenderPassWrapper.reset()
        }
    }
    ,
    e.prototype._getCurrentRenderPass = function() {
        return this._currentRenderTarget && !this._currentRenderPass ? this._startRenderTargetRenderPass(this._currentRenderTarget, !1, null, !1, !1) : this._currentRenderPass || this._startMainRenderPass(!1),
        this._currentRenderPass
    }
    ,
    e.prototype._getCurrentRenderPassIndex = function() {
        return this._currentRenderPass === null ? -1 : this._currentRenderPass === this._mainRenderPassWrapper.renderPass ? 0 : 1
    }
    ,
    e.prototype._startMainRenderPass = function(t, r, n, o) {
        var a, s, l;
        this._mainRenderPassWrapper.renderPass && this._endMainRenderPass(),
        this.useReverseDepthBuffer && this.setDepthFunctionToGreaterOrEqual();
        var u = t && r || LoadOp.Load
          , c = t && n ? this.useReverseDepthBuffer ? this._clearReverseDepthValue : this._clearDepthValue : LoadOp.Load
          , h = t && o ? this._clearStencilValue : LoadOp.Load;
        this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].loadValue = u,
        this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.depthLoadValue = c,
        this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.stencilLoadValue = h,
        this._mainRenderPassWrapper.renderPassDescriptor.occlusionQuerySet = !((a = this._occlusionQuery) === null || a === void 0) && a.hasQueries ? this._occlusionQuery.querySet : void 0;
        var f = this._invertYFinalFramebuffer ? this._mainRenderPassCopyWrapper : this._mainRenderPassWrapper;
        this._swapChainTexture = this._context.getCurrentTexture(),
        f.colorAttachmentGPUTextures[0].set(this._swapChainTexture),
        this._options.antialiasing ? this._invertYFinalFramebuffer ? f.renderPassDescriptor.colorAttachments[0].view = this._swapChainTexture.createView() : f.renderPassDescriptor.colorAttachments[0].resolveTarget = this._swapChainTexture.createView() : f.renderPassDescriptor.colorAttachments[0].view = this._swapChainTexture.createView(),
        this.dbgVerboseLogsForFirstFrames && (this._count === void 0 && (this._count = 0),
        (!this._count || this._count < this.dbgVerboseLogsNumFrames) && console.log("frame #" + this._count + " - main begin pass - texture width=" + this._mainTextureExtends.width, " height=" + this._mainTextureExtends.height, this._mainRenderPassWrapper.renderPassDescriptor)),
        (s = this._debugPushGroup) === null || s === void 0 || s.call(this, "main pass", 0),
        this._currentRenderPass = this._renderEncoder.beginRenderPass(this._mainRenderPassWrapper.renderPassDescriptor),
        this._mainRenderPassWrapper.renderPass = this._currentRenderPass,
        (l = this._debugFlushPendingCommands) === null || l === void 0 || l.call(this),
        this._resetCurrentViewport(0),
        this._resetCurrentScissor(0),
        this._resetCurrentStencilRef(0),
        this._resetCurrentColorBlend(0)
    }
    ,
    e.prototype._endMainRenderPass = function() {
        var t;
        this._mainRenderPassWrapper.renderPass !== null && (this._snapshotRendering.endMainRenderPass(),
        !this.compatibilityMode && !this._snapshotRendering.play && (this._bundleList.run(this._mainRenderPassWrapper.renderPass),
        this._bundleList.reset()),
        this._mainRenderPassWrapper.renderPass.endPass(),
        this.dbgVerboseLogsForFirstFrames && (this._count === void 0 && (this._count = 0),
        (!this._count || this._count < this.dbgVerboseLogsNumFrames) && console.log("frame #" + this._count + " - main end pass")),
        (t = this._debugPopGroup) === null || t === void 0 || t.call(this, 0),
        this._resetCurrentViewport(0),
        this._resetCurrentScissor(0),
        this._resetCurrentStencilRef(0),
        this._resetCurrentColorBlend(0),
        this._mainRenderPassWrapper.renderPass === this._currentRenderPass && (this._currentRenderPass = null),
        this._mainRenderPassWrapper.reset(!1))
    }
    ,
    e.prototype.bindFramebuffer = function(t, r, n, o, a, s, l) {
        var u, c;
        r === void 0 && (r = 0),
        s === void 0 && (s = 0),
        l === void 0 && (l = 0);
        var h = (u = t.texture) === null || u === void 0 ? void 0 : u._hardwareTexture;
        if (!h) {
            this.dbgSanityChecks && console.error("bindFramebuffer: Trying to bind a texture that does not have a hardware texture!", t, h);
            return
        }
        this._currentRenderTarget && this.unBindFramebuffer(this._currentRenderTarget),
        this._currentRenderTarget = t,
        h._currentLayer = t.isCube ? l * 6 + r : l,
        this._rttRenderPassWrapper.colorAttachmentGPUTextures[0] = h,
        this._rttRenderPassWrapper.depthTextureFormat = this._currentRenderTarget._depthStencilTexture ? WebGPUTextureHelper.GetWebGPUTextureFormat(-1, this._currentRenderTarget._depthStencilTexture.format) : void 0,
        this._setDepthTextureFormat(this._rttRenderPassWrapper),
        this._setColorFormat(this._rttRenderPassWrapper),
        this._rttRenderPassWrapper.colorAttachmentViewDescriptor = {
            format: this._colorFormat,
            dimension: TextureViewDimension.E2d,
            mipLevelCount: 1,
            baseArrayLayer: t.isCube ? l * 6 + r : l,
            baseMipLevel: s,
            arrayLayerCount: 1,
            aspect: TextureAspect.All
        },
        this._rttRenderPassWrapper.depthAttachmentViewDescriptor = {
            format: this._depthTextureFormat,
            dimension: TextureViewDimension.E2d,
            mipLevelCount: 1,
            baseArrayLayer: t.isCube ? l * 6 + r : l,
            baseMipLevel: 0,
            arrayLayerCount: 1,
            aspect: TextureAspect.All
        },
        this.dbgVerboseLogsForFirstFrames && (this._count === void 0 && (this._count = 0),
        (!this._count || this._count < this.dbgVerboseLogsNumFrames) && console.log("frame #" + this._count + " - bindFramebuffer called - internalTexture.uniqueId=", (c = t.texture) === null || c === void 0 ? void 0 : c.uniqueId, "face=", r, "lodLevel=", s, "layer=", l, this._rttRenderPassWrapper.colorAttachmentViewDescriptor, this._rttRenderPassWrapper.depthAttachmentViewDescriptor)),
        this._currentRenderPass = null,
        this.snapshotRendering && this.snapshotRenderingMode === 1 && this._getCurrentRenderPass(),
        this._cachedViewport && !a ? this.setViewport(this._cachedViewport, n, o) : (n || (n = t.width,
        s && (n = n / Math.pow(2, s))),
        o || (o = t.height,
        s && (o = o / Math.pow(2, s))),
        this._viewport(0, 0, n, o)),
        this.wipeCaches()
    }
    ,
    e.prototype.unBindFramebuffer = function(t, r, n) {
        var o, a;
        r === void 0 && (r = !1);
        var s = this._currentRenderTarget;
        this._currentRenderTarget = null,
        n && n(),
        this._currentRenderTarget = s,
        this._currentRenderPass && this._currentRenderPass !== this._mainRenderPassWrapper.renderPass && this._endRenderTargetRenderPass(),
        ((o = t.texture) === null || o === void 0 ? void 0 : o.generateMipMaps) && !r && !t.isCube && this._generateMipmaps(t.texture),
        this._currentRenderTarget = null,
        this._onAfterUnbindFrameBufferObservable.notifyObservers(this),
        this.dbgVerboseLogsForFirstFrames && (this._count === void 0 && (this._count = 0),
        (!this._count || this._count < this.dbgVerboseLogsNumFrames) && console.log("frame #" + this._count + " - unBindFramebuffer called - internalTexture.uniqueId=", (a = t.texture) === null || a === void 0 ? void 0 : a.uniqueId)),
        this._mrtAttachments = [],
        this._cacheRenderPipeline.setMRTAttachments(this._mrtAttachments, []),
        this._currentRenderPass = this._mainRenderPassWrapper.renderPass,
        this._setDepthTextureFormat(this._mainRenderPassWrapper),
        this._setColorFormat(this._mainRenderPassWrapper)
    }
    ,
    e.prototype.restoreDefaultFramebuffer = function() {
        this._currentRenderTarget ? this.unBindFramebuffer(this._currentRenderTarget) : (this._currentRenderPass = this._mainRenderPassWrapper.renderPass,
        this._setDepthTextureFormat(this._mainRenderPassWrapper),
        this._setColorFormat(this._mainRenderPassWrapper)),
        this._currentRenderPass && this._cachedViewport && this.setViewport(this._cachedViewport),
        this.wipeCaches()
    }
    ,
    e.prototype._setColorFormat = function(t) {
        var r = t.colorAttachmentGPUTextures[0].format;
        this._cacheRenderPipeline.setColorFormat(r),
        this._colorFormat !== r && (this._colorFormat = r)
    }
    ,
    e.prototype._setDepthTextureFormat = function(t) {
        this._cacheRenderPipeline.setDepthStencilFormat(t.depthTextureFormat),
        this._depthTextureFormat !== t.depthTextureFormat && (this._depthTextureFormat = t.depthTextureFormat)
    }
    ,
    e.prototype.setDitheringState = function(t) {}
    ,
    e.prototype.setRasterizerState = function(t) {}
    ,
    e.prototype.setState = function(t, r, n, o, a, s, l) {
        var u, c;
        r === void 0 && (r = 0),
        o === void 0 && (o = !1),
        l === void 0 && (l = 0),
        (this._depthCullingState.cull !== t || n) && (this._depthCullingState.cull = t);
        var h = !((c = (u = this.cullBackFaces) !== null && u !== void 0 ? u : a) !== null && c !== void 0) || c ? 1 : 2;
        (this._depthCullingState.cullFace !== h || n) && (this._depthCullingState.cullFace = h),
        this.setZOffset(r),
        this.setZOffsetUnits(l);
        var f = o ? 1 : 2;
        (this._depthCullingState.frontFace !== f || n) && (this._depthCullingState.frontFace = f),
        this._stencilStateComposer.stencilMaterial = s
    }
    ,
    e.prototype._applyRenderPassChanges = function(t, r) {
        var n, o = this._mustUpdateViewport(t), a = this._mustUpdateScissor(t), s = this._stencilStateComposer.enabled ? this._mustUpdateStencilRef(t) : !1, l = this._alphaState.alphaBlend ? this._mustUpdateBlendColor(t) : !1;
        r ? (o && r.addItem(new WebGPURenderItemViewport(this._viewportCached.x,this._viewportCached.y,this._viewportCached.z,this._viewportCached.w)),
        a && r.addItem(new WebGPURenderItemScissor(this._scissorCached.x,this._scissorCached.y,this._scissorCached.z,this._scissorCached.w)),
        s && r.addItem(new WebGPURenderItemStencilRef((n = this._stencilStateComposer.funcRef) !== null && n !== void 0 ? n : 0)),
        l && r.addItem(new WebGPURenderItemBlendColor(this._alphaState._blendConstants.slice()))) : (o && this._applyViewport(t),
        a && this._applyScissor(t),
        s && this._applyStencilRef(t),
        l && this._applyBlendColor(t))
    }
    ,
    e.prototype._draw = function(t, r, n, o, a) {
        var s, l = this._getCurrentRenderPass(), u = this._getCurrentRenderPassIndex(), c = u === 0 ? this._bundleList : this._bundleListRenderTarget;
        this.applyStates();
        var h = this._currentEffect._pipelineContext;
        if (h.uniformBuffer && (h.uniformBuffer.update(),
        this.bindUniformBufferBase(h.uniformBuffer.getBuffer(), 0, WebGPUShaderProcessor.LeftOvertUBOName)),
        this._snapshotRendering.play) {
            this._reportDrawCall();
            return
        }
        !this.compatibilityMode && (this._currentDrawContext.isDirty(this._currentMaterialContext.updateId) || this._currentMaterialContext.isDirty || this._currentMaterialContext.forceBindGroupCreation) && (this._currentDrawContext.fastBundle = void 0);
        var f = !this.compatibilityMode && this._currentDrawContext.fastBundle
          , d = l;
        if (f || this._snapshotRendering.record) {
            if (this._applyRenderPassChanges(l, c),
            !this._snapshotRendering.record) {
                this._counters.numBundleReuseNonCompatMode++,
                this._currentDrawContext.indirectDrawBuffer && this._currentDrawContext.setIndirectData(o, a || 1, n),
                c.addBundle(this._currentDrawContext.fastBundle),
                this._reportDrawCall();
                return
            }
            d = c.getBundleEncoder(this._cacheRenderPipeline.colorFormats, this._depthTextureFormat, this.currentSampleCount),
            c.numDrawCalls++
        }
        var _ = 0;
        if (!this._caps.textureFloatLinearFiltering && this._currentMaterialContext.hasFloatTextures)
            for (var g = 1, m = 0; m < h.shaderProcessingContext.textureNames.length; ++m) {
                var v = h.shaderProcessingContext.textureNames[m]
                  , y = (s = this._currentMaterialContext.textures[v]) === null || s === void 0 ? void 0 : s.texture;
                (y == null ? void 0 : y.type) === 1 && (_ |= g),
                g = g << 1
            }
        var b = this._cacheRenderPipeline.getRenderPipeline(r, this._currentEffect, this.currentSampleCount, _)
          , T = this._cacheBindGroups.getBindGroups(h, this._currentDrawContext, this._currentMaterialContext);
        this._snapshotRendering.record || (this._applyRenderPassChanges(l, this.compatibilityMode ? null : c),
        this.compatibilityMode || (this._counters.numBundleCreationNonCompatMode++,
        d = this._device.createRenderBundleEncoder({
            colorFormats: this._cacheRenderPipeline.colorFormats,
            depthStencilFormat: this._depthTextureFormat,
            sampleCount: this.currentSampleCount
        }))),
        d.setPipeline(b),
        this._currentIndexBuffer && d.setIndexBuffer(this._currentIndexBuffer.underlyingResource, this._currentIndexBuffer.is32Bits ? IndexFormat.Uint32 : IndexFormat.Uint16, 0);
        for (var C = this._cacheRenderPipeline.vertexBuffers, A = 0; A < C.length; A++) {
            var S = C[A]
              , P = S.getBuffer();
            P && d.setVertexBuffer(A, P.underlyingResource, S._validOffsetRange ? 0 : S.byteOffset)
        }
        for (var m = 0; m < T.length; m++)
            d.setBindGroup(m, T[m]);
        var R = !this.compatibilityMode && !this._snapshotRendering.record;
        R && this._currentDrawContext.indirectDrawBuffer ? (this._currentDrawContext.setIndirectData(o, a || 1, n),
        t === 0 ? d.drawIndexedIndirect(this._currentDrawContext.indirectDrawBuffer, 0) : d.drawIndirect(this._currentDrawContext.indirectDrawBuffer, 0)) : t === 0 ? d.drawIndexed(o, a || 1, n, 0, 0) : d.draw(o, a || 1, n, 0),
        R && (this._currentDrawContext.fastBundle = d.finish(),
        c.addBundle(this._currentDrawContext.fastBundle)),
        this._reportDrawCall()
    }
    ,
    e.prototype.drawElementsType = function(t, r, n, o) {
        o === void 0 && (o = 1),
        this._draw(0, t, r, n, o)
    }
    ,
    e.prototype.drawArraysType = function(t, r, n, o) {
        o === void 0 && (o = 1),
        this._currentIndexBuffer = null,
        this._draw(1, t, r, n, o)
    }
    ,
    e.prototype.dispose = function() {
        var t, r, n;
        (t = this._mainTexture) === null || t === void 0 || t.destroy(),
        (r = this._mainTextureLastCopy) === null || r === void 0 || r.destroy(),
        (n = this._depthTexture) === null || n === void 0 || n.destroy(),
        i.prototype.dispose.call(this)
    }
    ,
    e.prototype.getRenderWidth = function(t) {
        return t === void 0 && (t = !1),
        !t && this._currentRenderTarget ? this._currentRenderTarget.width : this._canvas.width
    }
    ,
    e.prototype.getRenderHeight = function(t) {
        return t === void 0 && (t = !1),
        !t && this._currentRenderTarget ? this._currentRenderTarget.height : this._canvas.height
    }
    ,
    e.prototype.getRenderingCanvas = function() {
        return this._canvas
    }
    ,
    e.prototype.getError = function() {
        return 0
    }
    ,
    e.prototype.bindSamplers = function(t) {}
    ,
    e.prototype._bindTextureDirectly = function(t, r, n, o) {
        return !1
    }
    ,
    e.prototype.areAllEffectsReady = function() {
        return !0
    }
    ,
    e.prototype._executeWhenRenderingStateIsCompiled = function(t, r) {
        r()
    }
    ,
    e.prototype._isRenderingStateCompiled = function(t) {
        return !0
    }
    ,
    e.prototype._getUnpackAlignement = function() {
        return 1
    }
    ,
    e.prototype._unpackFlipY = function(t) {}
    ,
    e.prototype._bindUnboundFramebuffer = function(t) {
        throw "_bindUnboundFramebuffer is not implementedin WebGPU! You probably want to use restoreDefaultFramebuffer or unBindFramebuffer instead"
    }
    ,
    e.prototype._getSamplingParameters = function(t, r) {
        throw "_getSamplingParameters is not available in WebGPU"
    }
    ,
    e.prototype.getUniforms = function(t, r) {
        return []
    }
    ,
    e.prototype.setIntArray = function(t, r) {
        return !1
    }
    ,
    e.prototype.setIntArray2 = function(t, r) {
        return !1
    }
    ,
    e.prototype.setIntArray3 = function(t, r) {
        return !1
    }
    ,
    e.prototype.setIntArray4 = function(t, r) {
        return !1
    }
    ,
    e.prototype.setArray = function(t, r) {
        return !1
    }
    ,
    e.prototype.setArray2 = function(t, r) {
        return !1
    }
    ,
    e.prototype.setArray3 = function(t, r) {
        return !1
    }
    ,
    e.prototype.setArray4 = function(t, r) {
        return !1
    }
    ,
    e.prototype.setMatrices = function(t, r) {
        return !1
    }
    ,
    e.prototype.setMatrix3x3 = function(t, r) {
        return !1
    }
    ,
    e.prototype.setMatrix2x2 = function(t, r) {
        return !1
    }
    ,
    e.prototype.setFloat = function(t, r) {
        return !1
    }
    ,
    e.prototype.setFloat2 = function(t, r, n) {
        return !1
    }
    ,
    e.prototype.setFloat3 = function(t, r, n, o) {
        return !1
    }
    ,
    e.prototype.setFloat4 = function(t, r, n, o, a) {
        return !1
    }
    ,
    e._glslangDefaultOptions = {
        jsPath: "https://preview.babylonjs.com/glslang/glslang.js",
        wasmPath: "https://preview.babylonjs.com/glslang/glslang.wasm"
    },
    e.UseTWGSL = !0,
    e
}(Engine);
WebGPUEngine.prototype.setAlphaMode = function(i, e) {
    if (e === void 0 && (e = !1),
    !(this._alphaMode === i && (i === 0 && !this._alphaState.alphaBlend || i !== 0 && this._alphaState.alphaBlend))) {
        switch (i) {
        case 0:
            this._alphaState.alphaBlend = !1;
            break;
        case 7:
            this._alphaState.setAlphaBlendFunctionParameters(1, 771, 1, 1),
            this._alphaState.alphaBlend = !0;
            break;
        case 8:
            this._alphaState.setAlphaBlendFunctionParameters(1, 771, 1, 771),
            this._alphaState.alphaBlend = !0;
            break;
        case 2:
            this._alphaState.setAlphaBlendFunctionParameters(770, 771, 1, 1),
            this._alphaState.alphaBlend = !0;
            break;
        case 6:
            this._alphaState.setAlphaBlendFunctionParameters(1, 1, 0, 1),
            this._alphaState.alphaBlend = !0;
            break;
        case 1:
            this._alphaState.setAlphaBlendFunctionParameters(770, 1, 0, 1),
            this._alphaState.alphaBlend = !0;
            break;
        case 3:
            this._alphaState.setAlphaBlendFunctionParameters(0, 769, 1, 1),
            this._alphaState.alphaBlend = !0;
            break;
        case 4:
            this._alphaState.setAlphaBlendFunctionParameters(774, 0, 1, 1),
            this._alphaState.alphaBlend = !0;
            break;
        case 5:
            this._alphaState.setAlphaBlendFunctionParameters(770, 769, 1, 1),
            this._alphaState.alphaBlend = !0;
            break;
        case 9:
            this._alphaState.setAlphaBlendFunctionParameters(32769, 32770, 32771, 32772),
            this._alphaState.alphaBlend = !0;
            break;
        case 10:
            this._alphaState.setAlphaBlendFunctionParameters(1, 769, 1, 771),
            this._alphaState.alphaBlend = !0;
            break;
        case 11:
            this._alphaState.setAlphaBlendFunctionParameters(1, 1, 1, 1),
            this._alphaState.alphaBlend = !0;
            break;
        case 12:
            this._alphaState.setAlphaBlendFunctionParameters(772, 1, 0, 0),
            this._alphaState.alphaBlend = !0;
            break;
        case 13:
            this._alphaState.setAlphaBlendFunctionParameters(775, 769, 773, 771),
            this._alphaState.alphaBlend = !0;
            break;
        case 14:
            this._alphaState.setAlphaBlendFunctionParameters(1, 771, 1, 771),
            this._alphaState.alphaBlend = !0;
            break;
        case 15:
            this._alphaState.setAlphaBlendFunctionParameters(1, 1, 1, 0),
            this._alphaState.alphaBlend = !0;
            break;
        case 16:
            this._alphaState.setAlphaBlendFunctionParameters(775, 769, 0, 1),
            this._alphaState.alphaBlend = !0;
            break;
        case 17:
            this._alphaState.setAlphaBlendFunctionParameters(770, 771, 1, 771),
            this._alphaState.alphaBlend = !0;
            break
        }
        e || (this.setDepthWrite(i === Engine.ALPHA_DISABLE),
        this._cacheRenderPipeline.setDepthWriteEnabled(i === Engine.ALPHA_DISABLE)),
        this._alphaMode = i,
        this._cacheRenderPipeline.setAlphaBlendEnabled(this._alphaState.alphaBlend),
        this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters, this._alphaState._blendEquationParameters)
    }
}
;
WebGPUEngine.prototype.setAlphaEquation = function(i) {
    Engine.prototype.setAlphaEquation.call(this, i),
    this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters, this._alphaState._blendEquationParameters)
}
;
var ComputeEffect = function() {
    function i(e, t, r, n) {
        var o = this;
        n === void 0 && (n = "");
        var a, s;
        this.name = null,
        this.defines = "",
        this.onCompiled = null,
        this.onError = null,
        this.uniqueId = 0,
        this.onCompileObservable = new Observable,
        this.onErrorObservable = new Observable,
        this.onBindObservable = new Observable,
        this._wasPreviouslyReady = !1,
        this._isReady = !1,
        this._compilationError = "",
        this._key = "",
        this._computeSourceCodeOverride = "",
        this._pipelineContext = null,
        this._computeSourceCode = "",
        this._rawComputeSourceCode = "",
        this._shaderLanguage = ShaderLanguage.WGSL,
        this.name = e,
        this._key = n,
        this._engine = r,
        this.uniqueId = i._uniqueIdSeed++,
        this.defines = (a = t.defines) !== null && a !== void 0 ? a : "",
        this.onError = t.onError,
        this.onCompiled = t.onCompiled,
        this._entryPoint = (s = t.entryPoint) !== null && s !== void 0 ? s : "main",
        this._shaderStore = ShaderStore.GetShadersStore(this._shaderLanguage),
        this._shaderRepository = ShaderStore.GetShadersRepository(this._shaderLanguage),
        this._includeShaderStore = ShaderStore.GetIncludesShadersStore(this._shaderLanguage);
        var l, u = IsWindowObjectExist() ? this._engine.getHostDocument() : null;
        e.computeSource ? l = "source:" + e.computeSource : e.computeElement ? (l = u ? u.getElementById(e.computeElement) : null,
        l || (l = e.computeElement)) : l = e.compute || e;
        var c = {
            defines: this.defines.split(`
`),
            indexParameters: void 0,
            isFragment: !1,
            shouldUseHighPrecisionShader: !1,
            processor: null,
            supportsUniformBuffers: this._engine.supportsUniformBuffers,
            shadersRepository: this._shaderRepository,
            includesShadersStore: this._includeShaderStore,
            version: (this._engine.version * 100).toString(),
            platformName: this._engine.shaderPlatformName,
            processingContext: null,
            isNDCHalfZRange: this._engine.isNDCHalfZRange,
            useReverseDepthBuffer: this._engine.useReverseDepthBuffer
        };
        this._loadShader(l, "Compute", "", function(h) {
            ShaderProcessor.Initialize(c),
            ShaderProcessor.PreProcess(h, c, function(f) {
                o._rawComputeSourceCode = h,
                t.processFinalCode && (f = t.processFinalCode(f));
                var d = ShaderProcessor.Finalize(f, "", c);
                o._useFinalCode(d.vertexCode, e)
            }, o._engine)
        })
    }
    return i.prototype._useFinalCode = function(e, t) {
        if (t) {
            var r = t.computeElement || t.compute || t.spectorName || t;
            this._computeSourceCode = "//#define SHADER_NAME compute:" + r + `
` + e
        } else
            this._computeSourceCode = e;
        this._prepareEffect()
    }
    ,
    Object.defineProperty(i.prototype, "key", {
        get: function() {
            return this._key
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype.isReady = function() {
        try {
            return this._isReadyInternal()
        } catch {
            return !1
        }
    }
    ,
    i.prototype._isReadyInternal = function() {
        return this._isReady ? !0 : this._pipelineContext ? this._pipelineContext.isReady : !1
    }
    ,
    i.prototype.getEngine = function() {
        return this._engine
    }
    ,
    i.prototype.getPipelineContext = function() {
        return this._pipelineContext
    }
    ,
    i.prototype.getCompilationError = function() {
        return this._compilationError
    }
    ,
    i.prototype.executeWhenCompiled = function(e) {
        var t = this;
        if (this.isReady()) {
            e(this);
            return
        }
        this.onCompileObservable.add(function(r) {
            e(r)
        }),
        (!this._pipelineContext || this._pipelineContext.isAsync) && setTimeout(function() {
            t._checkIsReady(null)
        }, 16)
    }
    ,
    i.prototype._checkIsReady = function(e) {
        var t = this;
        try {
            if (this._isReadyInternal())
                return
        } catch (r) {
            this._processCompilationErrors(r, e);
            return
        }
        setTimeout(function() {
            t._checkIsReady(e)
        }, 16)
    }
    ,
    i.prototype._loadShader = function(e, t, r, n) {
        if (typeof HTMLElement != "undefined" && e instanceof HTMLElement) {
            var o = GetDOMTextContent(e);
            n(o);
            return
        }
        if (e.substr(0, 7) === "source:") {
            n(e.substr(7));
            return
        }
        if (e.substr(0, 7) === "base64:") {
            var a = window.atob(e.substr(7));
            n(a);
            return
        }
        if (this._shaderStore[e + t + "Shader"]) {
            n(this._shaderStore[e + t + "Shader"]);
            return
        }
        if (r && this._shaderStore[e + r + "Shader"]) {
            n(this._shaderStore[e + r + "Shader"]);
            return
        }
        var s;
        e[0] === "." || e[0] === "/" || e.indexOf("http") > -1 ? s = e : s = this._shaderRepository + e,
        this._engine._loadFile(s + "." + t.toLowerCase() + ".fx", n)
    }
    ,
    Object.defineProperty(i.prototype, "computeSourceCode", {
        get: function() {
            var e, t;
            return this._computeSourceCodeOverride ? this._computeSourceCodeOverride : (t = (e = this._pipelineContext) === null || e === void 0 ? void 0 : e._getComputeShaderCode()) !== null && t !== void 0 ? t : this._computeSourceCode
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "rawComputeSourceCode", {
        get: function() {
            return this._rawComputeSourceCode
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype._prepareEffect = function() {
        var e = this
          , t = this.defines
          , r = this._pipelineContext;
        this._isReady = !1;
        try {
            var n = this._engine;
            this._pipelineContext = n.createComputePipelineContext(),
            this._pipelineContext._name = this._key,
            n._prepareComputePipelineContext(this._pipelineContext, this._computeSourceCodeOverride ? this._computeSourceCodeOverride : this._computeSourceCode, this._rawComputeSourceCode, this._computeSourceCodeOverride ? null : t, this._entryPoint),
            n._executeWhenComputeStateIsCompiled(this._pipelineContext, function() {
                e._compilationError = "",
                e._isReady = !0,
                e.onCompiled && e.onCompiled(e),
                e.onCompileObservable.notifyObservers(e),
                e.onCompileObservable.clear(),
                r && e.getEngine()._deleteComputePipelineContext(r)
            }),
            this._pipelineContext.isAsync && this._checkIsReady(r)
        } catch (o) {
            this._processCompilationErrors(o, r)
        }
    }
    ,
    i.prototype._getShaderCodeAndErrorLine = function(e, t) {
        var r = /COMPUTE SHADER ERROR: 0:(\d+?):/
          , n = null;
        if (t && e) {
            var o = t.match(r);
            if (o && o.length === 2) {
                var a = parseInt(o[1])
                  , s = e.split(`
`, -1);
                s.length >= a && (n = "Offending line [" + a + "] in compute code: " + s[a - 1])
            }
        }
        return [e, n]
    }
    ,
    i.prototype._processCompilationErrors = function(e, t) {
        var r, n;
        if (t === void 0 && (t = null),
        this._compilationError = e.message,
        Logger$2.Error("Unable to compile compute effect:"),
        Logger$2.Error(`Defines:\r
` + this.defines),
        i.LogShaderCodeOnCompilationError) {
            var o = null
              , a = null;
            !((n = this._pipelineContext) === null || n === void 0) && n._getComputeShaderCode() && (r = this._getShaderCodeAndErrorLine(this._pipelineContext._getComputeShaderCode(), this._compilationError),
            a = r[0],
            o = r[1],
            a && (Logger$2.Error("Compute code:"),
            Logger$2.Error(a))),
            o && Logger$2.Error(o)
        }
        Logger$2.Error("Error: " + this._compilationError),
        t && (this._pipelineContext = t,
        this._isReady = !0,
        this.onError && this.onError(this, this._compilationError),
        this.onErrorObservable.notifyObservers(this))
    }
    ,
    i.prototype.dispose = function() {
        this._pipelineContext && this._pipelineContext.dispose(),
        this._engine._releaseComputeEffect(this)
    }
    ,
    i.RegisterShader = function(e, t) {
        ShaderStore.GetShadersStore(ShaderLanguage.WGSL)[e + "ComputeShader"] = t
    }
    ,
    i._uniqueIdSeed = 0,
    i.LogShaderCodeOnCompilationError = !0,
    i
}()
  , WebGPUComputeContext = function() {
    function i(e, t) {
        this._device = e,
        this._cacheSampler = t,
        this.uniqueId = i._Counter++,
        this._bindGroupEntries = [],
        this.clear()
    }
    return i.prototype.getBindGroups = function(e, t, r) {
        if (!r)
            throw new Error("WebGPUComputeContext.getBindGroups: bindingsMapping is required until browsers support reflection for wgsl shaders!");
        if (this._bindGroups.length === 0) {
            var n = this._bindGroupEntries.length > 0;
            for (var o in e) {
                var a = e[o]
                  , s = r[o]
                  , l = s.group
                  , u = s.binding
                  , c = a.type
                  , h = a.object
                  , f = a.indexInGroupEntries
                  , d = this._bindGroupEntries[l];
                switch (d || (d = this._bindGroupEntries[l] = []),
                c) {
                case ComputeBindingType.Sampler:
                    {
                        var _ = h;
                        f !== void 0 && n ? d[f].resource = this._cacheSampler.getSampler(_) : (a.indexInGroupEntries = d.length,
                        d.push({
                            binding: u,
                            resource: this._cacheSampler.getSampler(_)
                        }));
                        break
                    }
                case ComputeBindingType.Texture:
                case ComputeBindingType.TextureWithoutSampler:
                    {
                        var g = h
                          , m = g._texture._hardwareTexture;
                        f !== void 0 && n ? (c === ComputeBindingType.Texture && (d[f++].resource = this._cacheSampler.getSampler(g._texture)),
                        d[f].resource = m.view) : (a.indexInGroupEntries = d.length,
                        c === ComputeBindingType.Texture && d.push({
                            binding: u - 1,
                            resource: this._cacheSampler.getSampler(g._texture)
                        }),
                        d.push({
                            binding: u,
                            resource: m.view
                        }));
                        break
                    }
                case ComputeBindingType.StorageTexture:
                    {
                        var g = h
                          , m = g._texture._hardwareTexture;
                        (m.textureAdditionalUsages & TextureUsage.StorageBinding) === 0 && Logger$2.Error("computeDispatch: The texture (name=" + g.name + ", uniqueId=" + g.uniqueId + ") is not a storage texture!", 50),
                        f !== void 0 && n ? d[f].resource = m.view : (a.indexInGroupEntries = d.length,
                        d.push({
                            binding: u,
                            resource: m.view
                        }));
                        break
                    }
                case ComputeBindingType.UniformBuffer:
                case ComputeBindingType.StorageBuffer:
                    {
                        var v = (c === ComputeBindingType.UniformBuffer,
                        h)
                          , y = v.getBuffer()
                          , b = y.underlyingResource;
                        f !== void 0 && n ? (d[f].resource.buffer = b,
                        d[f].resource.size = y.capacity) : (a.indexInGroupEntries = d.length,
                        d.push({
                            binding: u,
                            resource: {
                                buffer: b,
                                offset: 0,
                                size: y.capacity
                            }
                        }));
                        break
                    }
                }
            }
            for (var T = 0; T < this._bindGroupEntries.length; ++T) {
                var d = this._bindGroupEntries[T];
                if (!d) {
                    this._bindGroups[T] = void 0;
                    continue
                }
                this._bindGroups[T] = this._device.createBindGroup({
                    layout: t.getBindGroupLayout(T),
                    entries: d
                })
            }
            this._bindGroups.length = this._bindGroupEntries.length
        }
        return this._bindGroups
    }
    ,
    i.prototype.clear = function() {
        this._bindGroups = []
    }
    ,
    i._Counter = 0,
    i
}()
  , WebGPUComputePipelineContext = function() {
    function i(e) {
        this._name = "unnamed",
        this.engine = e
    }
    return Object.defineProperty(i.prototype, "isAsync", {
        get: function() {
            return !1
        },
        enumerable: !1,
        configurable: !0
    }),
    Object.defineProperty(i.prototype, "isReady", {
        get: function() {
            return !!this.stage
        },
        enumerable: !1,
        configurable: !0
    }),
    i.prototype._getComputeShaderCode = function() {
        var e;
        return (e = this.sources) === null || e === void 0 ? void 0 : e.compute
    }
    ,
    i.prototype.dispose = function() {}
    ,
    i
}();
WebGPUEngine.prototype.createComputeContext = function() {
    return new WebGPUComputeContext(this._device,this._cacheSampler)
}
;
WebGPUEngine.prototype.createComputeEffect = function(i, e) {
    var t = i.computeElement || i.compute || i.computeToken || i.computeSource || i
      , r = t + "@" + e.defines;
    if (this._compiledComputeEffects[r]) {
        var n = this._compiledComputeEffects[r];
        return e.onCompiled && n.isReady() && e.onCompiled(n),
        n
    }
    var o = new ComputeEffect(i,e,this,r);
    return this._compiledComputeEffects[r] = o,
    o
}
;
WebGPUEngine.prototype.createComputePipelineContext = function() {
    return new WebGPUComputePipelineContext(this)
}
;
WebGPUEngine.prototype.areAllComputeEffectsReady = function() {
    for (var i in this._compiledComputeEffects) {
        var e = this._compiledComputeEffects[i];
        if (!e.isReady())
            return !1
    }
    return !0
}
;
WebGPUEngine.prototype.computeDispatch = function(i, e, t, r, n, o, a) {
    var s = this;
    if (this._currentRenderTarget) {
        this._onAfterUnbindFrameBufferObservable.addOnce(function() {
            s.computeDispatch(i, e, t, r, n, o, a)
        });
        return
    }
    var l = i._pipelineContext
      , u = e;
    l.computePipeline || (l.computePipeline = this._device.createComputePipeline({
        compute: l.stage
    }));
    var c = this._renderTargetEncoder
      , h = c.beginComputePass();
    h.setPipeline(l.computePipeline);
    for (var f = u.getBindGroups(t, l.computePipeline, a), d = 0; d < f.length; ++d) {
        var _ = f[d];
        !_ || h.setBindGroup(d, _)
    }
    h.dispatch(r, n, o),
    h.endPass()
}
;
WebGPUEngine.prototype.releaseComputeEffects = function() {
    for (var i in this._compiledComputeEffects) {
        var e = this._compiledComputeEffects[i].getPipelineContext();
        this._deleteComputePipelineContext(e)
    }
    this._compiledComputeEffects = {}
}
;
WebGPUEngine.prototype._prepareComputePipelineContext = function(i, e, t, r, n) {
    var o = i;
    this.dbgShowShaderCode && (console.log(r),
    console.log(e)),
    o.sources = {
        compute: e,
        rawCompute: t
    },
    o.stage = this._createComputePipelineStageDescriptor(e, r, n)
}
;
WebGPUEngine.prototype._releaseComputeEffect = function(i) {
    this._compiledComputeEffects[i._key] && (delete this._compiledComputeEffects[i._key],
    this._deleteComputePipelineContext(i.getPipelineContext()))
}
;
WebGPUEngine.prototype._rebuildComputeEffects = function() {
    for (var i in this._compiledComputeEffects) {
        var e = this._compiledComputeEffects[i];
        e._pipelineContext = null,
        e._wasPreviouslyReady = !1,
        e._prepareEffect()
    }
}
;
WebGPUEngine.prototype._deleteComputePipelineContext = function(i) {
    var e = i;
    e && i.dispose()
}
;
WebGPUEngine.prototype._createComputePipelineStageDescriptor = function(i, e, t) {
    return e ? e = "//" + e.split(`
`).join(`
//`) + `
` : e = "",
    {
        module: this._device.createShaderModule({
            code: e + i
        }),
        entryPoint: t
    }
}
;
WebGPUEngine.prototype._createDepthStencilCubeTexture = function(i, e) {
    var t = new InternalTexture(this,InternalTextureSource.DepthStencil);
    t.isCube = !0;
    var r = __assign({
        bilinearFiltering: !1,
        comparisonFunction: 0,
        generateStencil: !1,
        samples: 1
    }, e);
    return t.format = r.generateStencil ? 13 : 14,
    this._setupDepthStencilTexture(t, i, r.generateStencil, r.bilinearFiltering, r.comparisonFunction, r.samples),
    this._textureHelper.createGPUTextureForInternalTexture(t),
    this._internalTexturesCache.push(t),
    t
}
;
WebGPUEngine.prototype.createCubeTexture = function(i, e, t, r, n, o, a, s, l, u, c, h, f) {
    var d = this;
    return n === void 0 && (n = null),
    o === void 0 && (o = null),
    s === void 0 && (s = null),
    l === void 0 && (l = !1),
    u === void 0 && (u = 0),
    c === void 0 && (c = 0),
    h === void 0 && (h = null),
    f === void 0 && (f = !1),
    this.createCubeTextureBase(i, e, t, !!r, n, o, a, s, l, u, c, h, null, function(_, g) {
        var m = g
          , v = m[0].width
          , y = v;
        d._setCubeMapTextureParams(_, !r),
        _.format = a != null ? a : -1;
        var b = d._textureHelper.createGPUTextureForInternalTexture(_, v, y);
        d._textureHelper.updateCubeTextures(m, b.underlyingResource, v, y, b.format, !1, !1, 0, 0, d._uploadEncoder),
        r || d._generateMipmaps(_, d._uploadEncoder),
        _.isReady = !0,
        _.onLoadedObservable.notifyObservers(_),
        _.onLoadedObservable.clear(),
        n && n()
    }, !!f)
}
;
WebGPUEngine.prototype._setCubeMapTextureParams = function(i, e) {
    i.samplingMode = e ? 3 : 2,
    i._cachedWrapU = 0,
    i._cachedWrapV = 0
}
;
WebGPUEngine.prototype._debugPushGroup = function(i, e) {
    if (!!this._options.enableGPUDebugMarkers)
        if (e === 0 || e === 1) {
            var t = e === 0 ? this._renderEncoder : this._renderTargetEncoder;
            t.pushDebugGroup(i)
        } else
            this._currentRenderPass ? this._currentRenderPass.pushDebugGroup(i) : this._pendingDebugCommands.push(["push", i])
}
;
WebGPUEngine.prototype._debugPopGroup = function(i) {
    if (!!this._options.enableGPUDebugMarkers)
        if (i === 0 || i === 1) {
            var e = i === 0 ? this._renderEncoder : this._renderTargetEncoder;
            e.popDebugGroup()
        } else
            this._currentRenderPass ? this._currentRenderPass.popDebugGroup() : this._pendingDebugCommands.push(["pop", null])
}
;
WebGPUEngine.prototype._debugInsertMarker = function(i, e) {
    if (!!this._options.enableGPUDebugMarkers)
        if (e === 0 || e === 1) {
            var t = e === 0 ? this._renderEncoder : this._renderTargetEncoder;
            t.insertDebugMarker(i)
        } else
            this._currentRenderPass ? this._currentRenderPass.insertDebugMarker(i) : this._pendingDebugCommands.push(["insert", i])
}
;
WebGPUEngine.prototype._debugFlushPendingCommands = function() {
    for (var i = 0; i < this._pendingDebugCommands.length; ++i) {
        var e = this._pendingDebugCommands[i]
          , t = e[0]
          , r = e[1];
        switch (t) {
        case "push":
            this._debugPushGroup(r);
            break;
        case "pop":
            this._debugPopGroup();
            break;
        case "insert":
            this._debugInsertMarker(r);
            break
        }
    }
    this._pendingDebugCommands.length = 0
}
;
WebGPUEngine.prototype.updateDynamicIndexBuffer = function(i, e, t) {
    t === void 0 && (t = 0);
    var r = i, n;
    e instanceof Uint16Array ? i.is32Bits ? n = Uint32Array.from(e) : n = e : e instanceof Uint32Array ? i.is32Bits ? n = e : n = Uint16Array.from(e) : i.is32Bits ? n = new Uint32Array(e) : n = new Uint16Array(e),
    this._bufferManager.setSubData(r, t, n)
}
;
WebGPUEngine.prototype.updateDynamicVertexBuffer = function(i, e, t, r) {
    var n = i;
    t === void 0 && (t = 0);
    var o;
    r === void 0 ? (e instanceof Array ? o = new Float32Array(e) : e instanceof ArrayBuffer ? o = new Uint8Array(e) : o = e,
    r = o.byteLength) : e instanceof Array ? o = new Float32Array(e) : e instanceof ArrayBuffer ? o = new Uint8Array(e) : o = e,
    this._bufferManager.setSubData(n, t, o, 0, r)
}
;
WebGPUEngine.prototype.updateDynamicTexture = function(i, e, t, r, n, o, a) {
    var s;
    if (r === void 0 && (r = !1),
    !!i) {
        var l = e.width
          , u = e.height
          , c = i._hardwareTexture;
        !((s = i._hardwareTexture) === null || s === void 0) && s.underlyingResource || (c = this._textureHelper.createGPUTextureForInternalTexture(i, l, u)),
        this._textureHelper.updateTexture(e, i, l, u, i.depth, c.format, 0, 0, t, r, 0, 0, this._uploadEncoder, a),
        i.generateMipMaps && this._generateMipmaps(i, this._uploadEncoder),
        i.isReady = !0
    }
}
;
var WebGPUExternalTexture = function(i) {
    __extends(e, i);
    function e(t) {
        return i.call(this, t) || this
    }
    return e
}(ExternalTexture);
Effect.prototype.setExternalTexture = function(i, e) {
    this._engine.setExternalTexture(i, e)
}
;
WebGPUEngine.prototype.createExternalTexture = function(i) {
    var e = new WebGPUExternalTexture(i);
    return e
}
;
WebGPUEngine.prototype.setExternalTexture = function(i, e) {
    if (!e) {
        this._currentMaterialContext.setTexture(i, null);
        return
    }
    this._setInternalTexture(i, e)
}
;
WebGPUEngine.prototype.unBindMultiColorAttachmentFramebuffer = function(i, e, t) {
    e === void 0 && (e = !1),
    t && t();
    var r = i._attachments
      , n = r.length;
    this._currentRenderPass && this._currentRenderPass !== this._mainRenderPassWrapper.renderPass && this._endRenderTargetRenderPass();
    for (var o = 0; o < n; o++) {
        var a = i.textures[o];
        a.generateMipMaps && !e && !a.isCube && this._generateMipmaps(a)
    }
    this._currentRenderTarget = null,
    this._mrtAttachments = [],
    this._cacheRenderPipeline.setMRTAttachments(this._mrtAttachments, []),
    this._currentRenderPass = this._mainRenderPassWrapper.renderPass,
    this._setDepthTextureFormat(this._mainRenderPassWrapper),
    this._setColorFormat(this._mainRenderPassWrapper)
}
;
WebGPUEngine.prototype.createMultipleRenderTarget = function(i, e, t) {
    var r, n = !1, o = !0, a = !1, s = !1, l = 15, u = 1, c = 0, h = 3, f = new Array, d = new Array, _ = this._createHardwareRenderTargetWrapper(!0, !1, i);
    e !== void 0 && (n = e.generateMipMaps === void 0 ? !1 : e.generateMipMaps,
    o = e.generateDepthBuffer === void 0 ? !0 : e.generateDepthBuffer,
    a = e.generateStencilBuffer === void 0 ? !1 : e.generateStencilBuffer,
    s = e.generateDepthTexture === void 0 ? !1 : e.generateDepthTexture,
    u = e.textureCount || 1,
    l = (r = e.depthTextureFormat) !== null && r !== void 0 ? r : 15,
    e.types && (f = e.types),
    e.samplingModes && (d = e.samplingModes));
    var g = i.width || i
      , m = i.height || i
      , v = null;
    (o || a || s) && (v = _.createDepthStencilTexture(0, !1, a, 1, l));
    var y = []
      , b = [];
    _._generateDepthBuffer = o,
    _._generateStencilBuffer = a,
    _._attachments = b;
    for (var T = 0; T < u; T++) {
        var C = d[T] || h
          , A = f[T] || c;
        (A === 1 && !this._caps.textureFloatLinearFiltering || A === 2 && !this._caps.textureHalfFloatLinearFiltering) && (C = 1),
        A === 1 && !this._caps.textureFloat && (A = 0,
        Logger$2.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type"));
        var S = new InternalTexture(this,InternalTextureSource.MultiRenderTarget);
        y.push(S),
        b.push(T + 1),
        S.baseWidth = g,
        S.baseHeight = m,
        S.width = g,
        S.height = m,
        S.isReady = !0,
        S.samples = 1,
        S.generateMipMaps = n,
        S.samplingMode = C,
        S.type = A,
        S._cachedWrapU = 0,
        S._cachedWrapV = 0,
        this._internalTexturesCache.push(S),
        this._textureHelper.createGPUTextureForInternalTexture(S)
    }
    return v && (v.incrementReferences(),
    y.push(v),
    this._internalTexturesCache.push(v)),
    _.setTextures(y),
    _
}
;
WebGPUEngine.prototype.updateMultipleRenderTargetTextureSampleCount = function(i, e) {
    if (!i || !i.textures || i.textures[0].samples === e)
        return e;
    var t = i._attachments.length;
    if (t === 0)
        return 1;
    e = Math.min(e, this.getCaps().maxMSAASamples);
    for (var r = 0; r < t; ++r) {
        var n = i.textures[r];
        this._textureHelper.createMSAATexture(n, e),
        n.samples = e
    }
    return i._depthStencilTexture && i._depthStencilTexture !== i.textures[i.textures.length - 1] && (this._textureHelper.createMSAATexture(i._depthStencilTexture, e),
    i._depthStencilTexture.samples = e),
    e
}
;
WebGPUEngine.prototype.bindAttachments = function(i) {
    i.length === 0 || !this._currentRenderTarget || (this._mrtAttachments = i)
}
;
WebGPUEngine.prototype.buildTextureLayout = function(i) {
    for (var e = [], t = 0; t < i.length; t++)
        i[t] ? e.push(t + 1) : e.push(0);
    return e
}
;
WebGPUEngine.prototype.restoreSingleAttachment = function() {}
;
WebGPUEngine.prototype.getGPUFrameTimeCounter = function() {
    return this._timestampQuery.gpuFrameTimeCounter
}
;
WebGPUEngine.prototype.captureGPUFrameTime = function(i) {
    this._timestampQuery.enable = i && !!this._caps.timerQuery
}
;
WebGPUEngine.prototype.createQuery = function() {
    return this._occlusionQuery.createQuery()
}
;
WebGPUEngine.prototype.deleteQuery = function(i) {
    return this._occlusionQuery.deleteQuery(i),
    this
}
;
WebGPUEngine.prototype.isQueryResultAvailable = function(i) {
    return this._occlusionQuery.isQueryResultAvailable(i)
}
;
WebGPUEngine.prototype.getQueryResult = function(i) {
    return this._occlusionQuery.getQueryResult(i)
}
;
WebGPUEngine.prototype.beginOcclusionQuery = function(i, e) {
    var t;
    if (this.compatibilityMode) {
        if (this._occlusionQuery.canBeginQuery)
            return (t = this._currentRenderPass) === null || t === void 0 || t.beginOcclusionQuery(e),
            !0
    } else {
        var r = this._getCurrentRenderPassIndex()
          , n = r === 0 ? this._bundleList : this._bundleListRenderTarget;
        return n.addItem(new WebGPURenderItemBeginOcclusionQuery(e)),
        !0
    }
    return !1
}
;
WebGPUEngine.prototype.endOcclusionQuery = function(i) {
    var e;
    if (this.compatibilityMode)
        (e = this._currentRenderPass) === null || e === void 0 || e.endOcclusionQuery();
    else {
        var t = this._getCurrentRenderPassIndex()
          , r = t === 0 ? this._bundleList : this._bundleListRenderTarget;
        r.addItem(new WebGPURenderItemEndOcclusionQuery)
    }
    return this
}
;
WebGPUEngine.prototype.createRawTexture = function(i, e, t, r, n, o, a, s, l, u) {
    s === void 0 && (s = null),
    l === void 0 && (l = 0),
    u === void 0 && (u = 0);
    var c = new InternalTexture(this,InternalTextureSource.Raw);
    return c.baseWidth = e,
    c.baseHeight = t,
    c.width = e,
    c.height = t,
    c.format = r,
    c.generateMipMaps = n,
    c.samplingMode = a,
    c.invertY = o,
    c._compression = s,
    c.type = l,
    this._doNotHandleContextLost || (c._bufferView = i),
    this._textureHelper.createGPUTextureForInternalTexture(c, e, t, void 0, u),
    this.updateRawTexture(c, i, r, o, s, l),
    this._internalTexturesCache.push(c),
    c
}
;
WebGPUEngine.prototype.updateRawTexture = function(i, e, t, r, n, o) {
    if (n === void 0 && (n = null),
    o === void 0 && (o = 0),
    !!i) {
        if (this._doNotHandleContextLost || (i._bufferView = e,
        i.invertY = r,
        i._compression = n),
        e) {
            var a = i._hardwareTexture
              , s = t === 4;
            s && (e = _convertRGBtoRGBATextureData(e, i.width, i.height, o));
            var l = new Uint8Array(e.buffer,e.byteOffset,e.byteLength);
            this._textureHelper.updateTexture(l, i, i.width, i.height, i.depth, a.format, 0, 0, r, !1, 0, 0, this._uploadEncoder),
            i.generateMipMaps && this._generateMipmaps(i, this._uploadEncoder)
        }
        i.isReady = !0
    }
}
;
WebGPUEngine.prototype.createRawCubeTexture = function(i, e, t, r, n, o, a, s) {
    s === void 0 && (s = null);
    var l = new InternalTexture(this,InternalTextureSource.CubeRaw);
    return r === 1 && !this._caps.textureFloatLinearFiltering ? (n = !1,
    a = 1,
    Logger$2.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")) : r === 2 && !this._caps.textureHalfFloatLinearFiltering ? (n = !1,
    a = 1,
    Logger$2.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")) : r === 1 && !this._caps.textureFloatRender ? (n = !1,
    Logger$2.Warn("Render to float textures is not supported. Mipmap generation forced to false.")) : r === 2 && !this._caps.colorBufferFloat && (n = !1,
    Logger$2.Warn("Render to half float textures is not supported. Mipmap generation forced to false.")),
    l.isCube = !0,
    l.format = t === 4 ? 5 : t,
    l.type = r,
    l.generateMipMaps = n,
    l.width = e,
    l.height = e,
    l.samplingMode = a,
    this._doNotHandleContextLost || (l._bufferViewArray = i),
    l._cachedWrapU = 0,
    l._cachedWrapV = 0,
    this._textureHelper.createGPUTextureForInternalTexture(l),
    i && this.updateRawCubeTexture(l, i, t, r, o, s),
    l
}
;
WebGPUEngine.prototype.updateRawCubeTexture = function(i, e, t, r, n, o, a) {
    o === void 0 && (o = null),
    i._bufferViewArray = e,
    i.invertY = n,
    i._compression = o;
    for (var s = i._hardwareTexture, l = t === 4, u = [], c = 0; c < e.length; ++c) {
        var h = e[c];
        l && (h = _convertRGBtoRGBATextureData(e[c], i.width, i.height, r)),
        u.push(new Uint8Array(h.buffer,h.byteOffset,h.byteLength))
    }
    this._textureHelper.updateCubeTextures(u, s.underlyingResource, i.width, i.height, s.format, n, !1, 0, 0, this._uploadEncoder),
    i.generateMipMaps && this._generateMipmaps(i, this._uploadEncoder),
    i.isReady = !0
}
;
WebGPUEngine.prototype.createRawCubeTextureFromUrl = function(i, e, t, r, n, o, a, s, l, u, c, h) {
    var f = this;
    l === void 0 && (l = null),
    u === void 0 && (u = null),
    c === void 0 && (c = 3),
    h === void 0 && (h = !1);
    var d = this.createRawCubeTexture(null, t, r, n, !o, h, c, null);
    e == null || e._addPendingData(d),
    d.url = i,
    this._internalTexturesCache.push(d);
    var _ = function(m, v) {
        e == null || e._removePendingData(d),
        u && m && u(m.status + " " + m.statusText, v)
    }
      , g = function(m) {
        var v = d.width
          , y = a(m);
        if (!!y) {
            var b = [0, 2, 4, 1, 3, 5];
            if (s)
                for (var T = r === 4, C = s(y), A = d._hardwareTexture, S = [0, 1, 2, 3, 4, 5], P = 0; P < C.length; P++) {
                    for (var R = v >> P, M = [], x = 0; x < 6; x++) {
                        var I = C[P][S[x]];
                        T && (I = _convertRGBtoRGBATextureData(I, R, R, n)),
                        M.push(new Uint8Array(I.buffer,I.byteOffset,I.byteLength))
                    }
                    f._textureHelper.updateCubeTextures(M, A.underlyingResource, R, R, A.format, h, !1, 0, 0, f._uploadEncoder)
                }
            else {
                for (var M = [], x = 0; x < 6; x++)
                    M.push(y[b[x]]);
                f.updateRawCubeTexture(d, M, r, n, h)
            }
            d.isReady = !0,
            e == null || e._removePendingData(d),
            l && l()
        }
    };
    return this._loadFile(i, function(m) {
        g(m)
    }, void 0, e == null ? void 0 : e.offlineProvider, !0, _),
    d
}
;
WebGPUEngine.prototype.createRawTexture3D = function(i, e, t, r, n, o, a, s, l, u, c) {
    l === void 0 && (l = null),
    u === void 0 && (u = 0),
    c === void 0 && (c = 0);
    var h = InternalTextureSource.Raw3D
      , f = new InternalTexture(this,h);
    return f.baseWidth = e,
    f.baseHeight = t,
    f.baseDepth = r,
    f.width = e,
    f.height = t,
    f.depth = r,
    f.format = n,
    f.type = u,
    f.generateMipMaps = o,
    f.samplingMode = s,
    f.is3D = !0,
    this._doNotHandleContextLost || (f._bufferView = i),
    this._textureHelper.createGPUTextureForInternalTexture(f, e, t, void 0, c),
    this.updateRawTexture3D(f, i, n, a, l, u),
    this._internalTexturesCache.push(f),
    f
}
;
WebGPUEngine.prototype.updateRawTexture3D = function(i, e, t, r, n, o) {
    if (n === void 0 && (n = null),
    o === void 0 && (o = 0),
    this._doNotHandleContextLost || (i._bufferView = e,
    i.format = t,
    i.invertY = r,
    i._compression = n),
    e) {
        var a = i._hardwareTexture
          , s = t === 4;
        s && (e = _convertRGBtoRGBATextureData(e, i.width, i.height, o));
        var l = new Uint8Array(e.buffer,e.byteOffset,e.byteLength);
        this._textureHelper.updateTexture(l, i, i.width, i.height, i.depth, a.format, 0, 0, r, !1, 0, 0, this._uploadEncoder),
        i.generateMipMaps && this._generateMipmaps(i, this._uploadEncoder)
    }
    i.isReady = !0
}
;
WebGPUEngine.prototype.createRawTexture2DArray = function(i, e, t, r, n, o, a, s, l, u, c) {
    l === void 0 && (l = null),
    u === void 0 && (u = 0),
    c === void 0 && (c = 0);
    var h = InternalTextureSource.Raw2DArray
      , f = new InternalTexture(this,h);
    return f.baseWidth = e,
    f.baseHeight = t,
    f.baseDepth = r,
    f.width = e,
    f.height = t,
    f.depth = r,
    f.format = n,
    f.type = u,
    f.generateMipMaps = o,
    f.samplingMode = s,
    f.is2DArray = !0,
    this._doNotHandleContextLost || (f._bufferView = i),
    this._textureHelper.createGPUTextureForInternalTexture(f, e, t, r, c),
    this.updateRawTexture2DArray(f, i, n, a, l, u),
    this._internalTexturesCache.push(f),
    f
}
;
WebGPUEngine.prototype.updateRawTexture2DArray = function(i, e, t, r, n, o) {
    if (n === void 0 && (n = null),
    o === void 0 && (o = 0),
    this._doNotHandleContextLost || (i._bufferView = e,
    i.format = t,
    i.invertY = r,
    i._compression = n),
    e) {
        var a = i._hardwareTexture
          , s = t === 4;
        s && (e = _convertRGBtoRGBATextureData(e, i.width, i.height, o));
        var l = new Uint8Array(e.buffer,e.byteOffset,e.byteLength);
        this._textureHelper.updateTexture(l, i, i.width, i.height, i.depth, a.format, 0, 0, r, !1, 0, 0, this._uploadEncoder),
        i.generateMipMaps && this._generateMipmaps(i, this._uploadEncoder)
    }
    i.isReady = !0
}
;
function _convertRGBtoRGBATextureData(i, e, t, r) {
    var n, o = 1;
    r === 1 ? n = new Float32Array(e * t * 4) : r === 2 ? (n = new Uint16Array(e * t * 4),
    o = 15360) : r === 7 ? n = new Uint32Array(e * t * 4) : n = new Uint8Array(e * t * 4);
    for (var a = 0; a < e; a++)
        for (var s = 0; s < t; s++) {
            var l = (s * e + a) * 3
              , u = (s * e + a) * 4;
            n[u + 0] = i[l + 0],
            n[u + 1] = i[l + 1],
            n[u + 2] = i[l + 2],
            n[u + 3] = o
        }
    return n
}
WebGPUEngine.prototype._readTexturePixels = function(i, e, t, r, n, o, a, s) {
    r === void 0 && (r = -1),
    n === void 0 && (n = 0),
    o === void 0 && (o = null),
    a === void 0 && (a = !0),
    s === void 0 && (s = !1);
    var l = i._hardwareTexture;
    return a && this.flushFramebuffer(),
    this._textureHelper.readPixels(l.underlyingResource, 0, 0, e, t, l.format, r, n, o, s)
}
;
WebGPUEngine.prototype._readTexturePixelsSync = function(i, e, t, r, n, o, a, s) {
    throw "_readTexturePixelsSync is unsupported in WebGPU!"
}
;
WebGPUEngine.prototype._createHardwareRenderTargetWrapper = function(i, e, t) {
    var r = new RenderTargetWrapper(i,e,t,this);
    return this._renderTargetWrapperCache.push(r),
    r
}
;
WebGPUEngine.prototype.createRenderTargetTexture = function(i, e) {
    var t = this._createHardwareRenderTargetWrapper(!1, !1, i)
      , r = {};
    e !== void 0 && typeof e == "object" ? (r.generateDepthBuffer = e.generateDepthBuffer === void 0 ? !0 : e.generateDepthBuffer,
    r.generateStencilBuffer = r.generateDepthBuffer && e.generateStencilBuffer) : (r.generateDepthBuffer = !0,
    r.generateStencilBuffer = !1);
    var n = this._createInternalTexture(i, e, !0, InternalTextureSource.RenderTarget);
    return t._generateDepthBuffer = r.generateDepthBuffer,
    t._generateStencilBuffer = !!r.generateStencilBuffer,
    t.setTextures(n),
    (t._generateDepthBuffer || t._generateStencilBuffer) && t.createDepthStencilTexture(0, r.samplingMode === void 0 || r.samplingMode === 2 || r.samplingMode === 2 || r.samplingMode === 3 || r.samplingMode === 3 || r.samplingMode === 5 || r.samplingMode === 6 || r.samplingMode === 7 || r.samplingMode === 11, t._generateStencilBuffer, t.samples),
    e !== void 0 && typeof e == "object" && e.createMipMaps && !r.generateMipMaps && (n.generateMipMaps = !0),
    this._textureHelper.createGPUTextureForInternalTexture(n, void 0, void 0, void 0, r.creationFlags),
    e !== void 0 && typeof e == "object" && e.createMipMaps && !r.generateMipMaps && (n.generateMipMaps = !1),
    t
}
;
WebGPUEngine.prototype._createDepthStencilTexture = function(i, e, t) {
    var r = new InternalTexture(this,InternalTextureSource.DepthStencil)
      , n = __assign({
        bilinearFiltering: !1,
        comparisonFunction: 0,
        generateStencil: !1,
        samples: 1,
        depthTextureFormat: 15
    }, e);
    return r.format = n.generateStencil ? 13 : n.depthTextureFormat === 15 ? 14 : n.depthTextureFormat,
    this._setupDepthStencilTexture(r, i, n.generateStencil, n.bilinearFiltering, n.comparisonFunction, n.samples),
    this._textureHelper.createGPUTextureForInternalTexture(r),
    this._internalTexturesCache.push(r),
    r
}
;
WebGPUEngine.prototype._setupDepthStencilTexture = function(i, e, t, r, n, o) {
    o === void 0 && (o = 1);
    var a = e.width || e
      , s = e.height || e
      , l = e.layers || 0;
    i.baseWidth = a,
    i.baseHeight = s,
    i.width = a,
    i.height = s,
    i.is2DArray = l > 0,
    i.depth = l,
    i.isReady = !0,
    i.samples = o,
    i.generateMipMaps = !1,
    i.samplingMode = r ? 2 : 1,
    i.type = 1,
    i._comparisonFunction = n,
    i._cachedWrapU = 0,
    i._cachedWrapV = 0
}
;
WebGPUEngine.prototype.updateRenderTargetTextureSampleCount = function(i, e) {
    return !i || !i.texture || i.samples === e || (e = Math.min(e, this.getCaps().maxMSAASamples),
    this._textureHelper.createMSAATexture(i.texture, e),
    i._depthStencilTexture && (this._textureHelper.createMSAATexture(i._depthStencilTexture, e),
    i._depthStencilTexture.samples = e),
    i.texture.samples = e),
    e
}
;
WebGPUEngine.prototype.createRenderTargetCubeTexture = function(i, e) {
    var t = this._createHardwareRenderTargetWrapper(!1, !0, i)
      , r = __assign({
        generateMipMaps: !0,
        generateDepthBuffer: !0,
        generateStencilBuffer: !1,
        type: 0,
        samplingMode: 3,
        format: 5,
        samples: 1
    }, e);
    r.generateStencilBuffer = r.generateDepthBuffer && r.generateStencilBuffer,
    t._generateDepthBuffer = r.generateDepthBuffer,
    t._generateStencilBuffer = r.generateStencilBuffer;
    var n = new InternalTexture(this,InternalTextureSource.RenderTarget);
    return n.width = i,
    n.height = i,
    n.depth = 0,
    n.isReady = !0,
    n.isCube = !0,
    n.samples = r.samples,
    n.generateMipMaps = r.generateMipMaps,
    n.samplingMode = r.samplingMode,
    n.type = r.type,
    n.format = r.format,
    this._internalTexturesCache.push(n),
    t.setTextures(n),
    (t._generateDepthBuffer || t._generateStencilBuffer) && t.createDepthStencilTexture(0, r.samplingMode === void 0 || r.samplingMode === 2 || r.samplingMode === 2 || r.samplingMode === 3 || r.samplingMode === 3 || r.samplingMode === 5 || r.samplingMode === 6 || r.samplingMode === 7 || r.samplingMode === 11, t._generateStencilBuffer, t.samples),
    e && e.createMipMaps && !r.generateMipMaps && (n.generateMipMaps = !0),
    this._textureHelper.createGPUTextureForInternalTexture(n),
    e && e.createMipMaps && !r.generateMipMaps && (n.generateMipMaps = !1),
    t
}
;
Effect.prototype.setTextureSampler = function(i, e) {
    this._engine.setTextureSampler(i, e)
}
;
WebGPUEngine.prototype.setTextureSampler = function(i, e) {
    var t;
    (t = this._currentMaterialContext) === null || t === void 0 || t.setSampler(i, e)
}
;
Effect.prototype.setStorageBuffer = function(i, e) {
    this._engine.setStorageBuffer(i, e)
}
;
WebGPUEngine.prototype.createStorageBuffer = function(i, e) {
    return this._createBuffer(i, e | 32)
}
;
WebGPUEngine.prototype.updateStorageBuffer = function(i, e, t, r) {
    var n = i;
    t === void 0 && (t = 0);
    var o;
    r === void 0 ? (e instanceof Array ? o = new Float32Array(e) : e instanceof ArrayBuffer ? o = new Uint8Array(e) : o = e,
    r = o.byteLength) : e instanceof Array ? o = new Float32Array(e) : e instanceof ArrayBuffer ? o = new Uint8Array(e) : o = e,
    this._bufferManager.setSubData(n, t, o, 0, r)
}
;
WebGPUEngine.prototype.readFromStorageBuffer = function(i, e, t, r) {
    var n = this;
    t = t || i.capacity;
    var o = this._bufferManager.createRawBuffer(t, BufferUsage.MapRead | BufferUsage.CopyDst);
    return this._renderTargetEncoder.copyBufferToBuffer(i.underlyingResource, e != null ? e : 0, o, 0, t),
    new Promise(function(a, s) {
        n.onEndFrameObservable.addOnce(function() {
            o.mapAsync(MapMode.Read, 0, t).then(function() {
                var l = o.getMappedRange(0, t)
                  , u = r;
                if (u === void 0)
                    u = new Uint8Array(t),
                    u.set(new Uint8Array(l));
                else {
                    var c = u.constructor;
                    u = new c(u.buffer),
                    u.set(new c(l))
                }
                o.unmap(),
                n._bufferManager.releaseBuffer(o),
                a(u)
            }, function(l) {
                return s(l)
            })
        })
    }
    )
}
;
WebGPUEngine.prototype.setStorageBuffer = function(i, e) {
    var t, r;
    (t = this._currentDrawContext) === null || t === void 0 || t.setBuffer(i, (r = e == null ? void 0 : e.getBuffer()) !== null && r !== void 0 ? r : null)
}
;
WebGPUEngine.prototype.createUniformBuffer = function(i) {
    var e;
    i instanceof Array ? e = new Float32Array(i) : e = i;
    var t = this._bufferManager.createBuffer(e, BufferUsage.Uniform | BufferUsage.CopyDst);
    return t
}
;
WebGPUEngine.prototype.createDynamicUniformBuffer = function(i) {
    return this.createUniformBuffer(i)
}
;
WebGPUEngine.prototype.updateUniformBuffer = function(i, e, t, r) {
    t === void 0 && (t = 0);
    var n = i, o;
    r === void 0 ? (e instanceof Float32Array ? o = e : o = new Float32Array(e),
    r = o.byteLength) : e instanceof Float32Array ? o = e : o = new Float32Array(e),
    this._bufferManager.setSubData(n, t, o, 0, r)
}
;
WebGPUEngine.prototype.bindUniformBufferBase = function(i, e, t) {
    this._currentDrawContext.setBuffer(t, i)
}
;
WebGPUEngine.prototype.bindUniformBlock = function(i, e, t) {}
;
WebGPUEngine.prototype.updateVideoTexture = function(i, e, t) {
    var r = this, n;
    if (!(!i || i._isDisabled)) {
        this._videoTextureSupported === void 0 && (this._videoTextureSupported = !0);
        var o = i._hardwareTexture;
        !((n = i._hardwareTexture) === null || n === void 0) && n.underlyingResource || (o = this._textureHelper.createGPUTextureForInternalTexture(i)),
        this.createImageBitmap(e).then(function(a) {
            r._textureHelper.updateTexture(a, i, i.width, i.height, i.depth, o.format, 0, 0, !t, !1, 0, 0, r._uploadEncoder),
            i.generateMipMaps && r._generateMipmaps(i, r._uploadEncoder),
            i.isReady = !0
        }).catch(function(a) {
            i.isReady = !0
        })
    }
}
;
const DEFAULT_LOGGER = {
    debug: console.log,
    info: console.log,
    warn: console.warn,
    error: console.error
}
  , pe = class {
    constructor(e) {
        E(this, "module");
        this.module = e
    }
    static setLogger(e) {
        pe.instance = e
    }
    debug(...e) {
        return pe.instance.debug(...e)
    }
    info(...e) {
        return pe.instance.info(...e)
    }
    warn(...e) {
        return pe.instance.warn(...e)
    }
    error(...e) {
        return pe.instance.error(...e)
    }
}
;
let Logger$1 = pe;
E(Logger$1, "instance", DEFAULT_LOGGER);
var Codes$2 = (i=>(i[i.Success = 0] = "Success",
i[i.Timeout = 1003] = "Timeout",
i))(Codes$2 || {});
const COMPONENT_LIST_PREFIX = "/component_list.json";
class XverseError$1 extends Error {
    constructor(e, t) {
        super(t);
        E(this, "code");
        this.code = e
    }
    toJSON() {
        return {
            code: this.code,
            message: this.message
        }
    }
    toString() {
        if (Object(this) !== this)
            throw new TypeError;
        let t = this.name;
        t = t === void 0 ? "Error" : String(t);
        let r = this.message;
        r = r === void 0 ? "" : String(r);
        const n = this.code;
        return r = n === void 0 ? r : n + "," + r,
        t === "" ? r : r === "" ? t : t + ": " + r
    }
}
class AvatarAssetLoadingError extends XverseError$1 {
    constructor(e) {
        super(5100, e || "[Engine] \u89D2\u8272\u8D44\u4EA7\u52A0\u8F7D\u5931\u8D25")
    }
}
class AvatarAnimationError extends XverseError$1 {
    constructor(e) {
        super(5101, e || "[Engine] \u89D2\u8272\u52A8\u753B\u64AD\u653E\u5931\u8D25")
    }
}
class TimeoutError$1 extends XverseError$1 {
    constructor(e) {
        super(Codes$2.Timeout, e || "[Engine] \u8D85\u65F6\u9519\u8BEF")
    }
}
class DuplicateAvatarIDError extends XverseError$1 {
    constructor(e) {
        super(5103, e || "[Engine] \u89D2\u8272id\u91CD\u590D")
    }
}
class ContainerLoadingFailedError extends XverseError$1 {
    constructor(e) {
        super(5104, e || "[Engine] \u89D2\u8272\u8D44\u4EA7\u62C9\u53D6\u9519\u8BEF")
    }
}
class XTvMediaUrlError extends XverseError$1 {
    constructor(e) {
        super(5201, e || "[Engine] \u4F20\u5165Url\u9519\u8BEF")
    }
}
class XTvVideoElementError extends XverseError$1 {
    constructor(e) {
        super(5202, e || "[Engine] \u4F20\u5165video DOM\u9519\u8BEF")
    }
}
class XTvModelError extends XverseError$1 {
    constructor(e) {
        super(5203, e || "[Engine] \u4F20\u5165TV\u6A21\u578Burl\u9519\u8BEF")
    }
}
class XLowpolyModelError extends XverseError$1 {
    constructor(e) {
        super(5204, e || "[Engine] \u4F20\u5165\u6A21\u578Burl\u9519\u8BEF")
    }
}
class XLowpolyJsonError extends XverseError$1 {
    constructor(e) {
        super(5205, e || "[Engine] \u4F20\u5165\u6A21\u578Bjson\u9519\u8BEF")
    }
}
class XDecalError extends XverseError$1 {
    constructor(e) {
        super(5206, e || "[Engine] Decal\u6A21\u578B\u9519\u8BEF")
    }
}
class XDecalTextureError extends XverseError$1 {
    constructor(e) {
        super(5207, e || "[Engine] decal\u7EB9\u7406\u9519\u8BEF")
    }
}
class XBreathPointError extends XverseError$1 {
    constructor(e) {
        super(5208, e || "[Engine] \u547C\u5438\u70B9\u9519\u8BEF")
    }
}
class XMaterialError extends XverseError$1 {
    constructor(e) {
        super(5210, e || "[Engine] Material\u9519\u8BEF")
    }
}
class ExceedMaxAvatarNumError extends XverseError$1 {
    constructor(e) {
        super(5211, e || "[Engine] \u89D2\u8272\u4E2A\u6570\u8D85\u51FA\u4E0A\u9650")
    }
}
const avatarSetting = {
    fileType: ".glb",
    lodType: "_lod",
    lod: [{
        level: "lod0",
        fileName: ".glb",
        quota: 5,
        dist: 1e3
    }, {
        level: "lod1",
        fileName: "_lod2.glb",
        quota: 5,
        dist: 2e3
    }, {
        level: "lod2",
        fileName: "_lod4.glb",
        quota: 0,
        dist: 7500
    }],
    isRayCastEnable: !0,
    maxAvatarNum: 40,
    maxBillBoardDist: 7500,
    body: "body",
    head: "head",
    hair: "hair",
    suit: "suit",
    pants: "pants",
    shoes: "shoes",
    clothes: "clothes",
    animations: "animations",
    defaultIdle: "Idle",
    cullingDistance: 200,
    defaultMove: "Walking"
}
  , avatarResources = {
    ygb: {
        name: "ygb",
        mat: "NM_ygb",
        mesh: "ygb"
    }
}
  , action = {
    GiftClap: {
        animName: "GiftClap",
        keyTime: 1760
    },
    Cheering: {
        animName: "Cheering",
        attachPair: [{
            bone: "mixamorig_MiddleFinger2_R",
            obj: "ygb",
            offset: {
                x: 0,
                y: 0,
                z: 0
            },
            rotate: {
                x: 0,
                y: 3.84,
                z: 0
            },
            scale: {
                x: 1,
                y: 1,
                z: 1
            }
        }, {
            bone: "mixamorig_MiddleFinger2_L",
            obj: "ygb",
            offset: {
                x: 0,
                y: 0,
                z: 0
            },
            rotate: {
                x: 0,
                y: 3.49,
                z: 0
            },
            scale: {
                x: 1,
                y: 1,
                z: 1
            }
        }]
    }
}
  , getAnimationKey = (i,e)=>e + "_" + i
  , log$K = new Logger$1("AvatarManager");
class XAvatarLoader {
    constructor() {
        E(this, "containers", new Map);
        E(this, "meshes", new Map);
        E(this, "animations", new Map);
        E(this, "aniPath", new Map);
        E(this, "binPath", new Map);
        E(this, "texPath", new Map);
        E(this, "matPath", new Map);
        E(this, "mshPath", new Map);
        E(this, "rootPath", new Map);
        E(this, "meshTexList", new Map);
        E(this, "_enableIdb", !0);
        E(this, "_mappings", new Map);
        E(this, "_sharedTex", new Map);
        E(this, "avaliableAnimation", new Map);
        E(this, "enableShareTexture", !0);
        E(this, "enableShareAnimation", !0);
        E(this, "fillEmptyLod", !0);
        const e = new GLTFFileLoader;
        SceneLoader.RegisterPlugin(e),
        e.preprocessUrlAsync = function(t) {
            const r = avatarLoader._mappings.get(t);
            return r ? Promise.resolve(r) : Promise.resolve(t)
        }
    }
    getParsedUrl(e, t, r, n="") {
        return new Promise((o,a)=>{
            if (!r || r.indexOf(".zip") === -1)
                return o(r);
            const s = this.rootPath.get(r);
            if (s)
                return o(s);
            {
                const l = ".zip"
                  , u = r.replace(l, "") + COMPONENT_LIST_PREFIX;
                e.urlTransformer(u, !0).then(c=>{
                    if (!c)
                        return a("Loading Failed");
                    new Response(c).json().then(h=>{
                        var _, g, m, v, y, b, T;
                        const f = r.replace(l, "")
                          , d = f + ((_ = h == null ? void 0 : h.components) == null ? void 0 : _.url.replace("./", ""));
                        if (this.rootPath.set(r, d),
                        h.components ? (h.components.url && this.mshPath.set(t, f + "/" + ((g = h == null ? void 0 : h.components) == null ? void 0 : g.url.replace("./", ""))),
                        h.components.url_lod2 && this.mshPath.set(t + "_" + avatarSetting.lod[1].level, f + "/" + ((m = h == null ? void 0 : h.components) == null ? void 0 : m.url_lod2.replace("./", ""))),
                        h.components.url_lod4 && this.mshPath.set(t + "_" + avatarSetting.lod[2].level, f + "/" + ((v = h == null ? void 0 : h.components) == null ? void 0 : v.url_lod4.replace("./", "")))) : (h.meshes.url && this.mshPath.set(t, f + "/" + ((y = h == null ? void 0 : h.meshes) == null ? void 0 : y.url.replace("./", ""))),
                        h.meshes.url_lod2 && this.mshPath.set(t + "_" + avatarSetting.lod[1].level, f + "/" + ((b = h == null ? void 0 : h.meshes) == null ? void 0 : b.url_lod2.replace("./", ""))),
                        h.meshes.url_lod4 && this.mshPath.set(t + "_" + avatarSetting.lod[2].level, f + "/" + ((T = h == null ? void 0 : h.meshes) == null ? void 0 : T.url_lod4.replace("./", "")))),
                        h.materials && h.materials.forEach(C=>{
                            const A = f + "/" + C.url;
                            this.matPath.set(C.name, A)
                        }
                        ),
                        h.bin) {
                            const C = f + "/" + h.bin.url;
                            this.binPath.set(t, C);
                            const A = f + "/" + h.bin.url_lod2;
                            this.binPath.set(t + "_" + avatarSetting.lod[1].level, A);
                            const S = f + "/" + h.bin.url_lod4;
                            this.binPath.set(t + "_" + avatarSetting.lod[2].level, S)
                        }
                        return h.textures && h.textures.forEach(C=>{
                            const A = f + "/" + C.url;
                            this.texPath.set(C.url, A);
                            const S = this.meshTexList.get(h.components.url);
                            C.type === "png" && (S ? S.find(P=>P === C.name) || S.push(C.url) : this.meshTexList.set(t, [C.name]))
                        }
                        ),
                        o(d)
                    }
                    ).catch(h=>{
                        log$K.error(`[Engine] parse json file error,${h}`)
                    }
                    )
                }
                ).catch(c=>{
                    log$K.error(`[Engine] ulrtransform error, cannot find resource in db,${c}`)
                }
                )
            }
        }
        )
    }
    async parse(e, t) {
        const r = [];
        t.forEach(n=>{
            this._setAnimationList(n.id, n.animations),
            r.push(this.getParsedUrl(e, n.id, n.url)),
            n.components.forEach(o=>{
                o.units.forEach(a=>{
                    r.push(this.getParsedUrl(e, a.name, a.url))
                }
                )
            }
            )
        }
        ),
        await Promise.all(r)
    }
    _setAnimationList(e, t) {
        t ? t.forEach(r=>{
            this.aniPath.set(e + "_" + r.name, r.url)
        }
        ) : log$K.error("[Engine] no animation list exist, please check config for details")
    }
    disposeContainer() {
        this.containers.forEach((e,t)=>{
            e.xReferenceCount < 1 && (this.enableShareTexture && e.textures.length > 0 && e.textures[0].xReferenceCount != null && (e.textures[0].xReferenceCount--,
            e.textures = []),
            e.dispose(),
            this.containers.delete(t))
        }
        ),
        this._sharedTex.forEach((e,t)=>{
            e.xReferenceCount == 0 && (e.dispose(),
            this._sharedTex.delete(t))
        }
        )
    }
    set enableIdb(e) {
        this._enableIdb = e
    }
    getGlbPath(e) {
        return this.aniPath.get(e + ".glb")
    }
    getGltfPath(e) {
        return this.mshPath.get(e + ".gltf")
    }
    getPngUrl(e) {
        return this.texPath.get(e + ".png")
    }
    getMeshUrl(e) {
        return this.mshPath.get(e)
    }
    _getSourceKey(e, t) {
        return t && avatarSetting.lod[t] ? e + avatarSetting.lod[t].fileName.split(".")[0] : e
    }
    _getAnimPath(e, t) {
        let r = this.aniPath.get(t + "_animations_" + t.split("_")[1]);
        return r || (r = this.aniPath.get(t + "_" + e)),
        r
    }
    load(e, t, r, n) {
        return new Promise((o,a)=>{
            this.loadGlb(e, t, r).then(s=>s ? o(s) : a("[Engine] container load failed")).catch(()=>a("[Engine] container load failed"))
        }
        )
    }
    _searchAnimation(e, t) {
        let r;
        return this.containers.forEach((n,o)=>{
            const a = t.split("_")[0];
            o.indexOf(a) != -1 && o.indexOf(e) != -1 && (r = n)
        }
        ),
        r
    }
    loadAnimRes(e, t, r) {
        return new Promise((n,o)=>{
            const a = this._getAnimPath(t, r)
              , s = getAnimationKey(t, r);
            if (a && this.containers.get(a))
                return n(this.containers.get(a));
            if (a)
                this._loadGlbFromBlob(e, s, a).then(l=>l.animationGroups.length == 0 ? (this.containers.delete(s),
                l.dispose(),
                Promise.reject("container does not contains animation data")) : n(l));
            else
                return o("no such url")
        }
        )
    }
    loadGlb(e, t, r) {
        let n = this.getMeshUrl(this._getSourceKey(t, r));
        return !n && this.fillEmptyLod && (r = 0,
        n = this.getMeshUrl(this._getSourceKey(t, r))),
        n && this.containers.get(n) ? Promise.resolve(this.containers.get(n)) : n ? this._enableIdb ? Promise.resolve(this._loadGlbFromBlob(e, this._getSourceKey(t, r), n)) : Promise.resolve(this._loadGlbFromUrl(e, this._getSourceKey(t, r), n)) : Promise.reject("no such url")
    }
    loadGltf(e, t, r, n) {
        const o = this._getSourceKey(t, r || 0);
        let a = this.getGltfPath(o);
        return !a && this.fillEmptyLod && (a = this.getGltfPath(t)),
        a && this.containers.get(a) ? Promise.resolve(this.containers.get(a)) : this._enableIdb ? this._loadGltfFromBlob(e, t, r, n) : a ? this._loadGltfFromUrl(e, t, a.replace(t + ".gltf", "")) : Promise.reject()
    }
    loadSubsequence() {}
    loadVAT() {}
    getResourceName(e) {
        return this.meshTexList.get(e)
    }
    _loadGltfFromUrl(e, t, r) {
        return SceneLoader.LoadAssetContainerAsync(r, t + ".gltf", e.Scene, null, ".gltf")
    }
    _loadGlbFromBlob(e, t, r) {
        return new Promise((n,o)=>{
            e.urlTransformer(r).then(a=>{
                SceneLoader.LoadAssetContainerAsync("", a, e.Scene, null, ".glb").then(s=>{
                    if (s) {
                        if (this.enableShareTexture && s.textures.length > 0) {
                            const l = t.indexOf("_lod") != -1 ? t.slice(0, -5) : t
                              , u = this._sharedTex.get(l);
                            u ? (s.meshes[1].material._albedoTexture = u,
                            s.textures.forEach(c=>{
                                c.dispose()
                            }
                            ),
                            s.textures = [u],
                            u.xReferenceCount++) : (this._sharedTex.set(l, s.textures[0]),
                            s.textures[0].xReferenceCount = 1)
                        }
                        return s.addAllToScene(),
                        s.xReferenceCount = 0,
                        s.meshes.forEach(l=>{
                            l.setEnabled(!1)
                        }
                        ),
                        this.containers.set(r, s),
                        n(s)
                    } else
                        o("glb file load failed")
                }
                )
            }
            )
        }
        )
    }
    _loadGlbFromUrl(e, t, r) {
        return new Promise((n,o)=>{
            SceneLoader.LoadAssetContainerAsync("", r, e.Scene, null, ".glb").then(a=>{
                if (a) {
                    if (a.addAllToScene(),
                    a.meshes.forEach(s=>{
                        s.setEnabled(!1)
                    }
                    ),
                    this.enableShareTexture && a.textures.length > 0) {
                        const s = t.indexOf("_lod") != -1 ? t.slice(0, -5) : t
                          , l = this._sharedTex.get(s);
                        l ? (a.meshes[1].material._albedoTexture = l,
                        a.textures.forEach(u=>{
                            u.dispose()
                        }
                        ),
                        a.textures = [l],
                        l.xReferenceCount++) : (this._sharedTex.set(s, a.textures[0]),
                        a.textures[0].xReferenceCount = 1)
                    }
                    return a.xReferenceCount = 0,
                    this.containers.set(r, a),
                    n(a)
                } else
                    o("glb file load failed")
            }
            )
        }
        )
    }
    _loadGltfFromBlob(e, t, r, n) {
        return new Promise((o,a)=>{
            const s = [];
            let l = this._getSourceKey(t, r)
              , u = this.getGltfPath(l);
            if (!u && this.fillEmptyLod && (r = 0,
            l = this._getSourceKey(t, r),
            u = this.getGltfPath(l)),
            !u)
                return a(`[Engine] gltf path incorrect ${l},cancel.`);
            const c = this.mshPath.get(l + ".gltf");
            if (!c)
                return a("cannot find asset mshPath");
            const h = this.binPath.get(l + ".bin");
            if (!h)
                return a("cannot find asset binPath");
            if (!n) {
                const _ = this.meshTexList.get(t);
                if (!_ || _.length == 0)
                    return a("cannot find texture");
                n = _[0]
            }
            const f = this.texPath.get(n + ".png");
            if (!f)
                return a();
            const d = this.texPath.get(n + "-astc.ktx");
            if (!d)
                return a();
            s.push(this._blobMapping(e, c)),
            s.push(this._blobMapping(e, h)),
            s.push(this._blobMapping(e, f)),
            s.push(this._blobMapping(e, d)),
            Promise.all(s).then(()=>{
                const _ = u.replace(l + ".gltf", "");
                SceneLoader.LoadAssetContainerAsync(_, l + ".gltf", e.Scene, null, ".gltf").then(g=>{
                    var v;
                    this.containers.set(u, g),
                    g.addAllToScene(),
                    g.meshes.forEach(y=>{
                        y.setEnabled(!1)
                    }
                    );
                    const m = this._sharedTex.get(t);
                    m ? ((v = g.meshes[1].material._albedoTexture) == null || v.dispose(),
                    g.meshes[1].material._albedoTexture = m) : this._sharedTex.set(t, g.meshes[1].material._albedoTexture),
                    o(g)
                }
                )
            }
            )
        }
        )
    }
    _blobMapping(e, t) {
        return new Promise((r,n)=>{
            e.urlTransformer(t).then(o=>o ? (this._mappings.set(t, o),
            r(t)) : n(`[Engine] url urlTransformer parse error ${t}`))
        }
        )
    }
}
const avatarLoader = new XAvatarLoader
  , log$J = new Logger$1("AnimationController");
class XAnimationController {
    constructor(e) {
        E(this, "iBodyAnim");
        E(this, "animations", []);
        E(this, "defaultAnimation", "Idle");
        E(this, "onPlay", "Idle");
        E(this, "loop", !0);
        E(this, "animationExtras", []);
        E(this, "enableBlend", !1);
        E(this, "enableSkLod", !1);
        E(this, "_boneMap", new Map);
        E(this, "_lodMask", new Map);
        E(this, "activeFaceAnimation");
        E(this, "iFaceAnim");
        E(this, "_scene");
        E(this, "_avatar");
        E(this, "onPlayObservable", new Observable);
        E(this, "postObserver");
        E(this, "playAnimation", (e,t,r=0,n,o,a)=>new Promise((s,l)=>{
            if (this._isPlaying(e, r) || (this._registerAnimInfo(e, t, r, n, o, a),
            !this._isAnimate()))
                return s(null);
            this._prerocess(e, t),
            this._avatar.avatarManager.loadAnimation(this._avatar.avatarType, e).then(u=>{
                if (!u)
                    return l(new AvatarAnimationError("animation group does not exist"));
                const c = this._mappingSkeleton(u);
                if (!c)
                    return l(new AvatarAnimationError("mapping animation failed"));
                if (c && this._isAnimationValid(c))
                    return c.dispose(),
                    l(new AvatarAnimationError("mapping animation failed"));
                if (this.enableSkLod && this.skeletonMask(c, r),
                this.detachAnimation(r),
                r == 0 ? this.iBodyAnim.animGroup = c : r == 1 && (this.iFaceAnim.animGroup = c),
                !this._playAnimation(r))
                    return l(new AvatarAnimationError("[Engine] play animation failed, animtion resource does not match current character"));
                this._playEffect(),
                this.postObserver = c.onAnimationEndObservable.addOnce(()=>(this._postprocess(r),
                s(null)))
            }
            )
        }
        ));
        E(this, "stopAnimation", (e=0)=>{
            var t, r, n, o;
            switch (e) {
            case 0:
                this.iBodyAnim && this.iBodyAnim.animGroup && ((t = this.iBodyAnim) == null || t.animGroup.stop());
                break;
            case 1:
                this.iFaceAnim && this.iFaceAnim.animGroup && ((r = this.iFaceAnim) == null || r.animGroup.stop());
                break;
            case 2:
                this.iBodyAnim && this.iBodyAnim.animGroup && ((n = this.iBodyAnim) == null || n.animGroup.stop()),
                this.iFaceAnim && this.iFaceAnim.animGroup && ((o = this.iFaceAnim) == null || o.animGroup.stop());
                break
            }
        }
        );
        E(this, "pauseAnimation", (e=0)=>{
            var t, r, n, o;
            switch (e) {
            case 0:
                this.iBodyAnim && this.iBodyAnim.animGroup && ((t = this.iBodyAnim) == null || t.animGroup.pause());
                break;
            case 1:
                this.iFaceAnim && this.iFaceAnim.animGroup && ((r = this.iFaceAnim) == null || r.animGroup.pause());
                break;
            case 2:
                this.iBodyAnim && this.iBodyAnim.animGroup && ((n = this.iBodyAnim) == null || n.animGroup.pause()),
                this.iFaceAnim && this.iFaceAnim.animGroup && ((o = this.iFaceAnim) == null || o.animGroup.pause());
                break
            }
        }
        );
        E(this, "resetAnimation", (e=0)=>{
            var t, r, n, o;
            switch (e) {
            case 0:
                this.iBodyAnim && this.iBodyAnim.animGroup && ((t = this.iBodyAnim) == null || t.animGroup.reset());
                break;
            case 1:
                this.iFaceAnim && this.iFaceAnim.animGroup && ((r = this.iFaceAnim) == null || r.animGroup.reset());
                break;
            case 2:
                this.iBodyAnim && this.iBodyAnim.animGroup && ((n = this.iBodyAnim) == null || n.animGroup.reset()),
                this.iFaceAnim && this.iFaceAnim.animGroup && ((o = this.iFaceAnim) == null || o.animGroup.reset());
                break
            }
        }
        );
        this._avatar = e,
        this._scene = e.avatarManager.scene,
        this.animationExtras.push(action.Cheering.animName),
        this._boneMap = new Map
    }
    _isPlaying(e, t) {
        return t == 0 && this.iBodyAnim != null && this.iBodyAnim.animGroup && e == this.iBodyAnim.name ? !0 : !!(t == 1 && this.iFaceAnim != null && this.iFaceAnim.animGroup && e == this.iFaceAnim.name)
    }
    activeAnimation(e=0) {
        var t, r;
        switch (e) {
        case 0:
            return (t = this.iBodyAnim) == null ? void 0 : t.animGroup;
        case 1:
            return (r = this.iFaceAnim) == null ? void 0 : r.animGroup;
        default:
            return
        }
    }
    enableAnimationBlend(e=.1, t=0) {
        var r, n, o, a;
        if (t == 0 && ((r = this.iBodyAnim) == null ? void 0 : r.animGroup))
            for (const s of (n = this.iBodyAnim) == null ? void 0 : n.animGroup.targetedAnimations)
                s.animation.enableBlending = !0,
                s.animation.blendingSpeed = e;
        else if (t == 0 && ((o = this.iFaceAnim) == null ? void 0 : o.animGroup))
            for (const s of (a = this.iFaceAnim) == null ? void 0 : a.animGroup.targetedAnimations)
                s.animation.enableBlending = !0,
                s.animation.blendingSpeed = e
    }
    disableAnimationBlend(e=0) {
        var t, r, n, o;
        if (e == 0 && ((t = this.iBodyAnim) == null ? void 0 : t.animGroup))
            for (const a of (r = this.iBodyAnim) == null ? void 0 : r.animGroup.targetedAnimations)
                a.animation.enableBlending = !1;
        else if (e == 0 && ((n = this.iFaceAnim) == null ? void 0 : n.animGroup))
            for (const a of (o = this.iFaceAnim) == null ? void 0 : o.animGroup.targetedAnimations)
                a.animation.enableBlending = !1
    }
    skeletonMask(e, t=0) {
        if (t == 0) {
            const r = this._lodMask.get(this._avatar.distLevel);
            if (r)
                for (let n = 0; n < e.targetedAnimations.length; ++n)
                    r.includes(e.targetedAnimations[n].target.name) || (e.targetedAnimations.splice(n, 1),
                    n--);
            return !0
        }
        return !1
    }
    detachAnimation(e=2) {
        var t, r;
        switch (e) {
        case 0:
            this.iBodyAnim && this.iBodyAnim.animGroup && (this.iBodyAnim.animGroup._parentContainer.xReferenceCount && this.iBodyAnim.animGroup._parentContainer.xReferenceCount--,
            this.iBodyAnim.animGroup.stop(),
            this.iBodyAnim.animGroup.dispose(),
            this.iBodyAnim.animGroup = void 0);
            break;
        case 1:
            this.iFaceAnim && this.iFaceAnim.animGroup && (this.iFaceAnim.animGroup._parentContainer.xReferenceCount && this.iFaceAnim.animGroup._parentContainer.xReferenceCount--,
            this.iFaceAnim.animGroup.stop(),
            this.iFaceAnim.animGroup.dispose(),
            this.iFaceAnim.animGroup = void 0);
            break;
        case 2:
            this.iBodyAnim && this.iBodyAnim.animGroup && (this.iBodyAnim.animGroup._parentContainer.xReferenceCount && this.iBodyAnim.animGroup._parentContainer.xReferenceCount--,
            (t = this.iBodyAnim) == null || t.animGroup.stop(),
            (r = this.iBodyAnim) == null || r.animGroup.dispose(),
            this.iBodyAnim.animGroup = void 0),
            this.iFaceAnim && this.iFaceAnim.animGroup && (this.iFaceAnim.animGroup._parentContainer.xReferenceCount && this.iFaceAnim.animGroup._parentContainer.xReferenceCount--,
            this.iFaceAnim.animGroup.stop(),
            this.iFaceAnim.animGroup.dispose(),
            this.iFaceAnim.animGroup = void 0);
            break
        }
    }
    blendAnimation() {}
    getAnimation(e, t) {
        return avatarLoader.animations.get(getAnimationKey(t, e))
    }
    _mappingSkeleton(e) {
        if (e) {
            const t = e.clone(e.name, r=>{
                var o, a, s;
                const n = r.name.split(" ").length > 2 ? r.name.split(" ")[2] : r.name;
                if (this._boneMap.size === ((o = this._avatar.skeleton) == null ? void 0 : o.bones.length))
                    return this._boneMap.get(n);
                {
                    const l = (s = (a = this._avatar.skeleton) == null ? void 0 : a.bones.find(u=>u.name === r.name || u.name === r.name.split(" ")[2])) == null ? void 0 : s.getTransformNode();
                    return l && (l.name = n,
                    this._boneMap.set(n, l)),
                    l
                }
            }
            );
            return t._parentContainer = e._parentContainer,
            t
        } else
            return
    }
    removeAnimation(e) {
        const t = avatarLoader.containers.get(e.name);
        t && (t.dispose(),
        avatarLoader.containers.delete(e.name),
        avatarLoader.animations.delete(getAnimationKey(e.name, e.skType)))
    }
    _setPosition(e, t) {
        this._avatar.priority === 0 && this._avatar.isRender && e === this.defaultAnimation && e != this.onPlay && !this._avatar.isSelected && this._avatar.setPosition(this._avatar.position, !0)
    }
    _registerAnimInfo(e, t, r=0, n, o, a) {
        const s = {
            name: e,
            skType: this._avatar.avatarType,
            loop: t,
            playSpeed: n,
            currentFrame: 0,
            startFrame: o,
            endFrame: a
        };
        r == 0 ? this.iBodyAnim == null ? this.iBodyAnim = s : (this.iBodyAnim.name = e,
        this.iBodyAnim.skType = this._avatar.avatarType,
        this.iBodyAnim.loop = t,
        this.iBodyAnim.playSpeed = n,
        this.iBodyAnim.currentFrame = 0,
        this.iBodyAnim.startFrame = o,
        this.iBodyAnim.endFrame = a) : r == 1 && (this.iFaceAnim == null ? this.iFaceAnim = s : (this.iFaceAnim.name = e,
        this.iFaceAnim.skType = this._avatar.avatarType,
        this.iFaceAnim.loop = t,
        this.iFaceAnim.playSpeed = n,
        this.iFaceAnim.currentFrame = 0,
        this.iFaceAnim.startFrame = o,
        this.iFaceAnim.endFrame = a)),
        this.onPlay = e,
        this.loop = t
    }
    _isAnimate() {
        var e;
        return !(!this._avatar.isRender || !this._avatar.skeleton || ((e = this._avatar.rootNode) == null ? void 0 : e.getChildMeshes().length) == 0)
    }
    _prerocess(e, t) {
        this._avatar.isRayCastEnable && this._setPosition(e, t),
        this._avatar.priority === 0 && log$J.info(`start play animation: ${e} on avatar ${this._avatar.id}`)
    }
    _playEffect() {
        this.animationExtras.indexOf(this.iBodyAnim.name) != -1 && action.Cheering.attachPair.forEach(t=>{
            this._avatar.attachExtraProp(t.obj, t.bone, new Vector3(t.offset.x,t.offset.y,t.offset.z), new Vector3(t.rotate.x,t.rotate.y,t.rotate.z)),
            this._avatar.showExtra(t.obj)
        }
        )
    }
    _playAnimation(e=0) {
        var t, r;
        return e == 0 && this.iBodyAnim && ((t = this.iBodyAnim) == null ? void 0 : t.animGroup) ? (this.onPlayObservable.notifyObservers(this._scene),
        this.iBodyAnim.animGroup.start(this.loop, this.iBodyAnim.playSpeed, this.iBodyAnim.startFrame, this.iBodyAnim.endFrame, !1),
        !0) : e == 1 && this.iFaceAnim && ((r = this.iFaceAnim) == null ? void 0 : r.animGroup) ? (this.iFaceAnim.animGroup.start(this.loop, this.iFaceAnim.playSpeed, this.iFaceAnim.startFrame, this.iFaceAnim.endFrame, !1),
        !0) : !1
    }
    _postprocess(e) {
        var r, n;
        let t;
        e == 0 ? t = (r = this.iBodyAnim) == null ? void 0 : r.name : e == 1 && (t = (n = this.iFaceAnim) == null ? void 0 : n.name),
        t === action.Cheering.animName && this._avatar.disposeExtra()
    }
    _isAnimationValid(e) {
        for (let t = 0; t < e.targetedAnimations.length; ++t)
            if (e.targetedAnimations[t].target)
                return !1;
        return !0
    }
}
const checkOS = ()=>{
    const i = navigator.userAgent
      , e = /(?:Windows Phone)/.test(i)
      , t = /(?:SymbianOS)/.test(i) || e
      , r = /(?:Android)/.test(i)
      , n = /(?:Firefox)/.test(i);
    /(?:Chrome|CriOS)/.test(i);
    const o = /(?:iPad|PlayBook)/.test(i) || r && !/(?:Mobile)/.test(i) || n && /(?:Tablet)/.test(i)
      , a = /(?:iPhone|ipad|ipod)/.test(i) && !o
      , s = !a && !r && !t;
    return {
        isTablet: o,
        isPhone: a,
        isIOS: /iPhone|iPod|iPad/.test(navigator.userAgent),
        isAndroid: r,
        isPc: s
    }
}
  , ue4Rotation2Xverse = i=>isRotationCorrect() ? (i.pitch >= 89.5 ? i.pitch = 89.5 : i.pitch <= -89.5 && (i.pitch = -89.5),
new Vector3(-1 * Math.PI * i.pitch / 180,Math.PI * i.yaw / 180 - Math.PI * 27 / 18,Math.PI * i.roll / 180 < .001 ? 0 : Math.PI * i.roll / 180)) : null
  , ue4Rotation2Xverse_mesh = i=>isRotationCorrect() ? new Vector3(Math.PI * i.pitch / 180,Math.PI * i.yaw / 180,Math.abs(Math.PI * i.roll) / 180 < .001 ? 0 : -1 * (Math.PI * i.roll) / 180) : null
  , scaleFromUE4toXverse = 100
  , ue4Scaling2Xverse = i=>isScalingCorrect() ? new Vector3(i.x,i.z,-1 * i.y) : null
  , ue4Position2Xverse = i=>isPositionCorrect() ? new Vector3(i.x * .01,i.z * .01,-1 * i.y * .01) : null
  , xversePosition2Ue4 = i=>isPositionCorrect() ? {
    x: i.x * 100,
    y: -1 * i.z * 100,
    z: i.y * 100
} : null
  , xverseRotation2Ue4 = i=>{
    if (isPositionCorrect()) {
        let e = 0;
        return i.z == 0 ? e = 0 : e = 180 * i.z / Math.PI,
        {
            pitch: 180 * i.x * -1 / Math.PI,
            yaw: (i.y + Math.PI * 27 / 18) * 180 / Math.PI,
            roll: e
        }
    } else
        return null
}
  , calcDistance3D = (i,e)=>Math.sqrt((i.x - e.x) * (i.x - e.x) + (i.y - e.y) * (i.y - e.y) + (i.z - e.z) * (i.z - e.z))
  , calcDistance3DVector = (i,e)=>Math.sqrt((i.x - e.x) * (i.x - e.x) + (i.y - e.y) * (i.y - e.y) + (i.z - e.z) * (i.z - e.z))
  , isPositionCorrect = i=>!0
  , isScalingCorrect = i=>!0
  , calcDistance3DAngle = (i,e)=>Math.sqrt((i.roll - e.roll) * (i.roll - e.roll) + (i.pitch - e.pitch) * (i.pitch - e.pitch) + (i.yaw - e.yaw) * (i.yaw - e.yaw))
  , isRotationCorrect = i=>!0
  , getStringBoundaries = (i,e,t=new Map)=>{
    let r = 0
      , n = ""
      , o = -1
      , a = 0;
    const s = [0];
    for (let l = 0; l < i.length; l++) {
        const u = i.codePointAt(l);
        let c = t.get(u);
        if (c)
            r += c,
            n += i[l],
            u > 64 && u < 91 || u > 96 && u < 123 ? (o == -1 && (o = l),
            a += c) : (o = -1,
            a = 0);
        else if (u < 975 || u > 1024 && u < 1920)
            c = 1,
            r++,
            n += i[l],
            u > 64 && u < 91 || u > 96 && u < 123 ? (o == -1 && (o = l),
            a += c) : (o = -1,
            a = 0);
        else if (u > 4499 && u < 4600 || u > 8207 && u < 8232 || u > 8238 && u < 8287 || u > 8238 && u < 8287 || u > 8304 && u < 8384 || u > 8447 && u < 9211 || u > 11263 && u < 11624 || u > 11646 && u < 11671 || u > 11679 && u < 11845 || u > 11903 && u < 12020 || u > 12031 && u < 12246 || u > 12287 && u < 12544 || u > 12548 && u < 12728 || u > 12735 && u < 12772 || u > 12783 && u < 19894 || u > 19967 && u < 40918 || u > 42191 && u < 42240 || u > 44031 && u < 55204 || u > 59276 && u < 59287 || u > 59412 && u < 59493 || u > 63743 && u < 64207 || u > 65039 && u < 65050 || u > 65071 && u < 65510)
            c = 2,
            r += 2,
            o = -1,
            a = 0,
            n += i[l];
        else if (u > 9311 && u < 11158) {
            c = 2,
            r += 2,
            o = -1,
            a = 0,
            n += i[l];
            const h = i.codePointAt(l + 1);
            h > 65023 && h < 65040 && (n += i[l + 1],
            l++)
        } else
            u > 126979 && u < 129783 && (c = 2,
            r += 2,
            o = -1,
            a = 0,
            l++,
            n += String.fromCodePoint(u));
        if (l == s[s.length - 1] + 1 && o > 0 ? (s[s.length - 1] = o,
        r = 0 + a) : r > e && (s.push(l),
        a >= r && (a = 0 + c,
        o = 0),
        r = 0 + c),
        l >= i.length - 1)
            break
    }
    return s[s.length - 1] != i.length && s.push(i.length),
    [n, s]
}
  , getAlphaWidthMap = (i,e)=>{
    const t = new DynamicTexture("test",3,e)
      , r = new Map;
    for (let n = 32; n < 127; n++) {
        const o = String.fromCodePoint(n)
          , a = 2 + "px " + i;
        t.drawText(o, null, null, a, "#000000", "#ffffff", !0);
        const s = t.getContext();
        s.font = a;
        const l = s.measureText(o).width;
        r.set(n, l)
    }
    return t.dispose(),
    r
}
;
var EMeshType = (i=>(i.XAvatar = "XAvatar",
i.XStaticMesh = "XStaticMesh",
i.XBreathPoint = "breathpoint",
i.Decal = "decal",
i.Cgplane = "cgplane",
i.Tv = "tv",
i.XSubSequence = "XSubSequence",
i.XBillboard = "XBillboard",
i))(EMeshType || {});
const log$I = new Logger$1("Billboard");
var BillboardStatus = (i=>(i[i.SHOW = 1] = "SHOW",
i[i.HIDE = 0] = "HIDE",
i[i.DISPOSE = -1] = "DISPOSE",
i))(BillboardStatus || {});
class XBillboard {
    constructor(e, t=!1, r=!1) {
        E(this, "_mesh", null);
        E(this, "_texture", null);
        E(this, "_scalingFactor", 1);
        E(this, "offsets", null);
        E(this, "_pickable");
        E(this, "_background", null);
        E(this, "_billboardManager");
        E(this, "poolobj", null);
        E(this, "_usePool");
        E(this, "_initMeshScale", new Vector3(1,1,1));
        E(this, "_status", -1);
        E(this, "_stageChanged", !1);
        E(this, "DEFAULT_CONFIGS", {});
        this._billboardManager = e,
        this._pickable = t,
        this._usePool = r
    }
    set scalingFactor(e) {
        this._scalingFactor = e
    }
    set background(e) {
        this._background = e
    }
    get size() {
        return -1
    }
    setStatus(e) {
        e != this._status && (this._stageChanged = !0,
        this._status = e)
    }
    get status() {
        return this._status
    }
    get stageChanged() {
        return this._stageChanged
    }
    set stageChanged(e) {
        this._stageChanged = e
    }
    init(e="", t=.001, r=.001, n=!1) {
        const o = this._billboardManager.sceneManager.Scene;
        if (this._usePool) {
            const a = this._billboardManager.billboardPool.getFree(o, t, r, n);
            this._mesh = a.data,
            this._mesh.isPickable = this._pickable,
            this._mesh.xid = e,
            this._mesh.xtype = EMeshType.XBillboard,
            this._texture = this._mesh.material.diffuseTexture,
            this.poolobj = a
        } else
            this._mesh = this._billboardManager.createBillboardAsset(o, n);
        this._mesh.isPickable = this._pickable,
        this._initMeshScale.x = t * 1e3,
        this._initMeshScale.y = r * 1e3,
        this._mesh.xid = e,
        this._mesh.xtype = EMeshType.XBillboard,
        this._texture = this._mesh.material.diffuseTexture,
        this.setStatus(1),
        this._stageChanged = !0
    }
    dispose() {
        this._usePool ? this.poolobj && (this._billboardManager.billboardPool.release(this.poolobj),
        this._mesh = null,
        this._texture = null,
        this.poolobj = null) : this._mesh && (this._mesh.dispose(!0, !0),
        this._mesh = null,
        this._texture = null),
        this._background = null
    }
    getMesh() {
        return this._mesh
    }
    updateImage(e) {
        return new Promise(t=>{
            if (this._texture == null) {
                log$I.error("[Engine]Billboard texture not found");
                return
            }
            const r = this._mesh
              , n = this._texture
              , o = this._scalingFactor
              , a = this._initMeshScale.x
              , s = this._initMeshScale.y
              , l = this._texture.getContext()
              , u = this._texture.getSize();
            l.clearRect(0, 0, u.width, u.height);
            const c = new Image;
            c.crossOrigin = "anonymous",
            c.src = e,
            c.onload = ()=>{
                const h = c.width * o
                  , f = c.height * o;
                r.scaling.x = h * a,
                r.scaling.y = f * s,
                n.scaleTo(h, f),
                l.drawImage(c, 0, 0, h, f),
                n.hasAlpha = !0,
                n.update(),
                t()
            }
        }
        )
    }
    show() {
        this._mesh && (this._mesh.setEnabled(!0),
        this._mesh.isPickable = this._pickable)
    }
    hide() {
        this._mesh && (this._mesh.setEnabled(!1),
        this._mesh.isPickable = !1)
    }
    setId(e) {
        this._mesh && (this._mesh.xid = e)
    }
    setPosition(e) {
        if (e && this._mesh) {
            const t = ue4Position2Xverse(e);
            this._mesh.position = t
        }
    }
    updateText(e, t, r=!0, n=[], o=30, a="monospace", s="black", l="bold", u) {
        if (this._texture == null) {
            log$I.error("[Engine]Billboard texture not found");
            return
        }
        const c = this._texture
          , h = this._mesh
          , f = this._scalingFactor
          , d = this._initMeshScale.x
          , _ = this._initMeshScale.y;
        if (e != "") {
            const g = this._texture.getContext()
              , m = this._texture.getSize();
            g.clearRect(0, 0, m.width, m.height);
            const v = new Image;
            if (r) {
                t != null ? t ? this._background = this._billboardManager.userBackGroundBlob : this._background = this._billboardManager.npcBackGroundBlob : this._background || (this._background = this._billboardManager.userBackGroundBlob);
                let y = e
                  , b = u && u < n.length - 1 ? u : n.length - 1;
                if (this._background) {
                    if (b > this._background.length) {
                        for (let T = 0; T < b - this._background.length; T++)
                            n.pop();
                        b = n.length - 1,
                        y = e.slice(0, n[b] - 1) + String.fromCharCode(8230)
                    }
                    v.crossOrigin = "anonymous",
                    v.src = this._background[b - 1],
                    v.onload = function() {
                        const T = v.width * f
                          , C = v.height * f;
                        h.scaling.x = T * d,
                        h.scaling.y = C * _,
                        c.scaleTo(T, C),
                        g.textAlign = "center",
                        g.textBaseline = "middle",
                        g.drawImage(v, 0, 0, T, C);
                        for (let A = 0; A < b; A++)
                            c.drawText(y.slice(n[0 + A], n[1 + A]), T / 2, C * (A + 1) / (b + 1) + (A - (b - 1) / 2) * f * 10, l + " " + o * f + "px " + a, s, "transparent", !0);
                        c.hasAlpha = !0
                    }
                }
            } else {
                const y = u && u < n.length - 1 ? u : n.length - 1
                  , b = 480 * f
                  , T = 60 * f * y;
                this._mesh.scaling = new Vector3(b * d,T * _,1),
                c.scaleTo(b, T);
                const C = c.getContext();
                C.textAlign = "center",
                C.textBaseline = "middle";
                for (let A = 0; A < y; A++)
                    c.drawText(e.slice(n[0 + A], n[1 + A]), b / 2 + 2 * f, T * (A + 1) / (y + 1) + (A - (y - 1) / 2) * f * 10 + 2 * f, l + " " + o * f + "px " + a, "#333333", "transparent", !0),
                    c.drawText(e.slice(n[0 + A], n[1 + A]), b / 2, T * (A + 1) / (y + 1) + (A - (y - 1) / 2) * f * 10, l + " " + o * f + "px " + a, s, "transparent", !0);
                c.hasAlpha = !0
            }
        } else
            this.clearText()
    }
    drawBillboard(e, t, r) {
        var m;
        const {imageList: n} = e
          , {texts: o, font: a="monospace", fontsize: s=40, fontcolor: l="#ffffff", fontstyle: u="", linesize: c=20, linelimit: h} = t
          , {position: f, offsets: d, scale: _, compensationZ: g=0} = r;
        if (this.scalingFactor = _ || 1,
        d && (this.offsets = {
            x: d.x * this._scalingFactor,
            y: d.y * this._scalingFactor,
            z: d.z * this._scalingFactor
        }),
        this.offsets || (this.offsets = {
            x: 0,
            y: 0,
            z: 0
        }),
        this.setPosition(f),
        n && !o)
            (m = this._billboardManager.sceneManager) == null || m.urlTransformer(n[0]).then(v=>{
                this.updateImage(v)
            }
            );
        else if (o && !n) {
            const [v,y] = getStringBoundaries(o, c, XBillboardManager.alphaWidthMap);
            this.offsets.z += this._scalingFactor * g * (y.length - 1),
            this.updateText(v, void 0, !1, y, s, a, l, u, h)
        } else if (o && n) {
            this.background = n;
            const [v,y] = getStringBoundaries(o, c, XBillboardManager.alphaWidthMap);
            this.offsets.z += this._scalingFactor * g * (y.length - 1),
            this.updateText(v, void 0, !0, y, s, a, l, u, h)
        }
        this.setStatus(1)
    }
    clearText() {
        if (this._texture != null) {
            const e = this._texture.getContext()
              , t = this._texture.getSize();
            e.clearRect(0, 0, t.width, t.height),
            this._texture.update()
        }
    }
}
const log$H = new Logger$1("XAvatarComopnent");
class XAvatarComopnent {
    constructor() {
        E(this, "resourceIdList", []);
        E(this, "skeleton");
        E(this, "extraProp");
        E(this, "extras", []);
        E(this, "body")
    }
    addBodyComp(e, t) {
        return !e.rootNode || t.root.getChildMeshes().length === 0 ? (t.isRender = !1,
        !1) : (this.body = t,
        this.body.root.parent = e.rootNode,
        t.isRender = !0,
        this.body.root.getChildMeshes()[0] && (this.body.root.getChildMeshes()[0].xtype = EMeshType.XAvatar,
        this.body.root.getChildMeshes()[0].xid = e.id),
        this.skeleton = t.skeleton,
        !0)
    }
    addClothesComp(e, t) {
        return !e.rootNode || !this.skeleton || !t.root ? (t.isRender = !1,
        !1) : (t.root.xtype = EMeshType.XAvatar,
        t.root.xid = e.id,
        t.isRender = !0,
        t.root.parent = e.rootNode.getChildMeshes()[0],
        this.resourceIdList.push(t),
        t.root.skeleton = this.skeleton,
        t.root.getChildMeshes().forEach(r=>{
            r.skeleton = this.skeleton
        }
        ),
        !0)
    }
    clearClothesComp(e) {
        e.root.getChildMeshes().forEach(t=>{
            t.skeleton = null,
            t.dispose(),
            t.xid = void 0
        }
        ),
        e.root.dispose(),
        this.resourceIdList = this.resourceIdList.filter(t=>t.uId != e.uId)
    }
    clearAllClothesComps() {
        this.resourceIdList.forEach(e=>{
            var t;
            e.root.parent = null,
            e.root._parentContainer.xReferenceCount && (e.root._parentContainer.xReferenceCount--,
            e.root._parentContainer = null),
            e.isRender = !1,
            e.isSelected = !1,
            e.root.getChildMeshes().forEach(r=>{
                r.skeleton = null,
                r.dispose()
            }
            ),
            (t = e.root.skeleton) == null || t.dispose(),
            e.root.dispose()
        }
        ),
        this.resourceIdList = []
    }
    dispose(e) {
        this.body ? (this.body.root._parentContainer.xReferenceCount && (this.body.root._parentContainer.xReferenceCount--,
        this.body.root._parentContainer = null),
        this.clearAllClothesComps(),
        this.body.isRender = !1,
        this.body.skeleton.dispose(),
        this.body.skeleton = null,
        this.body.root.dispose(),
        this.body = void 0,
        this.skeleton && (this.skeleton.dispose(),
        this.skeleton = void 0)) : log$H.warn("[Engine] no body to dispose")
    }
    changeClothesComp(e, t, r, n, o) {
        return new Promise(a=>{
            if (r === "pendant" || this.resourceIdList.some(s=>s.name === t))
                return a();
            if (e.isHide || !e.isRender)
                o.concat(r).forEach(l=>{
                    e.clothesList = e.clothesList.filter(c=>c.type != l);
                    const u = {
                        type: r,
                        id: t,
                        url: n,
                        lod: 0
                    };
                    e.clothesList.push(u)
                }
                ),
                a();
            else {
                const s = o.concat(r);
                e.avatarManager.loadDecoration(r, t, 0).then(l=>{
                    if (l) {
                        e.attachDecoration(l);
                        const u = {
                            type: r,
                            id: t,
                            url: n
                        };
                        e.clothesList.push(u),
                        l.root.setEnabled(!0),
                        s.forEach(c=>{
                            const h = this.resourceIdList.filter(f=>f.type === c);
                            if (h.length > 1) {
                                const f = h.filter(d=>d.name === t);
                                if (f.length > 1)
                                    for (let d = 1; d < f.length; ++d) {
                                        e.detachDecoration(f[d]),
                                        e.clothesList = e.clothesList.filter(g=>g.id != f[d].name);
                                        const _ = {
                                            type: r,
                                            id: t,
                                            url: n
                                        };
                                        e.clothesList.push(_)
                                    }
                            }
                            h[0] && h[0].name != t && this._readyToDetach(e, r) && (e.detachDecoration(h[0]),
                            e.clothesList = e.clothesList.filter(f=>f.id != h[0].name))
                        }
                        )
                    }
                    return a()
                }
                )
            }
        }
        )
    }
    _readyToDetach(e, t) {
        return !((t == "clothes" || t == "pants") && e.clothesList.filter(n=>n.type === "suit").length == 1 && (!e.clothesList.some(n=>n.type === "pants") || !e.clothesList.some(n=>n.type === "clothes")))
    }
    addDecoComp(e, t, r, n, o) {
        if (e.isRender) {
            const a = e.avatarManager.extraComps.get(t)
              , s = a == null ? void 0 : a.clone(t, void 0);
            if (!a) {
                log$H.error("\u6CA1\u6709\u5BF9\u5E94\u7684\u7EC4\u4EF6");
                return
            }
            this.extras.push(s);
            const l = this.skeleton.bones.find(u=>u.name === r);
            s.position = n,
            s.rotation = o,
            s.attachToBone(l, e.rootNode.getChildMeshes()[0])
        }
    }
    showExtra(e) {
        this.extras.forEach(t=>{
            t.name.indexOf(e) > 0 && t.setEnabled(!0)
        }
        )
    }
    hideExtra(e) {
        this.extras.forEach(t=>{
            t.name.indexOf(e) > 0 && t.setEnabled(!1)
        }
        )
    }
    disposeExtra() {
        this.extras.forEach(e=>{
            e.dispose()
        }
        ),
        this.extras = []
    }
}
const log$G = new Logger$1("XStateMachine");
class XStateMachine {
    constructor(e) {
        E(this, "state");
        E(this, "isMoving");
        E(this, "isRotating");
        E(this, "_observer");
        E(this, "_movingObserver");
        E(this, "_scene");
        this._scene = e
    }
    rotateTo(e, t, r, n) {
        return new Promise((o,a)=>{
            var h;
            const s = e.avatarManager.scene;
            if (r && e.setRotation(r),
            t == r)
                return o();
            e.priority === 0 && log$G.info(`avatar ${e.id} starts to rotate from ${r} to ${t}`);
            let l = 0;
            const u = 1e3 / 25
              , c = calcDistance3DAngle(t, e.rotation) / u;
            this._movingObserver && s.onBeforeRenderObservable.remove(this._movingObserver),
            (h = e.controller) == null || h.playAnimation(n || "Walking", !0),
            this._movingObserver = s == null ? void 0 : s.onBeforeRenderObservable.add(()=>{
                var f;
                if (l < 1) {
                    if (!e.rootNode)
                        return e.setRotation(t),
                        o();
                    const d = Vector3.Lerp(e.rootNode.rotation, ue4Rotation2Xverse(t), l);
                    e.setRotation(xverseRotation2Ue4(d)),
                    l += u / (c * 1e3)
                } else
                    return s.onBeforeRenderObservable.remove(this._movingObserver),
                    (f = e.controller) == null || f.playAnimation("Idle", !0),
                    o()
            }
            )
        }
        )
    }
    _filterPathPoint(e) {
        let t = 0;
        const r = 1e-4;
        if (e.length <= 1)
            return [];
        for (; t < e.length - 1; )
            calcDistance3D(e[t], e[t + 1]) < r ? e.splice(t, 1) : t++;
        return e
    }
    moveTo(e, t, r, n, o, a) {
        return new Promise((s,l)=>{
            var m;
            const u = e.avatarManager.scene;
            e.priority === 0 && log$G.info(`avatar ${e.id} starts to move from ${t} to ${r}`);
            let c = 0;
            a ? a = a.concat(r) : a = [r],
            a = this._filterPathPoint(a);
            let h = t
              , f = a.shift();
            if (!f)
                return l("[Engine input path error]");
            let d = calcDistance3D(h, f) / n;
            const _ = 1e3 / 25;
            e.rootNode.lookAt(ue4Position2Xverse(f));
            const g = xverseRotation2Ue4({
                x: e.rootNode.rotation.x,
                y: e.rootNode.rotation.y,
                z: e.rootNode.rotation.z
            });
            g && (g.roll = 0,
            g.pitch = 0,
            e.setRotation(g)),
            this._movingObserver && u.onBeforeRenderObservable.remove(this._movingObserver),
            (m = e.controller) == null || m.playAnimation(o, !0),
            this._movingObserver = u == null ? void 0 : u.onBeforeRenderObservable.add(()=>{
                var v;
                if (c < 1) {
                    const y = Vector3.Lerp(ue4Position2Xverse(h), ue4Position2Xverse(f), c);
                    if (e.setPosition(xversePosition2Ue4(y)),
                    !e.rootNode)
                        return e.setPosition(r),
                        s();
                    c += _ / (d * 1e3)
                } else if (h = f,
                f = a.shift(),
                f) {
                    d = calcDistance3D(h, f) / n,
                    e.rootNode.lookAt(ue4Position2Xverse(f));
                    const y = xverseRotation2Ue4({
                        x: e.rootNode.rotation.x,
                        y: e.rootNode.rotation.y,
                        z: e.rootNode.rotation.z
                    });
                    y && (y.roll = 0,
                    y.pitch = 0,
                    e.setRotation(y)),
                    c = 0
                } else
                    return u.onBeforeRenderObservable.remove(this._movingObserver),
                    (v = e.controller) == null || v.playAnimation("Idle", !0),
                    s()
            }
            )
        }
        )
    }
    lookAt(e, t, r) {
        return new Promise(n=>{
            var _, g;
            const o = ue4Position2Xverse(t)
              , s = e.rootNode.position.subtract(o).length()
              , l = new Vector3(s * Math.sin(e.rootNode.rotation.y),0,s * Math.cos(e.rootNode.rotation.y))
              , u = (_ = e.rootNode) == null ? void 0 : _.position.add(l);
            let c = 0;
            const h = r || 1 / 100
              , f = (g = e.rootNode) == null ? void 0 : g.getScene()
              , d = f == null ? void 0 : f.onBeforeRenderObservable.add(()=>{
                var y, b;
                const m = (y = e.controller) == null ? void 0 : y.animations.find(T=>T.name == "Idle");
                (m == null ? void 0 : m.isPlaying) != !0 && (m == null || m.play());
                const v = Vector3.Lerp(u, o, c);
                c < 1 ? ((b = e.rootNode) == null || b.lookAt(v),
                c += h) : (d && f.onBeforeRenderObservable.remove(d),
                n())
            }
            )
        }
        )
    }
    sendObjectTo(e, t, r, n=2, o=10, a={
        x: 0,
        y: 0,
        z: 150
    }) {
        return new Promise((s,l)=>{
            var u;
            if (!r.loaded)
                l("Gift has not inited!");
            else {
                const c = (u = e.rootNode) == null ? void 0 : u.getScene();
                let h = 0;
                const f = 1 / (n * 25)
                  , d = f
                  , _ = o / 100
                  , g = 8 * _ * f * f;
                let m = .5 * g / f
                  , v = ue4Position2Xverse(e.position);
                const y = ue4Position2Xverse(a)
                  , b = ue4Position2Xverse(e.position)
                  , T = c == null ? void 0 : c.onBeforeRenderObservable.add(()=>{
                    (!t || !e.position || !t.position) && (T && c.onBeforeRenderObservable.remove(T),
                    l("Invalid receiver when shoot gift!")),
                    r.loaded || (T && c.onBeforeRenderObservable.remove(T),
                    s());
                    const C = ue4Position2Xverse(t.position)
                      , A = new Vector3((C.x - b.x) * f,m,(C.z - b.z) * f);
                    m = m - g,
                    h < 1 ? (v = v.add(A),
                    r.setPositionVector(v.add(y)),
                    h += d) : (s(),
                    T && c.onBeforeRenderObservable.remove(T))
                }
                )
            }
        }
        )
    }
    roll(e, t, r, n) {
        var o, a;
        this._observer && ((o = this._scene) == null || o.onBeforeRenderObservable.remove(this._observer)),
        t && (r = r != null ? r : 1,
        n = n != null ? n : 1,
        this._observer = (a = this._scene) == null ? void 0 : a.onBeforeRenderObservable.add(()=>{
            e.rootNode.rotation.y += r * .1 * n,
            e.rootNode.rotation.y %= Math.PI * 2
        }
        ))
    }
    disposeObsever() {
        this._movingObserver && this._scene.onBeforeRenderObservable.remove(this._movingObserver)
    }
}
class PoolObject {
    constructor(e, t, r, n=!0) {
        E(this, "data");
        E(this, "nextFree");
        E(this, "previousFree");
        E(this, "free");
        this.data = e,
        this.nextFree = t,
        this.previousFree = r,
        this.free = n
    }
    dispose() {
        this.data && this.data instanceof Mesh && this.data.dispose(!0, !0),
        this.previousFree = null,
        this.nextFree = null,
        this.data = null
    }
}
class Pool {
    constructor(e, t, r, n, ...o) {
        E(this, "objCreator");
        E(this, "objReseter");
        E(this, "_pool");
        E(this, "lastFree");
        E(this, "nextFree");
        E(this, "capacity");
        this._pool = [],
        this.objCreator = e,
        this.objReseter = t;
        for (let a = 0; a < n; a++)
            this.addNewObject(this.newPoolObject(...o));
        this.capacity = r
    }
    addNewObject(e) {
        return this._pool.push(e),
        this.release(e),
        e
    }
    release(e) {
        e.free = !0,
        e.nextFree = null,
        e.previousFree = this.lastFree,
        this.lastFree ? this.lastFree.nextFree = e : this.nextFree = e,
        this.lastFree = e,
        this.objReseter(e)
    }
    getFree(...e) {
        const t = this.nextFree ? this.nextFree : this.addNewObject(this.newPoolObject(...e));
        return t.free = !1,
        this.nextFree = t.nextFree,
        this.nextFree || (this.lastFree = null),
        t
    }
    newPoolObject(...e) {
        const t = this.objCreator(...e);
        return new PoolObject(t,this.nextFree,this.lastFree)
    }
    releaseAll() {
        this._pool.forEach(e=>this.release(e))
    }
    clean(e=0, ...t) {
        let r = this.nextFree;
        if (!r)
            return;
        let n = 0;
        for (; r; )
            n += 1,
            r = r.nextFree;
        let o = !1;
        if (n > e && this._pool.length > this.capacity && (o = !0),
        o)
            for (r = this.nextFree; r; ) {
                r.free = !1,
                this.nextFree = r.nextFree;
                const a = this._pool.indexOf(r);
                this._pool.splice(a, 1),
                this.nextFree || (this.lastFree = null),
                r == null || r.dispose(),
                r = this.nextFree
            }
    }
}
const texRootDir = "https://app-asset-1258211750.file.myqcloud.com/1/textures/"
  , ge = class {
    constructor(e) {
        E(this, "billboardMap", new Map);
        E(this, "sceneManager");
        E(this, "billboardPool");
        E(this, "userBackGroundBlob", new Array);
        E(this, "npcBackGroundBlob", new Array);
        E(this, "tickObserver");
        E(this, "tickInterval");
        E(this, "_updateLoopObserver");
        this.sceneManager = e,
        this.billboardPool = new Pool(this.createBillboardAsset,this.resetBillboardAsset,0,60,this.sceneManager.Scene,!1),
        this.tickInterval = 250;
        let t = 0;
        this.tickObserver = this.sceneManager.Scene.onAfterRenderObservable.add(()=>{
            t += 1,
            t == this.tickInterval && (this.tick(),
            t = 0)
        }
        ),
        this.launchBillboardStatusLoop()
    }
    tick() {
        this.billboardPool.clean(0, this.sceneManager.Scene, !1)
    }
    createBillboardAsset(e, t=!1) {
        const r = MeshBuilder.CreatePlane("billboard-", {
            height: .001,
            width: .001,
            sideOrientation: Mesh.DOUBLESIDE
        }, e);
        r.isPickable = !0,
        r.setEnabled(!1);
        const n = new DynamicTexture("billboard-tex-",{
            width: .001 + 1,
            height: .001 + 1
        },e,t,Texture.BILINEAR_SAMPLINGMODE);
        n.hasAlpha = !0;
        const o = new StandardMaterial("billboard-mat-",e);
        return o.diffuseTexture = n,
        o.emissiveColor = new Color3(.95,.95,.95),
        o.useAlphaFromDiffuseTexture = !0,
        r.material = o,
        r.billboardMode = Mesh.BILLBOARDMODE_Y,
        r.position.y = 0,
        r
    }
    resetBillboardAsset(e) {
        const t = e.data;
        return t.setEnabled(!1),
        t.isPickable = !1,
        e
    }
    async loadBackGroundTexToIDB() {
        ge.userBubbleUrls.forEach(r=>{
            this.sceneManager.urlTransformer(r).then(n=>{
                this.userBackGroundBlob.push(n)
            }
            )
        }
        ),
        ge.npcBubbleUrls.forEach(r=>{
            this.sceneManager.urlTransformer(r).then(n=>{
                this.npcBackGroundBlob.push(n)
            }
            )
        }
        )
    }
    addBillboardToMap(e, t) {
        this.billboardMap.set(e, t)
    }
    addBillboard(e, t, r) {
        let n = this.getBillboard(e);
        return n || (n = new XBillboard(this,t,r),
        this.addBillboardToMap(e, n)),
        n
    }
    generateStaticBillboard(e, {id: t="billboard", isUser: r, background: n, font: o="Arial", fontsize: a=40, fontcolor: s="#ffffff", fontstyle: l="600", linesize: u=16, linelimit: c, scale: h=1, width: f=.01, height: d=.01, position: _={
        x: 0,
        y: 0,
        z: 0
    }}) {
        const g = this.addBillboard(t, !1, !0);
        g.getMesh() == null && g.init(t, f, d);
        let m;
        r != null && (m = r ? ge.userBubbleUrls : ge.npcBubbleUrls),
        g && g.getMesh() && (g.DEFAULT_CONFIGS = {
            id: t,
            isUser: r,
            background: n,
            font: o,
            fontsize: a,
            fontcolor: s,
            fontstyle: l,
            linesize: u,
            linelimit: c,
            scale: h,
            width: f,
            height: d,
            position: _
        },
        g.drawBillboard({
            imageList: n || m
        }, {
            texts: e,
            font: o,
            fontsize: a,
            fontcolor: s,
            fontstyle: l,
            linesize: u,
            linelimit: c
        }, {
            position: _,
            scale: h
        }),
        t && g.setId(t),
        g.setStatus(BillboardStatus.SHOW))
    }
    getBillboard(e) {
        return this.billboardMap.get(e)
    }
    toggle(e, t) {
        var r;
        (r = this.getBillboard(e)) == null || r.setStatus(t ? BillboardStatus.SHOW : BillboardStatus.HIDE)
    }
    removeBillboard(e) {
        const t = this.getBillboard(e);
        t && (t.setStatus(BillboardStatus.DISPOSE),
        this.billboardMap.delete(e))
    }
    launchBillboardStatusLoop() {
        this._updateLoopObserver = this.sceneManager.Scene.onBeforeRenderObservable.add(()=>{
            this.billboardMap.size <= 0 || this.billboardMap.forEach(e=>{
                e.stageChanged && (e.status == BillboardStatus.SHOW ? e.show() : e.status == BillboardStatus.HIDE ? e.hide() : (e.hide(),
                e.dispose()),
                e.stageChanged = !1)
            }
            )
        }
        )
    }
}
;
let XBillboardManager = ge;
E(XBillboardManager, "alphaWidthMap", new Map),
E(XBillboardManager, "userBubbleUrls", [texRootDir + "bubble01.png", texRootDir + "bubble02.png", texRootDir + "bubble03.png"]),
E(XBillboardManager, "npcBubbleUrls", [texRootDir + "bubble01_npc.png", texRootDir + "bubble02_npc.png", texRootDir + "bubble03_npc.png"]);
const log$F = new Logger$1("XAvatarBillboardComponent");
class XAvatarBillboardComponent {
    constructor(e) {
        E(this, "_nickName", "");
        E(this, "_words", "");
        E(this, "_isNameVisible", !0);
        E(this, "_isBubbleVisible", !0);
        E(this, "_isGiftButtonsVisible", !1);
        E(this, "withinVisualRange", !1);
        E(this, "_bubble");
        E(this, "_nameBoard");
        E(this, "_giftButtons", new Map);
        E(this, "_buttonTex", new Map);
        E(this, "_nameLinesLimit", 2);
        E(this, "_nameLengthPerLine", 16);
        E(this, "_scene");
        E(this, "_pickBbox", null);
        E(this, "bbox");
        E(this, "_height", .26);
        E(this, "_attachmentObservers", new Map);
        E(this, "attachToAvatar", (e,t,r=!1,n={
            x: 0,
            y: 0,
            z: 0
        },o=!1,a,s)=>{
            const l = e.rootNode;
            if (this.bbox || e.getBbox(),
            t && l) {
                const u = a || t.uniqueId;
                let c = this._attachmentObservers.get(u);
                if (c)
                    if (o)
                        this._scene.onBeforeRenderObservable.remove(c),
                        this._attachmentObservers.delete(u);
                    else
                        return;
                const h = ue4Position2Xverse(n);
                r ? (t.setParent(l),
                t.position = h) : (c = this._scene.onBeforeRenderObservable.add(()=>{
                    let f = 0;
                    s ? (f = e.rootNode.rotation.y / Math.PI * 180 + 90,
                    e.rootNode.rotation.y && (t.rotation.y = e.rootNode.rotation.y)) : f = e.avatarManager.sceneManager.cameraComponent.getCameraPose().rotation.yaw,
                    f || (f = 0);
                    const d = new Vector3(0,this._height,0);
                    e.controller && e.controller.activeAnimation() && e.controller.activeAnimation().animatables[0] && (this._height = d.y = (e.controller.activeAnimation().animatables[0].target.position.y * .01 - .66) * e.scale),
                    d.y < .07 * e.scale && (d.y = 0),
                    t.position.x = l.position.x + h.x * Math.sin(f * Math.PI / 180) + h.z * Math.cos(f * Math.PI / 180),
                    t.position.z = l.position.z + h.x * Math.cos(f * Math.PI / 180) - h.z * Math.sin(f * Math.PI / 180),
                    t.position.y = l.position.y + this.bbox.maximum.y + h.y + d.y
                }
                ),
                this._attachmentObservers.set(u, c))
            } else
                log$F.error("avatar or attachment not found!")
        }
        );
        E(this, "detachFromAvatar", (e,t,r=!1)=>{
            const n = this._attachmentObservers.get(t.uniqueId);
            n && this._scene.onBeforeRenderObservable.remove(n),
            e.rootNode ? (t.setEnabled(!1),
            t.parent = null,
            r && t.dispose()) : log$F.error("avatar not found!")
        }
        );
        E(this, "getBbox", (e,t={})=>{
            const {isConst: r=!1, changeWithAvatar: n=!1} = t;
            let {localCenter: o={
                x: 0,
                y: 0,
                z: 75
            }, width: a=1.32, height: s=1.5, depth: l=.44} = t;
            if (n) {
                const u = e.scale;
                o = {
                    x: o.x * u,
                    y: o.y * u,
                    z: o.z * u
                },
                a *= u,
                s *= u,
                l *= u
            }
            if (e.rootNode) {
                let u = new Vector3(0,0,0)
                  , c = new Vector3(0,0,0);
                if (r) {
                    const f = ue4Position2Xverse(o);
                    u = u.add(f.add(new Vector3(-a / 2,-s / 2,-l / 2))),
                    c = c.add(f.add(new Vector3(a / 2,s / 2,l / 2)))
                } else if (u = u.add(new Vector3(Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY)),
                c = c.add(new Vector3(Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY)),
                e.isRender) {
                    e.rootNode.getChildMeshes().forEach(_=>{
                        const g = _.getBoundingInfo().boundingBox.minimum
                          , m = _.getBoundingInfo().boundingBox.maximum;
                        u.x = Math.min(u.x, g.x),
                        c.x = Math.max(c.x, m.x),
                        u.y = Math.min(u.y, g.y),
                        c.y = Math.max(c.y, m.y),
                        u.z = Math.min(u.z, g.z),
                        c.z = Math.max(c.z, m.z)
                    }
                    );
                    const f = c.x - u.x
                      , d = c.z - u.z;
                    u.x -= e.scale * f / 2,
                    c.x += e.scale * f / 2,
                    c.y *= e.scale,
                    u.z -= e.scale * d / 2,
                    c.z += e.scale * d / 2
                } else {
                    const f = e.avatarManager.getMainAvatar();
                    f && f.bbComponent.bbox && (u.x = f.bbComponent.bbox.minimum.x,
                    c.x = f.bbComponent.bbox.maximum.x,
                    u.y = f.bbComponent.bbox.minimum.y,
                    c.y = f.bbComponent.bbox.maximum.y,
                    u.z = f.bbComponent.bbox.minimum.z,
                    c.z = f.bbComponent.bbox.maximum.z)
                }
                const h = e.rootNode.computeWorldMatrix(!0);
                if (this.bbox ? this.bbox.reConstruct(u, c, h) : this.bbox = new BoundingBox(u,c,h),
                this._pickBbox == null) {
                    const f = this.createPickBoundingbox(e, this.bbox);
                    this.attachToAvatar(e, f.data, !1, {
                        x: 0,
                        y: 0,
                        z: 0
                    }, !1, "pickbox"),
                    this._pickBbox = f
                }
            } else
                log$F.error("avatar not found!")
        }
        );
        this._scene = e
    }
    get isNameVisible() {
        return this._isNameVisible
    }
    get isBubbleVisible() {
        return this._isBubbleVisible
    }
    get isGiftButtonsVisible() {
        return this._isGiftButtonsVisible
    }
    get words() {
        return this._words
    }
    get nickName() {
        return this._nickName
    }
    get giftButtons() {
        return this._giftButtons
    }
    get bubble() {
        return this._bubble
    }
    get nameBoard() {
        return this._nameBoard
    }
    setNicknameStatus(e) {
        if (this.nameBoard && this.nameBoard.setStatus(e),
        e == BillboardStatus.DISPOSE) {
            const t = this._attachmentObservers.get("nickname");
            t && (this._scene.onBeforeRenderObservable.remove(t),
            this._attachmentObservers.delete("nickname"))
        }
    }
    setBubbleStatus(e) {
        if (this.bubble && this.bubble.setStatus(e),
        e == BillboardStatus.DISPOSE) {
            const t = this._attachmentObservers.get("bubble");
            t && (this._scene.onBeforeRenderObservable.remove(t),
            this._attachmentObservers.delete("bubble"))
        }
    }
    setButtonsStatus(e) {
        this.giftButtons && this.giftButtons.size != 0 && this.giftButtons.forEach(t=>{
            if (t.setStatus(e),
            e == BillboardStatus.DISPOSE && t.getMesh()) {
                const r = "button_" + t.getMesh().xid
                  , n = this._attachmentObservers.get(r);
                n && (this._scene.onBeforeRenderObservable.remove(n),
                this._attachmentObservers.delete(r))
            }
        }
        )
    }
    setGiftButtonsVisible(e) {
        this.setButtonsStatus(e ? BillboardStatus.SHOW : BillboardStatus.DISPOSE)
    }
    dispose(e) {
        this._attachmentObservers.forEach(t=>{
            this._scene.onBeforeRenderObservable.remove(t)
        }
        ),
        this._attachmentObservers.clear(),
        this.updateBillboardStatus(e, BillboardStatus.DISPOSE),
        this._buttonTex.clear(),
        this._pickBbox && (e.avatarManager.bboxMeshPool.release(this._pickBbox),
        this._pickBbox = null)
    }
    updateBillboardStatus(e, t) {
        this.bbox || e.getBbox(),
        e.isRender ? (e.setBubbleStatus(t),
        e.setButtonsStatus(t),
        e.setNicknameStatus(t)) : (e.setBubbleStatus(BillboardStatus.DISPOSE),
        e.setButtonsStatus(BillboardStatus.DISPOSE),
        e.enableNickname ? e.setNicknameStatus(t) : e.setNicknameStatus(BillboardStatus.DISPOSE))
    }
    disposeBillBoard(e) {
        this._attachmentObservers.forEach(t=>{
            this._scene.onBeforeRenderObservable.remove(t)
        }
        ),
        this._attachmentObservers.clear(),
        this.updateBillboardStatus(e, BillboardStatus.DISPOSE),
        this._buttonTex.clear(),
        this._pickBbox && (e.avatarManager.bboxMeshPool.release(this._pickBbox),
        this._pickBbox = null)
    }
    setPickBoxScale(e) {
        this._pickBbox && this._pickBbox.data && (this._pickBbox.data.scaling = new Vector3(e,e,e))
    }
    setIsPickable(e, t) {
        e.rootNode && e.rootNode.getChildMeshes().forEach(r=>{
            r.isPickable = t
        }
        ),
        this._pickBbox && this._pickBbox.data && (this._pickBbox.data.isPickable = t)
    }
    initNameboard(e, t=1) {
        this._nameBoard == null && (this._nameBoard = e.avatarManager.sceneManager.billboardComponent.addBillboard("name-" + e.id, !1, !0)),
        this._nameBoard.init("nickname", t / 300, t / 300)
    }
    initBubble(e, t=1) {
        this._bubble == null && (this._bubble = e.avatarManager.sceneManager.billboardComponent.addBillboard("bubble-" + e.id, !1, !0)),
        e.isRender && this._bubble.init("bubble", t / 250, t / 250)
    }
    say(e, t=this._words, {id: r, isUser: n, background: o, font: a="Arial", fontsize: s=38, fontcolor: l="#ffffff", fontstyle: u="bold", linesize: c=22, linelimit: h, offsets: f={
        x: 0,
        y: 0,
        z: 40
    }, scale: d, compensationZ: _=11.2, reregistAnyway: g=!0}) {
        (!this.bubble || this.bubble.getMesh() == null) && e.initBubble(),
        this._words = t;
        let m;
        n != null && (m = n ? XBillboardManager.userBubbleUrls : XBillboardManager.npcBubbleUrls),
        this._bubble && (this._bubble.DEFAULT_CONFIGS = {
            id: r,
            isUser: n,
            background: o || m,
            font: a,
            fontsize: s,
            fontcolor: l,
            fontstyle: u,
            linesize: c,
            linelimit: h,
            offsets: f,
            scale: d,
            compensationZ: _,
            reregistAnyway: g
        },
        this._bubble.getMesh() && (this._bubble.drawBillboard({
            imageList: o || m
        }, {
            texts: this._words,
            font: a,
            fontsize: s,
            fontcolor: l,
            fontstyle: u,
            linesize: c
        }, {
            offsets: f,
            scale: d,
            compensationZ: _
        }),
        this.attachToAvatar(e, this._bubble.getMesh(), !1, this._bubble.offsets, g, "bubble"),
        r && this._bubble.setId(r))),
        this.setButtonsStatus(BillboardStatus.DISPOSE)
    }
    silent() {
        this.setBubbleStatus(BillboardStatus.DISPOSE),
        this._words = ""
    }
    setNickName(e, t, {id: r, isUser: n, background: o, font: a="Arial", fontsize: s=40, fontcolor: l="#ffffff", fontstyle: u="bold", linesize: c=22, linelimit: h, offsets: f={
        x: 0,
        y: 0,
        z: 15
    }, scale: d, compensationZ: _=0, reregistAnyway: g=!1}) {
        this._nickName = t,
        (!this.nameBoard || this.nameBoard.getMesh() == null) && this.initNameboard(e),
        this._nameBoard && this._nameBoard.getMesh() && (this._nameBoard.DEFAULT_CONFIGS = {
            id: r,
            isUser: n,
            background: o,
            font: a,
            fontsize: s,
            fontcolor: l,
            fontstyle: u,
            linesize: c,
            linelimit: h,
            offsets: f,
            scale: d,
            compensationZ: _,
            reregistAnyway: g
        },
        this._nameBoard.drawBillboard({}, {
            texts: this._nickName,
            font: a,
            fontsize: s,
            fontcolor: l,
            fontstyle: u,
            linesize: c,
            linelimit: h
        }, {
            offsets: f,
            scale: d,
            compensationZ: 0
        }),
        this.attachToAvatar(e, this._nameBoard.getMesh(), !1, this._nameBoard.offsets, g, "nickname"),
        r && this._nameBoard.setId(r))
    }
    generateButtons(e, t=null, r, n=85) {
        if (t && (this._buttonTex = t,
        this.clearButtons()),
        this._buttonTex.size == 0)
            return;
        let o = (this._buttonTex.size - 1) / 2;
        this._buttonTex.forEach((a,s)=>{
            let l = this._giftButtons.get(s);
            l || (l = e.avatarManager.sceneManager.billboardComponent.addBillboard("button-" + s + e.id, !0, !1),
            l.init(s, r / 240, r / 240));
            const u = {
                x: r * o * 70,
                y: 0,
                z: r * (n - 20 * (o * o))
            };
            l.drawBillboard({
                imageList: [a]
            }, {}, {
                offsets: u,
                scale: r
            }),
            this.attachToAvatar(e, l.getMesh(), !1, l.offsets, !0, "button_" + s),
            this._giftButtons.set(s, l),
            o -= 1
        }
        ),
        this.setBubbleStatus(BillboardStatus.DISPOSE)
    }
    clearButtons() {
        this._giftButtons.forEach(e=>{
            e.dispose()
        }
        ),
        this._giftButtons.clear()
    }
    createPickBoundingbox(e, t) {
        const r = t.extendSize.x * 2
          , n = t.extendSize.y * 2
          , o = t.extendSize.z * 2
          , a = this._scene
          , s = Math.max(r, o)
          , l = e.avatarManager.bboxMeshPool.getFree(a, s, n, s)
          , u = l.data;
        return u && (u.position = t.centerWorld,
        u.setEnabled(!1),
        u.isPickable = !0,
        u.xtype = EMeshType.XAvatar,
        u.xid = e.id),
        l
    }
}
const log$E = new Logger$1("Avatar")
  , castRayOffsetY = .01
  , castRayTeleportationOffset = 10;
class XAvatar {
    constructor({id: e, avatarType: t, priority: r, avatarManager: n, assets: o, status: a}) {
        E(this, "id", "-1");
        E(this, "priority", 0);
        E(this, "isRender", !1);
        E(this, "distLevel", 0);
        E(this, "isInLoadingList", !1);
        E(this, "isHide", !1);
        E(this, "component");
        E(this, "controller");
        E(this, "stateMachine");
        E(this, "bbComponent");
        E(this, "_avatarType");
        E(this, "clothesList", []);
        E(this, "isSelected", !1);
        E(this, "pendingLod", !1);
        E(this, "_previousReceivedPosition", new Vector3(0,1e4,0));
        E(this, "_avatarPosition");
        E(this, "_avatarRotation");
        E(this, "_avatarScale");
        E(this, "rootNode");
        E(this, "distToCam", 1e11);
        E(this, "enableNickname", !0);
        E(this, "distance", 1e11);
        E(this, "isCulling", !1);
        E(this, "reslevel", 0);
        E(this, "isInLoadingQueue", !1);
        E(this, "_isRayCastEnable");
        E(this, "_scene");
        E(this, "_avatarManager");
        E(this, "_transparent", 0);
        E(this, "hide", ()=>(this.isHide = !0,
        this._hide(),
        !this.isRender));
        E(this, "_show", ()=>{
            var e;
            this.isHide || (this.setIsPickable(!0),
            this.priority == 0 && (this.rootNode.setEnabled(!0),
            this.isRender = !0,
            this.avatarManager._updateBillboardStatus(this, BillboardStatus.SHOW),
            (e = this.controller) == null || e.playAnimation(this.controller.onPlay, this.controller.loop)))
        }
        );
        E(this, "show", ()=>(this.isHide = !1,
        this._show(),
        !!this.isRender));
        E(this, "setAnimations", e=>{
            this.controller.animations = e
        }
        );
        E(this, "attachToAvatar", (e,t=!1,r={
            x: 0,
            y: 0,
            z: 0
        },n=!1,o,a)=>this.bbComponent.attachToAvatar(this, e, t, r, n, o, a));
        E(this, "detachFromAvatar", (e,t=!1)=>this.bbComponent.detachFromAvatar(this, e, t));
        E(this, "getBbox", (e={})=>this.bbComponent.getBbox(this, e));
        this.id = e,
        this._avatarManager = n,
        this._scene = this.avatarManager.scene,
        this.clothesList = o,
        this._avatarType = t,
        this.priority = r || 0,
        this.controller = new XAnimationController(this),
        this.component = new XAvatarComopnent,
        this.stateMachine = new XStateMachine(this._scene),
        this.bbComponent = new XAvatarBillboardComponent(this._scene),
        this.rootNode = new TransformNode(e,this._avatarManager.scene),
        this._avatarScale = a.avatarScale == null ? 1 : a.avatarScale,
        this._avatarRotation = a.avatarRotation == null ? {
            pitch: 0,
            yaw: 0,
            roll: 0
        } : a.avatarRotation,
        this._avatarPosition = a.avatarPosition == null ? {
            x: 0,
            y: 0,
            z: 0
        } : a.avatarPosition,
        this.setPosition(this._avatarPosition),
        this.setRotation(this._avatarRotation),
        this.setScale(this.scale),
        this._isRayCastEnable = avatarSetting.isRayCastEnable,
        this._scene.registerBeforeRender(()=>{
            this.tick()
        }
        )
    }
    tick() {
        this.cullingTick()
    }
    cullingTick() {
        var e;
        this.isCulling && ((e = this.rootNode) == null || e.getChildMeshes().forEach(t=>{
            this.distToCam < 50 ? t.visibility = 0 : t.visibility = this._transparent
        }
        ))
    }
    setTransParentThresh(e) {
        this._transparent = e
    }
    get isNameVisible() {
        return this.bbComponent.isNameVisible
    }
    get isBubbleVisible() {
        return this.bbComponent.isBubbleVisible
    }
    get isGiftButtonsVisible() {
        return this.bbComponent.isGiftButtonsVisible
    }
    get words() {
        return this.bbComponent.words
    }
    get nickName() {
        return this.bbComponent.nickName
    }
    get giftButtons() {
        return this.bbComponent.giftButtons
    }
    get bubble() {
        return this.bbComponent.bubble
    }
    get nameBoard() {
        return this.bbComponent.nameBoard
    }
    get avatarManager() {
        return this._avatarManager
    }
    set withinVisibleRange(e) {
        this.bbComponent.withinVisualRange = e
    }
    setNicknameStatus(e) {
        return this.bbComponent.setNicknameStatus(e)
    }
    setBubbleStatus(e) {
        return this.bbComponent.setBubbleStatus(e)
    }
    setButtonsStatus(e) {
        return this.bbComponent.setBubbleStatus(e)
    }
    setGiftButtonsVisible(e) {
        return this.bbComponent.setGiftButtonsVisible(e)
    }
    get avatarType() {
        return this._avatarType
    }
    attachBody(e) {
        return this.component.addBodyComp(this, e)
    }
    attachDecoration(e) {
        return this.component.addClothesComp(this, e)
    }
    detachDecoration(e) {
        return this.component.clearClothesComp(e)
    }
    detachDecorationAll() {
        return this.component.clearAllClothesComps()
    }
    get skeleton() {
        return this.component.skeleton
    }
    get position() {
        return this._avatarPosition
    }
    get rotation() {
        return this._avatarRotation
    }
    get scale() {
        return this._avatarScale
    }
    _hide_culling() {
        this.bbComponent.updateBillboardStatus(this, BillboardStatus.HIDE),
        this.isCulling = !0
    }
    _show_culling() {
        this.isCulling && (this.rootNode && this.rootNode.getChildMeshes().forEach(e=>{
            e.visibility = 1
        }
        ),
        this.bbComponent.updateBillboardStatus(this, BillboardStatus.SHOW),
        this.isCulling = !1)
    }
    _hide() {
        !this.isHide || (this.setIsPickable(!1),
        this.priority == 0 ? (this.rootNode.setEnabled(!1),
        this.isRender = !1,
        this.bbComponent.updateBillboardStatus(this, BillboardStatus.HIDE)) : this.isRender && (this.avatarManager.currentLODUsers[this.distLevel]--,
        this.removeAvatarFromScene()))
    }
    rotate(e, t, r) {
        return this.stateMachine.roll(this, e, t, r)
    }
    set isRayCastEnable(e) {
        this._isRayCastEnable = e
    }
    get isRayCastEnable() {
        return this._isRayCastEnable
    }
    getAvatarId() {
        return this.id
    }
    getAvaliableAnimations() {
        const e = avatarLoader.avaliableAnimation.get(this.avatarType);
        return e || []
    }
    setPosition(e, t=!1) {
        if (this._avatarPosition = e,
        this.rootNode) {
            const r = ue4Position2Xverse(this._avatarPosition);
            let n = !1;
            this.avatarManager.getMainAvatar() && (this.id != this.avatarManager.getMainAvatar().id || (Math.abs(r.y - this._previousReceivedPosition.y) > castRayOffsetY && (n = !0),
            r.subtract(this._previousReceivedPosition).length() > castRayTeleportationOffset && (n = !0))),
            this._isRayCastEnable ? n || t ? this._castRay(e).then(o=>{
                this.rootNode.position = r,
                this.rootNode.position.y -= o
            }
            ).catch(o=>{
                Promise.reject(o)
            }
            ) : (this.rootNode.position.x = r.x,
            this.rootNode.position.z = r.z) : this.rootNode.position = r,
            this._previousReceivedPosition = r.clone()
        }
        return Promise.resolve(e)
    }
    setRotation(e) {
        if (this._avatarRotation = e,
        this.rootNode) {
            const t = {
                pitch: e.pitch,
                yaw: e.yaw + 180,
                roll: e.roll
            }
              , r = ue4Rotation2Xverse(t);
            this.rootNode.rotation = r
        }
    }
    setAvatarVisible(e) {
        this.rootNode && (this.rootNode.setEnabled(e),
        this.rootNode.getChildMeshes().forEach(t=>{
            t.setEnabled(e)
        }
        ))
    }
    setScale(e) {
        this._avatarScale = e,
        this.rootNode && (this.rootNode.scaling = new Vector3(e,e,e)),
        this.bbComponent.bbox && this.getBbox()
    }
    _removeAvatarFromScene() {
        var e, t;
        this.isRender = !1,
        (e = this.controller) == null || e.detachAnimation(),
        this.component.dispose(this),
        (t = this.avatarManager.sceneManager) == null || t.lightComponent.removeShadow(this)
    }
    removeAvatarFromScene() {
        this._removeAvatarFromScene(),
        this._disposeBillBoard()
    }
    _disposeBillBoard() {
        this.bbComponent.disposeBillBoard(this)
    }
    addComponent(e, t, r, n) {
        return this.component.changeClothesComp(this, e, t, r, n)
    }
    _castRay(e) {
        return new Promise((t,r)=>{
            var d;
            const n = ue4Position2Xverse(e)
              , o = new Vector3(0,-1,0)
              , a = 1.5 * this.scale
              , s = 100 * a
              , l = a
              , u = new Vector3(n.x,n.y + l,+n.z)
              , c = new Ray(u,o,s)
              , h = (d = this.avatarManager.sceneManager) == null ? void 0 : d.getGround(e);
            if (!h || h.length <= 0)
                return log$E.warn(`\u89D2\u8272 id= ${this.id} \u627E\u4E0D\u5230\u5730\u9762\uFF0C\u5F53\u524D\u9AD8\u5EA6\u4E3A\u4E0B\u53D1\u9AD8\u5EA6`),
                t(0);
            let f = c.intersectsMeshes(h);
            if (f.length > 0)
                return t(f[0].distance - l);
            if (o.y = 1,
            f = c.intersectsMeshes(h),
            f.length > 0)
                return t(-(f[0].distance - l))
        }
        )
    }
    setPickBoxScale(e) {
        return this.bbComponent.setPickBoxScale(e)
    }
    setIsPickable(e) {
        return this.bbComponent.setIsPickable(this, e)
    }
    createPickBoundingbox(e) {
        return this.bbComponent.createPickBoundingbox(this, e)
    }
    scaleBbox(e) {
        this.bbComponent.bbox && this.bbComponent.bbox.scale(e)
    }
    rotateTo(e, t, r) {
        return this.stateMachine.rotateTo(this, e, t, r)
    }
    faceTo(e, t) {
        return this.stateMachine.lookAt(this, e, t)
    }
    removeObserver() {
        this.stateMachine.disposeObsever()
    }
    move(e, t, r, n, o) {
        return this.stateMachine.moveTo(this, e, t, r, n, o)
    }
    initNameboard(e=1) {
        return this.bbComponent.initNameboard(this, e)
    }
    initBubble(e=1) {
        return this.bbComponent.initBubble(this, e)
    }
    say(e, {id: t, isUser: r, background: n, font: o="Arial", fontsize: a=38, fontcolor: s="#ffffff", fontstyle: l="bold", linesize: u=22, linelimit: c, offsets: h={
        x: 0,
        y: 0,
        z: 40
    }, scale: f=this._avatarScale, compensationZ: d=11.2, reregistAnyway: _=!0}) {
        return this.bbComponent.say(this, e, {
            id: t,
            isUser: r,
            background: n,
            font: o,
            fontsize: a,
            fontcolor: s,
            fontstyle: l,
            linesize: u,
            linelimit: c,
            offsets: h,
            scale: f,
            compensationZ: d,
            reregistAnyway: _
        })
    }
    silent() {
        return this.bbComponent.silent()
    }
    setNickName(e, {id: t, isUser: r, background: n, font: o="Arial", fontsize: a=40, fontcolor: s="#ffffff", fontstyle: l="bold", linesize: u=22, linelimit: c, offsets: h={
        x: 0,
        y: 0,
        z: 15
    }, scale: f=this._avatarScale, compensationZ: d=0, reregistAnyway: _=!1}) {
        return this.bbComponent.setNickName(this, e, {
            id: t,
            isUser: r,
            background: n,
            font: o,
            fontsize: a,
            fontcolor: s,
            fontstyle: l,
            linesize: u,
            linelimit: c,
            offsets: h,
            scale: f,
            compensationZ: d,
            reregistAnyway: _
        })
    }
    generateButtons(e=null, t=this._avatarScale, r=85) {
        return this.bbComponent.generateButtons(this, e, t, r)
    }
    clearButtons() {
        return this.bbComponent.clearButtons()
    }
    attachExtraProp(e, t, r, n) {
        return this.component.addDecoComp(this, e, t, r, n)
    }
    showExtra(e) {
        return this.component.showExtra(e)
    }
    hideExtra(e) {
        return this.component.hideExtra(e)
    }
    disposeExtra() {
        return this.component.disposeExtra()
    }
    getSkeletonPositionByName(e) {
        var t;
        if (this.skeleton) {
            const r = this.skeleton.bones.find(n=>n.name.replace("Clone of ", "") == e);
            if (r && r.getTransformNode() && ((t = r.getTransformNode()) == null ? void 0 : t.position)) {
                const n = r.getTransformNode().position;
                return xversePosition2Ue4({
                    x: n.x,
                    y: n.y,
                    z: n.z
                })
            }
        }
    }
    shootTo(e, t, r=2, n=10, o={
        x: 0,
        y: 0,
        z: 150
    }) {
        return this.stateMachine.sendObjectTo(this, e, t, r, n, o)
    }
}
const log$D = new Logger$1("AvatarManager");
var EAvatarRelationRank = (i=>(i[i.Self = 0] = "Self",
i[i.Npc = 1] = "Npc",
i[i.Friend = 2] = "Friend",
i[i.Stranger = 3] = "Stranger",
i[i.Robot = 4] = "Robot",
i[i.Unknown = 5] = "Unknown",
i))(EAvatarRelationRank || {});
class XAvatarManager {
    constructor(e) {
        E(this, "characterMap", new Map);
        E(this, "curAnimList", []);
        E(this, "extraComps", new Map);
        E(this, "_mainUser");
        E(this, "_scene");
        E(this, "_sceneManager");
        E(this, "_lodSettings");
        E(this, "maxBillBoardDist", 0);
        E(this, "maxAvatarNum", 0);
        E(this, "currentLODUsers", []);
        E(this, "bboxMeshPool");
        E(this, "_distLevels", []);
        E(this, "_maxLODUsers", []);
        E(this, "_cullingDistance", 0);
        E(this, "_maxDistRange");
        E(this, "_delayTime", 100);
        E(this, "_queueLength", -1);
        E(this, "_queue", []);
        E(this, "_processList", []);
        E(this, "_process");
        E(this, "_updateLoopObserver");
        E(this, "_avatarInDistance", []);
        E(this, "_renderedAvatar", []);
        E(this, "_enableNickname", !0);
        E(this, "_tickObserver");
        E(this, "_tickInterval");
        E(this, "_defaultAnims");
        E(this, "_tickDispose", 0);
        E(this, "_disposeTime", 100);
        E(this, "avatarLoader", avatarLoader);
        this._scene = e.mainScene,
        this._sceneManager = e,
        this.initAvatarMap(),
        this._initSettings(),
        this._maxDistRange = this._distLevels[this._distLevels.length - 1],
        this.bboxMeshPool = new Pool(this.createBboxAsset,this.resetBboxAsset,0,this.maxAvatarNum,this._sceneManager.Scene,0,0,0),
        this._tickInterval = 250;
        let t = 0;
        this._tickObserver = this._scene.onAfterRenderObservable.add(()=>{
            t += 1,
            t == this._tickInterval && (this.tick(),
            t = 0)
        }
        )
    }
    tick() {
        this.bboxMeshPool.clean(0)
    }
    createBboxAsset(e, t, r, n) {
        return MeshBuilder.CreateBox("avatarBbox", {
            width: t,
            height: r,
            depth: n
        }, e)
    }
    resetBboxAsset(e) {
        const t = e.data;
        return t.setEnabled(!1),
        t.isPickable = !1,
        e
    }
    _initSettings() {
        this._defaultAnims = avatarSetting.defaultIdle,
        this._lodSettings = avatarSetting.lod,
        this._distLevels = avatarSetting.lod.map(e=>e.dist),
        this._maxLODUsers = avatarSetting.lod.map(e=>e.quota),
        this.currentLODUsers = new Array(this._distLevels.length).fill(0),
        this.maxAvatarNum = avatarSetting.maxAvatarNum,
        this.maxBillBoardDist = avatarSetting.maxBillBoardDist,
        this._cullingDistance = avatarSetting.cullingDistance
    }
    maxRenderNum() {
        let e = 0;
        return this._maxLODUsers.forEach(t=>{
            e += t
        }
        ),
        e
    }
    curRenderNum() {
        let e = 0;
        return this.currentLODUsers.forEach(t=>{
            e += t
        }
        ),
        e
    }
    setLoDLevels(e) {
        this._distLevels = e
    }
    set cullingDistance(e) {
        this._cullingDistance = e
    }
    get cullingDistance() {
        return this._cullingDistance
    }
    getLoDLevels() {
        return this._distLevels
    }
    setLodUserLimits(e, t) {
        this._maxLODUsers.length > e && (this._maxLODUsers[e] = t)
    }
    setLodDist(e, t) {
        this._distLevels[e] = t
    }
    setMaxDistRange(e) {
        this._maxDistRange = e,
        this._distLevels[this._distLevels.length - 1] = e
    }
    get scene() {
        return this._scene
    }
    setMainAvatar(e) {
        var t;
        this._mainUser = (t = this.characterMap.get(0)) == null ? void 0 : t.get(e)
    }
    getMainAvatar() {
        return this._mainUser
    }
    enableAllNickname(e) {
        return this.characterMap.forEach((t,r)=>{
            r != 0 && t.forEach((n,o)=>{
                this._updateBillboardStatus(n, e ? BillboardStatus.SHOW : BillboardStatus.HIDE)
            }
            )
        }
        ),
        this._enableNickname = e
    }
    getAvatarById(e) {
        let t;
        return this.characterMap.forEach((r,n)=>{
            r.get(e) && (t = r.get(e))
        }
        ),
        t
    }
    getAvatarNums() {
        let e = 0;
        return this.characterMap.forEach((t,r)=>{
            e += t.size
        }
        ),
        e
    }
    registerAvatar(e) {
        this.characterMap.get(e.priority).set(e.id, e)
    }
    unregisterAvatar(e) {
        this.characterMap.get(e.priority).delete(e.id)
    }
    initAvatarMap() {
        this.characterMap.set(0, new Map),
        this.characterMap.set(1, new Map),
        this.characterMap.set(2, new Map),
        this.characterMap.set(3, new Map),
        this.characterMap.set(4, new Map),
        this.characterMap.set(5, new Map)
    }
    loadAvatar({id: e, avatarType: t, priority: r, avatarManager: n, assets: o, status: a}) {
        return new Promise((s,l)=>{
            if (this.getAvatarById(e))
                return l(new DuplicateAvatarIDError(`[Engine] cannot init avatar with the same id = ${e}`));
            if (this.getAvatarNums() > this.maxAvatarNum)
                return l(new ExceedMaxAvatarNumError(`[Engine] \u8D85\u51FA\u6700\u5927\u89D2\u8272\u9650\u5236 ${this.maxAvatarNum}`));
            const u = new XAvatar({
                id: e,
                avatarType: t,
                priority: r,
                avatarManager: n,
                assets: o,
                status: a
            });
            if (this.registerAvatar(u),
            r == 0)
                this.setMainAvatar(u.id),
                this.addAvatarToScene(u, 0).then(c=>(log$D.debug(`[Engine] avatar ${u.id} has been added to scene`),
                c ? (this._updateBillboardStatus(c, BillboardStatus.SHOW),
                setTimeout(()=>{
                    this.launchProcessLoadingLoop()
                }
                , this._delayTime),
                s(c)) : (u.removeAvatarFromScene(),
                l(new AvatarAssetLoadingError)))).catch(c=>(u.removeAvatarFromScene(),
                l(new AvatarAssetLoadingError(c))));
            else
                return s(u)
        }
        )
    }
    deleteAvatar(e) {
        return e.isRender ? (e.removeAvatarFromScene(),
        this.currentLODUsers[e.distLevel]--) : e.bbComponent.disposeBillBoard(e),
        this._processList = this._processList.filter(t=>t.id !== e.id),
        this.unregisterAvatar(e),
        e.rootNode && (e.rootNode.dispose(),
        e.rootNode = void 0),
        e.bbComponent.bbox && e.bbComponent.bbox.dispose(),
        e.removeObserver(),
        e
    }
    _checkLODLevel(e) {
        if (e < this._distLevels[0])
            return 0;
        for (let t = 1; t < this._distLevels.length; ++t)
            if (e >= this._distLevels[t - 1] && e < this._distLevels[t])
                return t;
        return this._distLevels.length - 1
    }
    get sceneManager() {
        return this._sceneManager
    }
    launchProcessLoadingLoop() {
        this._updateAvatarStatus()
    }
    stopProcessLoadingLoop() {
        var e;
        this._updateLoopObserver && ((e = this._scene) == null || e.onBeforeRenderObservable.remove(this._updateLoopObserver))
    }
    _distToMain(e) {
        var n;
        const t = (n = this._mainUser) == null ? void 0 : n.position
          , r = e.position;
        if (r && t) {
            const o = this.sceneManager.cameraComponent.MainCamera.getFrontPosition(1).subtract(this.sceneManager.cameraComponent.MainCamera.position).normalize()
              , a = e.rootNode.position.subtract(this.sceneManager.cameraComponent.MainCamera.position).normalize();
            let s = 1;
            if (o && a) {
                const l = a.multiply(o);
                s = Math.acos(l.x + l.y + l.z) < this.sceneManager.cameraComponent.MainCamera.fov / 2 ? 1 : 1e11
            }
            return calcDistance3D(t, r) * s
        } else
            return log$D.warn("user position or camera position is not correct!"),
            1e11
    }
    _distToCamera(e) {
        var n;
        const t = (n = this._sceneManager) == null ? void 0 : n.cameraComponent.getCameraPose().position
          , r = e.position;
        return r && t ? calcDistance3D(t, r) : (log$D.warn("user position or camera position is not correct!"),
        1e11)
    }
    showAll(e) {
        this.characterMap.forEach((t,r)=>{
            e && r == 0 && t.forEach((n,o)=>{
                n.show()
            }
            ),
            r != 0 && t.forEach((n,o)=>{
                n.show()
            }
            )
        }
        )
    }
    hideAll(e) {
        this.characterMap.forEach((t,r)=>{
            e && r == 0 && t.forEach((n,o)=>{
                n.hide()
            }
            ),
            r != 0 && t.forEach((n,o)=>{
                n.hide()
            }
            )
        }
        )
    }
    _assemblyAvatar(e, t) {
        var n, o;
        const r = e.get(avatarSetting.body);
        if (r && !t.attachBody(r)) {
            t.isInLoadingList = !1,
            e.clear();
            return
        }
        for (const a of e)
            if (a[0] != avatarSetting.body && a[0] != avatarSetting.animations && !t.attachDecoration(a[1])) {
                t.isInLoadingList = !1,
                t.removeAvatarFromScene(),
                e.clear();
                return
            }
        t.isRender = !0,
        (n = t.controller) == null || n.playAnimation(t.controller.onPlay, t.controller.loop),
        (o = t.controller) == null || o.onPlayObservable.addOnce(()=>{
            var a, s;
            if (!this.getAvatarById(t.id)) {
                t.isInLoadingList = !1,
                t.removeAvatarFromScene(),
                this.currentLODUsers[t.distLevel]--;
                return
            }
            if (this.getAvatarById(t.id).rootNode.getChildMeshes().length < e.size) {
                log$D.error(`this avatar does not have complete components, render failed. current list ${(a = this.getAvatarById(t.id)) == null ? void 0 : a.clothesList},avatar: ${t.id},${t.nickName}`),
                t.isInLoadingList = !1,
                t.removeAvatarFromScene(),
                this.currentLODUsers[t.distLevel]--;
                return
            }
            t.setIsPickable(!0),
            t.isInLoadingList = !1,
            t.setAvatarVisible(!0),
            (s = this._sceneManager) == null || s.lightComponent.setShadow(t),
            t.getBbox(),
            t.nameBoard && t.nickName.length > 0 && t.setNickName(t.nickName, t.nameBoard.DEFAULT_CONFIGS),
            t.bubble && t.words.length > 0 && t.say(t.words, t.bubble.DEFAULT_CONFIGS),
            log$D.debug(`[Engine] avatar ${t.id} has been added to scene, current number of users : ${this.currentLODUsers}`)
        }
        )
    }
    _disposeUnusedAssets() {
        this._tickDispose++,
        this._tickDispose > this._disposeTime && (avatarLoader.disposeContainer(),
        this._tickDispose = 0)
    }
    _addResourcesToList(e, t) {
        return e.clothesList.forEach(r=>{
            r.lod = t,
            this._queue.push(r)
        }
        ),
        this._queue.push({
            type: avatarSetting.animations,
            id: this._defaultAnims
        }),
        this._queue.push({
            type: avatarSetting.body,
            id: e.avatarType,
            lod: t
        }),
        !0
    }
    _updateBillboardStatus(e, t) {
        e.bbComponent.updateBillboardStatus(e, t)
    }
    _processLayer(e) {
        const t = this.characterMap.get(e)
          , r = [];
        for (t == null || t.forEach(n=>{
            n.distToCam = this._distToCamera(n);
            const o = n.distToCam < this._cullingDistance;
            if (n.isRender && (!n.isHide && o ? n._hide_culling() : n._show_culling()),
            n.priority != 0) {
                n.distance = this._distToMain(n);
                let a = BillboardStatus.SHOW;
                n.distance < this._maxDistRange && (o ? a = BillboardStatus.HIDE : n._show_culling(),
                this._updateBillboardStatus(n, a)),
                n.isHide || (n.isInLoadingList ? this.currentLODUsers[n.distLevel]++ : r.push(n))
            }
        }
        ),
        r.sort((n,o)=>o.distance - n.distance); r.length > 0 && this.curRenderNum() < this.maxRenderNum(); ) {
            const n = r.pop();
            let o = this._checkLODLevel(n.distance)
              , a = !1;
            for (let s = 0; s < this._maxLODUsers.length; ++s)
                if (this.currentLODUsers[s] < this._maxLODUsers[s]) {
                    o = s,
                    a = !0;
                    break
                }
            if (!a || n.distance > this._maxDistRange) {
                if (n.isRender) {
                    n._removeAvatarFromScene();
                    let s = BillboardStatus.HIDE;
                    n.distance < this._maxDistRange && (s = BillboardStatus.SHOW),
                    this._updateBillboardStatus(n, s)
                }
                break
            }
            o != n.distLevel ? (n.isRender && (n.pendingLod = !0),
            n.distLevel = o,
            this._processList.push(n),
            n.isInLoadingList = !0) : n.isRender || (this._processList.push(n),
            n.isInLoadingList = !0),
            this.currentLODUsers[o]++
        }
        return this.curRenderNum() >= this.maxRenderNum() && r.forEach(n=>{
            if (n.isRender) {
                n._removeAvatarFromScene();
                let o = BillboardStatus.HIDE;
                n.distance < this._maxDistRange && (o = BillboardStatus.SHOW),
                this._updateBillboardStatus(n, o)
            }
        }
        ),
        this.curRenderNum() < this.maxRenderNum()
    }
    _updateAvatar() {
        this.currentLODUsers = [0, 0, 0];
        const e = [5, 4, 3, 2, 1, 0];
        for (; e.length > 0; ) {
            const t = e.pop();
            if (!this._processLayer(t)) {
                e.forEach(n=>{
                    var o;
                    (o = this.characterMap.get(n)) == null || o.forEach(a=>{
                        a.distance = this._distToMain(a);
                        let s = BillboardStatus.HIDE;
                        a.distToCam < this._maxDistRange && (s = BillboardStatus.SHOW,
                        a.isRender && a._removeAvatarFromScene()),
                        this._updateBillboardStatus(a, s)
                    }
                    )
                }
                );
                break
            }
        }
    }
    _updateAvatarStatus() {
        const e = new Map;
        this._updateLoopObserver = this.scene.onBeforeRenderObservable.add(()=>{
            var t;
            if (this._disposeUnusedAssets(),
            !(this.getAvatarNums() <= 0)) {
                if (!this._process && this._processList.length == 0 && this._updateAvatar(),
                !this._process && this._processList.length > 0) {
                    const r = this._processList.shift();
                    r != this._process && !r.isCulling ? this._addResourcesToList(r, r.distLevel) ? (this._process = r,
                    this._queueLength = this._queue.length) : (this._process = void 0,
                    this._queue = [],
                    r.isInLoadingList = !1) : r.isInLoadingList = !1
                }
                if (e.size === this._queueLength && this._process) {
                    this._process.pendingLod && (this._process.pendingLod = !1,
                    this._process._removeAvatarFromScene());
                    const r = Date.now();
                    this._assemblyAvatar(e, this._process),
                    (t = this._sceneManager) == null || t.engineRunTimeStats.timeArray_addAvatarToScene.add(Date.now() - r),
                    this._updateBillboardStatus(this._process, BillboardStatus.SHOW),
                    e.clear(),
                    this._queue = [],
                    this._process.isInLoadingList = !1,
                    this._process = void 0,
                    this._disposeUnusedAssets()
                }
                this._loadResByList(e)
            }
        }
        )
    }
    _loadResByList(e) {
        let t = 0;
        const r = 5;
        if (!this._process) {
            e.clear();
            return
        }
        for (; t < r && this._queue.length > 0; ) {
            const n = Date.now()
              , o = this._queue.pop();
            setTimeout(()=>{
                o ? o.type === avatarSetting.body ? this.loadBody(o.type, o.id, o.lod).then(a=>{
                    a && e.set(avatarSetting.body, a),
                    t += Date.now() - n
                }
                ).catch(a=>{
                    this._process && (this._process.isHide = !0,
                    this.currentLODUsers[this._process.distLevel]--,
                    e.clear(),
                    this._queue = [],
                    this._process.isInLoadingList = !1,
                    this._process = void 0,
                    t += 100),
                    log$D.warn(`[Engine] body ${o.id} uri error, type ${o.type}, avatar has been hided` + a)
                }
                ) : o.type === avatarSetting.animations ? this.loadAnimation(this._process.avatarType, o.id).then(a=>{
                    a && e.set(avatarSetting.animations, a),
                    t += Date.now() - n
                }
                ).catch(a=>{
                    this._process && (this._process.isHide = !0,
                    this.currentLODUsers[this._process.distLevel]--,
                    e.clear(),
                    this._queue = [],
                    this._process.isInLoadingList = !1,
                    this._process = void 0,
                    t += 100),
                    log$D.warn(`animation  ${o.id} uri error, type ${o.type}, avatar has been hided` + a)
                }
                ) : this.loadDecoration(o.type, o.id, o.lod).then(a=>{
                    a && e.set(a.type, a),
                    t += Date.now() - n
                }
                ).catch(a=>{
                    this._process && (this._process.isHide = !0,
                    this.currentLODUsers[this._process.distLevel]--,
                    e.clear(),
                    this._queue = [],
                    this._process.isInLoadingList = !1,
                    this._process = void 0,
                    t += 100),
                    log$D.warn(`component ${o.id} uri error, type ${o.type}, avatar has been hided` + a)
                }
                ) : t += 100
            }
            , 0)
        }
    }
    _validateContainer(e) {
        return !e.meshes || e.meshes.length <= 1 ? (log$D.warn("import container has no valid meshes"),
        !1) : !e.skeletons || e.skeletons.length == 0 ? (log$D.warn("import container has no valid skeletons"),
        !1) : !0
    }
    _getAssetContainer(e, t) {
        return new Promise((r,n)=>{
            const o = this._getSourceKey(e, t || 0)
              , a = avatarLoader.containers.get(o);
            if (a)
                return r(a);
            avatarLoader.load(this.sceneManager, e, t).then(s=>s ? this._validateContainer(s) ? (avatarLoader.containers.set(o, s),
            r(s)) : n(new ContainerLoadingFailedError(`[Engine] :: cannot load body type ${e}.`)) : n(new ContainerLoadingFailedError(`[Engine] container load failed cannot load body type ${e}.`))).catch(s=>n(new ContainerLoadingFailedError(`[Engine] ${s} :: cannot load body type ${e}.`)))
        }
        )
    }
    _clipContainerRes(e) {
        e.transformNodes.forEach(t=>{
            t.dispose()
        }
        ),
        e.transformNodes = [],
        e.skeletons.forEach(t=>{
            t.dispose()
        }
        ),
        e.skeletons = []
    }
    loadBody(e, t, r) {
        return new Promise((n,o)=>avatarLoader.load(this.sceneManager, t, r).then(a=>{
            if (a) {
                const s = a.instantiateModelsToScene();
                a.xReferenceCount++;
                const l = {
                    isRender: !1,
                    uId: Math.random(),
                    root: s.rootNodes[0],
                    skeletonType: e,
                    name: t,
                    animations: s.animationGroups,
                    skeleton: s.skeletons[0],
                    lod: r
                };
                return s.rootNodes[0]._parentContainer = a,
                s.rootNodes[0].setEnabled(!1),
                n(l)
            } else
                return o(new ContainerLoadingFailedError("[Engine] container failed instanciates failed"))
        }
        ).catch(()=>o(new ContainerLoadingFailedError(`[Engine] body type ${e} instanciates failed`))))
    }
    updateAnimationLists(e, t) {
        return new Promise((r,n)=>(avatarLoader.avaliableAnimation.set(t, e),
        r()))
    }
    loadAnimation(e, t) {
        return new Promise((r,n)=>avatarLoader.loadAnimRes(this.sceneManager, t, e).then(o=>{
            if (o) {
                let a;
                const s = this.avatarLoader.animations;
                return o.animationGroups.forEach(l=>{
                    l.stop(),
                    l.name === t && (a = l,
                    a.pContainer = o),
                    s.set(getAnimationKey(l.name, e), l)
                }
                ),
                this._clipContainerRes(o),
                o.xReferenceCount++,
                r(a)
            } else
                return n(new ContainerLoadingFailedError("[Engine] container failed instanciates failed"))
        }
        ))
    }
    loadDecoration(e, t, r) {
        return new Promise((n,o)=>avatarLoader.load(this.sceneManager, t, r).then(a=>{
            if (a) {
                this._clipContainerRes(a);
                const s = a.meshes[1].clone(a.meshes[1].name, null);
                if (!s) {
                    log$D.warn("[Engine] decoration does not exist!"),
                    n(null);
                    return
                }
                const l = {
                    isRender: !1,
                    uId: Math.random(),
                    root: s,
                    type: e,
                    name: t,
                    isSelected: !1,
                    lod: r
                };
                if (a.xReferenceCount++,
                s._parentContainer = a,
                a.meshes.length > 1)
                    for (let u = 2; u < a.meshes.length; u++)
                        s.addChild(a.meshes[u].clone(a.meshes[u].name, null));
                s.setEnabled(!1),
                l.isSelected = !0,
                n(l)
            } else
                return o(new ContainerLoadingFailedError("[Engine] container failed, instanciates failed."))
        }
        ).catch(()=>o(new ContainerLoadingFailedError(`[Engine] body type ${e} instanciates failed.`))))
    }
    _getSourceKey(e, t) {
        return t && avatarSetting.lod[t] ? e + avatarSetting.lod[t].fileName.split(".")[0] : e
    }
    addAvatarToScene(e, t) {
        const r = Date.now();
        return new Promise((n,o)=>{
            this.loadBody(e.avatarType, e.avatarType, t).then(a=>{
                var s;
                if (!a)
                    return e.isInLoadingList = !1,
                    o(new ContainerLoadingFailedError(`[Engine] avatar ${e.id} instanciates failed`));
                if (e.attachBody(a),
                a.animations.length > 0)
                    return a.animations.forEach(l=>{
                        l.stop()
                    }
                    ),
                    e.setAnimations(a.animations),
                    (s = e.controller) == null || s.playAnimation(e.controller.onPlay, !0),
                    e.isRender = !0,
                    e.isInLoadingList = !1,
                    e.setAvatarVisible(!0),
                    n(e);
                this.loadAnimation(e.avatarType, this._defaultAnims).then(l=>{
                    if (!l)
                        return e.removeAvatarFromScene(),
                        e.isInLoadingList = !1,
                        o(new AvatarAnimationError);
                    const u = [];
                    e.clothesList.length > 0 && e.clothesList.forEach(c=>{
                        u.push(this.loadDecoration(c.type, c.id, t))
                    }
                    ),
                    Promise.all(u).then(c=>{
                        var d, _, g, m;
                        c.forEach(v=>{
                            if (v && !v.isRender)
                                e.attachDecoration(v);
                            else
                                return e.isInLoadingList = !1,
                                e.removeAvatarFromScene(),
                                o(new AvatarAssetLoadingError)
                        }
                        ),
                        e.isRender = !0,
                        (d = e.controller) == null || d.playAnimation(e.controller.onPlay, e.controller.loop),
                        e.setAvatarVisible(!0);
                        const h = avatarLoader.mshPath.get("meshes/ygb.glb")
                          , f = avatarLoader.matPath.get(avatarResources.ygb.mesh);
                        h && f ? this.loadExtra(f, h).then(v=>{
                            var y;
                            e.isRender = !0,
                            e.isInLoadingList = !1,
                            e.distLevel = t,
                            (y = this._sceneManager) == null || y.engineRunTimeStats.timeArray_addAvatarToScene.add(Date.now() - r),
                            n(e)
                        }
                        ) : (e.isRender = !0,
                        e.isInLoadingList = !1,
                        e.distLevel = t,
                        (_ = this._sceneManager) == null || _.engineRunTimeStats.timeArray_addAvatarToScene.add(Date.now() - r),
                        n(e)),
                        (g = this._sceneManager) == null || g.lightComponent.setShadow(e),
                        e.isInLoadingList = !1,
                        e.distLevel = t,
                        (m = this._sceneManager) == null || m.engineRunTimeStats.timeArray_addAvatarToScene.add(Date.now() - r),
                        n(e)
                    }
                    ).catch(()=>o(new AvatarAssetLoadingError(`[Engine] avatar ${e.id} instanciates failed.`)))
                }
                ).catch(()=>o(new AvatarAssetLoadingError(`[Engine] avatar ${e.id} instanciates failed.`)))
            }
            ).catch(()=>o(new AvatarAssetLoadingError(`[Engine] avatar ${e.id} instanciates failed.`)))
        }
        )
    }
    loadExtra(e, t) {
        const r = avatarResources.ygb.name;
        return new Promise((n,o)=>{
            var a;
            (a = this.sceneManager) == null || a.urlTransformer(e).then(s=>{
                SceneLoader.LoadAssetContainerAsync("", s, this.scene, null, avatarSetting.fileType).then(l=>{
                    var c;
                    this.extraComps.set(r, l.meshes[0]);
                    const u = new NodeMaterial(`material_${r}`,this._scene,{
                        emitComments: !1
                    });
                    (c = this.sceneManager) == null || c.urlTransformer(t).then(h=>{
                        u.loadAsync(h).then(()=>{
                            l.meshes[2].material.dispose(!0, !0),
                            u.build(!1),
                            l.meshes[2].material = u,
                            n(l.meshes[2])
                        }
                        )
                    }
                    )
                }
                )
            }
            )
        }
        )
    }
    getAvatarList() {
        const e = [];
        return this.characterMap.forEach((t,r)=>{
            t.forEach((n,o)=>{
                e.push(n)
            }
            )
        }
        ),
        e
    }
    _debug_avatar() {
        var t, r;
        console.error("===>currentLODUsers", this.currentLODUsers),
        console.error("===>maxLODUsers", this._maxLODUsers),
        console.error("===>Loddist", this.getLoDLevels()),
        console.error("===> main character loc", (r = (t = this._mainUser) == null ? void 0 : t.rootNode) == null ? void 0 : r.position);
        let e = 0;
        this.getAvatarList().forEach(n=>{
            n.isRender && (console.error(`avatar id : ${n.id},lod ${n.distLevel},is Hide ${n.isHide}, distance ${n.distance}, is pending ${n.isInLoadingList}`),
            e++)
        }
        ),
        console.error("========= avatar num", e),
        console.error("loop:", this._updateLoopObserver ? "on" : "false", "=> process", this._process, "===> comp", this._processList),
        console.error("===>maxLODUsers", this._maxLODUsers)
    }
}
const log$C = new Logger$1("XLightManager");
class XLightManager {
    constructor(e) {
        E(this, "_scene");
        E(this, "_envTexture");
        E(this, "_shadowLight");
        E(this, "_shadowGenerator");
        E(this, "_avatarShadowMeshMap");
        E(this, "_cullingShadowObservers");
        E(this, "sceneManager");
        this.sceneManager = e,
        this._scene = this.sceneManager.Scene,
        this._envTexture = null,
        this.shadowLean = .1;
        const t = new Vector3(this.shadowLean,-1,0)
          , r = 1024;
        this._shadowLight = new DirectionalLight("AvatarLight",t,this._scene),
        this._shadowLight.shadowMaxZ = 5e3,
        this._shadowLight.intensity = 0,
        this.attachLightToCamera(this._shadowLight),
        this._shadowGenerator = new ShadowGenerator(r,this._shadowLight,!0),
        this._avatarShadowMeshMap = new Map,
        this._cullingShadowObservers = new Map
    }
    set shadowLean(e) {
        e = Math.min(e, 1),
        e = Math.max(e, -1),
        this._shadowLight && (this._shadowLight.direction = new Vector3(e,-1,0))
    }
    setIBL(e) {
        return new Promise((t,r)=>{
            this.sceneManager.urlTransformer(e).then(n=>{
                var o;
                if (n == ((o = this._envTexture) == null ? void 0 : o.url))
                    return t("env set success");
                this._envTexture != null && this.disposeIBL(),
                this._envTexture = CubeTexture.CreateFromPrefilteredData(n, this._scene, ".env"),
                this._scene.environmentTexture = this._envTexture,
                this._envTexture.onLoadObservable.addOnce(()=>{
                    t("env set success"),
                    log$C.info("env set success")
                }
                )
            }
            ).catch(()=>{
                r("env set fail")
            }
            )
        }
        )
    }
    disposeIBL() {
        this._envTexture == null ? log$C.info("env not exist") : (this._envTexture.dispose(),
        this._envTexture = null,
        this._scene.environmentTexture = null,
        log$C.info("env dispose success"))
    }
    removeShadow(e) {
        var t;
        if (this._avatarShadowMeshMap.has(e)) {
            this._avatarShadowMeshMap.delete(e),
            this._cullingShadowObservers.get(e) && (this._scene.onBeforeRenderObservable.remove(this._cullingShadowObservers.get(e)),
            this._cullingShadowObservers.delete(e));
            const r = e.rootNode;
            r && ((t = this._shadowGenerator) == null || t.removeShadowCaster(r))
        } else
            return
    }
    setShadow(e) {
        if (this._avatarShadowMeshMap.has(e))
            return;
        e.rootNode && this._avatarShadowMeshMap.set(e, e.rootNode.getChildMeshes());
        const t = 20
          , r = 10
          , n = this.cullingShadow(t, r, e);
        this._cullingShadowObservers.set(e, n)
    }
    cullingShadow(e, t, r) {
        let n = 0;
        const o = ()=>{
            var s, l;
            if (n == t) {
                const u = this._avatarShadowMeshMap.get(r)
                  , c = (s = r.rootNode) == null ? void 0 : s.getChildMeshes()
                  , h = this._scene.activeCamera;
                u == null || u.forEach(f=>{
                    var d;
                    (d = this._shadowGenerator) == null || d.removeShadowCaster(f, !1)
                }
                ),
                c == null || c.forEach(f=>{
                    var d;
                    (d = this._shadowGenerator) == null || d.addShadowCaster(f, !1)
                }
                ),
                h && r.rootNode && ((l = r.rootNode.position) == null ? void 0 : l.subtract(h.position).length()) > e && (c == null || c.forEach(f=>{
                    var d;
                    (d = this._shadowGenerator) == null || d.removeShadowCaster(f, !1)
                }
                )),
                c && this._avatarShadowMeshMap.set(r, c),
                n = 0
            } else
                n += 1
        }
        ;
        return this._scene.onBeforeRenderObservable.add(o)
    }
    attachLightToCamera(e) {
        const t = e
          , r = 15
          , n = ()=>{
            const o = this._scene.activeCamera;
            if (o) {
                const a = t.direction
                  , s = new Vector3(r * a.x,r * a.y,r * a.z)
                  , l = o.position;
                t.position = l.subtract(s)
            }
        }
        ;
        return t && this._scene.registerBeforeRender(n),
        n
    }
}
ParticleSystemSet.prototype.systems = new Array;
const de = class {
    constructor(e) {
        E(this, "_scene");
        E(this, "_particles");
        E(this, "_light");
        E(this, "load", (e,t,r)=>new Promise(n=>{
            ParticleSystemSet.BaseAssetsUrl = e;
            const o = new XMLHttpRequest;
            o.open("get", e + "/" + t),
            o.send(null),
            o.onload = ()=>{
                if (o.status == 200) {
                    const a = JSON.parse(o.responseText);
                    let s = null;
                    if (Object.keys(a).find(l=>l == "systems") == null) {
                        const l = ParticleSystem.Parse(a, this._scene, e);
                        s = new ParticleSystemSet,
                        s.systems.push(l)
                    } else
                        s = ParticleSystemSet.Parse(a, this._scene, !1);
                    n(s)
                }
            }
        }
        ));
        E(this, "get", e=>this._particles.get(e));
        E(this, "start", e=>{
            const t = this._particles.get(e);
            t && t.start()
        }
        );
        E(this, "stop", e=>{
            var r;
            const t = ((r = this._particles.get(e)) == null ? void 0 : r.systems) || [];
            for (let n = 0; n < t.length; n++)
                t[n].stop()
        }
        );
        E(this, "remove", e=>{
            const t = this._particles.get(e);
            t && t.dispose()
        }
        );
        E(this, "setParticlePosition", (e,t)=>{
            const r = this._particles.get(e);
            r && (r.emitterNode = t)
        }
        );
        E(this, "setParticleScalingInPlace", (e,t)=>{
            const r = this._particles.get(e);
            r == null || r.systems.forEach(n=>{
                de.scalingInPlace(n, t)
            }
            )
        }
        );
        if (this._scene = e,
        this._particles = new Map,
        this._light = null,
        this._scene.getLightByName("fireworkLight"))
            this._light = this._scene.getLightByName("fireworkLight");
        else {
            const t = new PointLight("fireworkLight",new Vector3(0,0,0),e);
            t.intensity = 0,
            this._light = t
        }
    }
    _flashBang(e=200) {
        const t = this._scene.getLightByName("fireworkLight");
        t.intensity = 1,
        setTimeout(()=>{
            t.intensity = 0
        }
        , e)
    }
}
;
let XParticleManager = de;
E(XParticleManager, "disposeParticleSysSet", e=>{
    !e.systems || (e.systems.forEach(t=>{
        de.disposeParticleSystem(t)
    }
    ),
    e.dispose())
}
),
E(XParticleManager, "disposeParticleSystem", e=>{
    e.particleSystem && (e = e.particleSystem),
    e.subEmitters && e.subEmitters.forEach(t=>{
        t instanceof Array ? t.forEach(r=>{
            de.disposeParticleSystem(r)
        }
        ) : de.disposeParticleSystem(t)
    }
    ),
    e.dispose()
}
),
E(XParticleManager, "scalingInPlace", (e,t)=>{
    e.getClassName() === "ParticleSystem" && (e.minSize *= t,
    e.maxSize *= t,
    e.subEmitters != null && e.subEmitters.forEach(r=>{
        r instanceof SubEmitter && de.scalingInPlace(r.particleSystem, t),
        r instanceof ParticleSystem && de.scalingInPlace(r, t),
        r instanceof Array && r.forEach(n=>{
            de.scalingInPlace(n.particleSystem, t)
        }
        )
    }
    ))
}
);
class EventEmitter$1 {
    constructor() {
        E(this, "topics", {});
        E(this, "on", (e,t,r)=>this.register(!1, e, t, r));
        E(this, "once", (e,t,r)=>this.register(!0, e, t, r));
        E(this, "register", (e,t,r,n)=>{
            this.topics[t] || (this.topics[t] = {
                once: e,
                listeners: [],
                excuted: !1
            });
            const o = {
                order: n || 0,
                listener: r,
                once: e
            };
            return this.topics[t].listeners.push(o),
            this.topics[t].listeners.sort((a,s)=>a.order - s.order),
            {
                unsub: ()=>{
                    this.off(t, r)
                }
            }
        }
        );
        E(this, "off", (e,t)=>{
            const r = this.topics[e];
            if (!r)
                return;
            const n = r.listeners.findIndex(o=>o.listener === t);
            this.topics[e].listeners.splice(n, 1)
        }
        );
        E(this, "removeAllListener", ()=>{
            this.topics = {}
        }
        );
        E(this, "emit", (e,t)=>{
            !this.topics[e] || this.topics[e].listeners.length < 1 || this.topics[e].excuted || (this.topics[e].listeners.forEach(r=>{
                r.listener(t !== void 0 ? t : {})
            }
            ),
            this.topics[e] && this.topics[e].once && (this.topics[e].excuted = !0))
        }
        )
    }
}
const VERSION$1 = "1.0.75"
  , ENV$1 = "production";
function getFormattedDate$1(i) {
    const e = i.getMonth() + 1
      , t = i.getDate()
      , r = i.getHours()
      , n = i.getMinutes()
      , o = i.getSeconds()
      , a = i.getMilliseconds()
      , s = (e < 10 ? "0" : "") + e
      , l = (t < 10 ? "0" : "") + t
      , u = (r < 10 ? "0" : "") + r
      , c = (n < 10 ? "0" : "") + n
      , h = (o < 10 ? "0" : "") + o;
    return i.getFullYear() + "-" + s + "-" + l + " " + u + ":" + c + ":" + h + "." + a
}
const REPORT_NUM_PER_REQUEST$1 = 20;
class Reporter$1 {
    constructor() {
        E(this, "_header", {});
        E(this, "_body", {});
        E(this, "_queue", []);
        E(this, "_api", "https://xa.xverse.cn:6688/collect");
        E(this, "_disabled", !1);
        E(this, "_interval", null);
        E(this, "isDocumentLoaded", ()=>document.readyState === "complete");
        this._header.logModuleId = "xverse-js",
        this._header.url = location.href,
        this._header.enviroment = ENV$1,
        this._body.sdkVersion = VERSION$1
    }
    disable() {
        this._disabled = !0,
        this._interval && window.clearInterval(this._interval)
    }
    updateHeader(e) {
        Object.assign(this._header, e)
    }
    updateBody(e) {
        Object.assign(this._body, e)
    }
    report(e, t, r) {
        if (this._disabled)
            return;
        r || (r = {});
        const {immediate: n, sampleRate: o} = r;
        if (o && o > Math.random())
            return;
        this.updateBody({
            logTime: getFormattedDate$1(new Date),
            logTimestamp: Date.now()
        });
        const a = s=>{
            const l = oe(le(oe({}, this._body), {
                type: e
            }), s);
            if (this._queue.push(l),
            e == "measurement") {
                const u = s
                  , c = u.metric + ":" + u.value
                  , h = le(oe({}, l), {
                    type: "log",
                    message: c
                });
                this._queue.push(h)
            }
        }
        ;
        Array.isArray(t) ? t.forEach(s=>a(s)) : a(t),
        n || this._queue.length >= REPORT_NUM_PER_REQUEST$1
    }
    _flushReport() {
        if (!this._queue.length || !this.isDocumentLoaded())
            return;
        const e = {
            header: this._header,
            body: this._queue.splice(0, REPORT_NUM_PER_REQUEST$1)
        };
        this._post(e)
    }
    _post(e) {
        return new Promise((t,r)=>{
            const n = new XMLHttpRequest;
            n.open("POST", this._api),
            n.setRequestHeader("Content-Type", "application/json");
            try {
                n.send(JSON.stringify(e))
            } catch (o) {
                console.error(o)
            }
            n.addEventListener("readystatechange", ()=>{
                if (n.readyState == 4)
                    return n.status == 200 ? t(n) : r("Unable to send log")
            }
            )
        }
        )
    }
}
const reporter$1 = new Reporter$1
  , log$B = new Logger$1("http");
class XverseDatabase extends Dexie$1 {
    constructor() {
        super("XverseDatabase1");
        E(this, "models");
        this.version(1).stores({
            models: "++id,name"
        }),
        this.models = this.table("models")
    }
}
const db = new XverseDatabase;
class Http$2 extends EventEmitter$1 {
    async get({url: e, useIndexedDb: t=!1, timeout: r=1e4, key: n}) {
        if (t)
            if (isIndexedDbSupported$1()) {
                const o = window.performance.now();
                let a = null;
                try {
                    a = await db.models.where("name").equals(e).first()
                } catch {
                    return log$B.warn("unable to query data from indexedDB"),
                    Promise.resolve(e)
                }
                const s = window.performance.now();
                log$B.debug(`search ${e} takes:${s - o}ms`);
                const l = `${a && a.model ? "found" : "notFound"} data by search ${e} `;
                if (log$B.debug(l),
                reporter$1.report("measurement", {
                    metric: "indexedDB",
                    value: s - o,
                    extra: l
                }),
                a && a.model) {
                    const u = dataURItoBlob$1(a.model);
                    return Promise.resolve(URL.createObjectURL(u))
                } else
                    return this.request({
                        url: e,
                        timeout: r,
                        contentType: "blob",
                        key: n
                    }).then(async u=>{
                        const c = await blobToDataURI$2(u.response);
                        try {
                            db.models.add({
                                name: e,
                                model: c
                            })
                        } catch {
                            log$B.warn("unable to add data to indexedDB")
                        }
                        return Promise.resolve(URL.createObjectURL(u.response))
                    }
                    ).catch(u=>Promise.reject(u))
            } else
                return this.request({
                    url: e,
                    timeout: r,
                    contentType: "blob",
                    key: n
                }).then(o=>{
                    const a = o.response;
                    return Promise.resolve(URL.createObjectURL(a))
                }
                ).catch(o=>Promise.reject(o));
        else
            return this.request({
                url: e,
                timeout: 5e3,
                key: n
            }).then(o=>o.getResponseHeader("content-type") === "application/json" ? Promise.resolve(JSON.parse(o.responseText)) : Promise.resolve(o.responseText)).catch(o=>{
                Promise.reject(o)
            }
            )
    }
    request({url: e, timeout: t=15e3, contentType: r, key: n}) {
        return new Promise((o,a)=>{
            const s = window.performance.now()
              , l = new XMLHttpRequest;
            r && (l.responseType = r),
            l.timeout = t,
            l.addEventListener("readystatechange", ()=>{
                if (l.readyState == 4)
                    if (l.status == 200) {
                        const u = window.performance.now();
                        return log$B.debug(`download ${e} takes:${u - s}ms`),
                        reporter$1.report("measurement", {
                            metric: "http",
                            value: u - s,
                            extra: e
                        }),
                        this.emit("loadend", {
                            message: `request ${e} load success`
                        }),
                        o(l)
                    } else {
                        const u = `Unable to load the request ${e}`;
                        return this.emit("error", {
                            message: u
                        }),
                        log$B.error(u),
                        a(u)
                    }
            }
            ),
            l.open("GET", e),
            l.send()
        }
        )
    }
}
const http$2 = new Http$2
  , isIndexedDbSupported$1 = ()=>(window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB) !== void 0
  , blobToDataURI$2 = async i=>new Promise((e,t)=>{
    const r = new FileReader;
    r.readAsDataURL(i),
    r.onload = function(n) {
        var o;
        e((o = n.target) == null ? void 0 : o.result)
    }
    ,
    r.onerror = function(n) {
        t(n)
    }
}
)
  , dataURItoBlob$1 = i=>{
    let e;
    i.split(",")[0].indexOf("base64") >= 0 ? e = atob(i.split(",")[1]) : e = unescape(i.split(",")[1]);
    const t = i.split(",")[0].split(":")[1].split(";")[0]
      , r = new Uint8Array(e.length);
    for (let o = 0; o < e.length; o++)
        r[o] = e.charCodeAt(o);
    return new Blob([r],{
        type: t
    })
}
  , DefaultUrlTransformer$1 = async i=>typeof i != "string" ? (console.warn("url transformer error", i),
i) : i.startsWith("blob:") ? i : http$2.get({
    url: i,
    useIndexedDb: !0,
    key: "url"
})
  , log$A = new Logger$1("subSequence")
  , DEFAULT_FRAME_RATE = 30
  , ROOT_MESH_ANIM_PROPERTY = ["scaling", "position", "rotation"]
  , MESH_TAG = "XSubSequence";
class XSpriteManager extends SpriteManager {
    constructor(e, t, r, n, o) {
        super(e, t, r, n, o);
        E(this, "originalPositions");
        this.originalPositions = new Array,
        this.sprites.forEach(a=>{
            this.originalPositions.push(a.position)
        }
        )
    }
    static Parse(e, t, r) {
        const n = new XSpriteManager(e.name,"",e.capacity,{
            width: e.cellWidth,
            height: e.cellHeight
        },t);
        e.texture ? n.texture = Texture.Parse(e.texture, t, r) : e.textureName && (n.texture = new Texture(r + e.textureUrl,t,!0,e.invertY !== void 0 ? e.invertY : !0));
        for (const o of e.sprites) {
            const a = Sprite.Parse(o, n);
            n.originalPositions.push(a.position)
        }
        return n
    }
}
class XSubSequence {
    constructor(e, t, r=DefaultUrlTransformer$1) {
        E(this, "_scene");
        E(this, "_meshGroups");
        E(this, "_animGroup");
        E(this, "_particleGroups");
        E(this, "_materialGroups");
        E(this, "_spriteGroups");
        E(this, "_glowGroups");
        E(this, "_highLightGroups");
        E(this, "_endFrame");
        E(this, "_centerNode");
        E(this, "_rootDir");
        E(this, "_abosoluteUrl");
        E(this, "_name");
        E(this, "_pickable", !1);
        E(this, "urlTransformer");
        E(this, "onLoadedObserverable", new Observable);
        E(this, "onSubSequenceTransformationChangeObservable", new Observable);
        E(this, "onIntersectionObservable", new Observable);
        E(this, "_loaded");
        E(this, "_isStarted");
        E(this, "_isPaused");
        E(this, "_isDisposing", !1);
        E(this, "init", ()=>new Promise((e,t)=>{
            this.urlTransformer(this._abosoluteUrl).then(r=>{
                const n = new XMLHttpRequest;
                n.open("get", r),
                n.send(null),
                n.onload = ()=>{
                    if (n.status == 200) {
                        const o = JSON.parse(n.responseText);
                        this.load(o).then(()=>{
                            this.onLoadedObserverable.notifyObservers(this),
                            this._loaded = !0,
                            e()
                        }
                        , ()=>{
                            t(),
                            log$A.error("subSequence: Load ${jsonBlob} json fail")
                        }
                        )
                    }
                }
                ,
                n.onerror = ()=>{
                    log$A.error("http: Get ${jsonBlob} json fail"),
                    t()
                }
            }
            )
        }
        ));
        E(this, "play", async(e=!0)=>new Promise(t=>{
            if (this._animGroup.isPlaying && this._animGroup.stop(),
            this._particleGroups.forEach(r=>{
                var n;
                ((n = r.emitterNode) == null ? void 0 : n.getClassName()) == "Mesh" && r.emitterNode instanceof Mesh ? r.emitterNode.isEnabled() && r.start() : r.start()
            }
            ),
            this._animGroup.targetedAnimations.length == 0) {
                this.show();
                let r = 0;
                this._spriteGroups.forEach(n=>{
                    n.sprites.forEach(o=>{
                        o.toIndex > r && (r = o.toIndex)
                    }
                    )
                }
                ),
                this._spriteGroups.forEach(n=>{
                    n.sprites.forEach(o=>{
                        o.playAnimation(o.fromIndex, o.toIndex, e, o.delay, ()=>{
                            o.toIndex == r && (this._isPaused = !0,
                            this.hide(),
                            t())
                        }
                        )
                    }
                    )
                }
                )
            } else
                this._animGroup.play(e),
                this._spriteGroups.forEach(r=>{
                    r.sprites.forEach(n=>{
                        n.playAnimation(n.fromIndex, n.toIndex, e, n.delay)
                    }
                    )
                }
                ),
                e ? this._animGroup.onAnimationGroupLoopObservable.addOnce(()=>{
                    t()
                }
                ) : this._animGroup.onAnimationGroupEndObservable.addOnce(()=>{
                    this._spriteGroups.forEach(r=>{
                        r.sprites.forEach(n=>{
                            n.isVisible = !1,
                            n.isPickable = !1,
                            n.stopAnimation()
                        }
                        )
                    }
                    ),
                    t()
                }
                );
            this._isStarted = !0,
            this._isPaused = !1
        }
        ));
        E(this, "stop", ()=>{
            this._animGroup.stop(),
            this._particleGroups.forEach(e=>{
                e.systems.forEach(t=>{
                    t.stop()
                }
                )
            }
            ),
            this._spriteGroups.forEach(e=>{
                e.sprites.forEach(t=>{
                    t.stopAnimation()
                }
                )
            }
            ),
            this._isStarted = !1
        }
        );
        E(this, "clone", (e="Clone")=>{
            const t = new XSubSequence(this._scene,this._abosoluteUrl);
            return t._centerNode.name = e + "_" + this._centerNode.name,
            t._animGroup.name = e + "_" + this._animGroup.name,
            this._meshGroups.forEach(r=>{
                const n = r.clone(e + "_", t._centerNode)
                  , o = n.getChildren(void 0, !1);
                if (o.forEach(a=>{
                    a.setEnabled(!0)
                }
                ),
                o.push(n),
                n) {
                    const a = r.getChildren(void 0, !1);
                    a.push(r),
                    this.animGroup.targetedAnimations.forEach(s=>{
                        if (s.target instanceof Node$2) {
                            const l = a.indexOf(s.target);
                            l != -1 && t._animGroup.addTargetedAnimation(s.animation, o[l])
                        }
                    }
                    )
                }
            }
            ),
            t._loaded = !0,
            t
        }
        );
        E(this, "goToFrame", e=>{
            this._animGroup.start(!0, 1, e, e)
        }
        );
        E(this, "pause", ()=>{
            this._isPaused = !0,
            this._animGroup.pause()
        }
        );
        E(this, "reset", ()=>{
            this._animGroup.reset()
        }
        );
        E(this, "loadTrackToAnim", e=>{
            const t = Array();
            let r = !0;
            e.keyFrame.forEach(o=>{
                if (o.frame > this._endFrame && (this._endFrame = o.frame),
                o.value instanceof Array) {
                    const a = {
                        frame: o.frame,
                        value: new Vector3(0,0,0)
                    }
                      , s = new Vector3(o.value[0],o.value[1],o.value[2]);
                    a.value = s,
                    t.push(a)
                } else
                    t.push(o),
                    r = !1
            }
            ),
            e.loop == null && (e.loop = !1),
            e.index == null && (e.index = 0);
            let n = null;
            if ("blockName"in e) {
                const o = {
                    keyFrame: t,
                    blockName: e.blockName,
                    property: e.property,
                    targetName: e.targetName,
                    index: e.index,
                    loop: e.loop
                };
                n = this.transferTrackToAnim(o, r)
            } else {
                const o = {
                    keyFrame: t,
                    property: e.property,
                    targetName: e.targetName,
                    index: e.index,
                    loop: e.loop
                };
                n = this.transferTrackToAnim(o, r)
            }
            return n
        }
        );
        E(this, "transferTrackToAnim", (e,t)=>{
            let r = null;
            t ? (r = new Animation(e.targetName + "_" + e.property,e.property,DEFAULT_FRAME_RATE,Animation.ANIMATIONTYPE_VECTOR3,Animation.ANIMATIONLOOPMODE_CYCLE),
            r.setKeys(e.keyFrame)) : (r = new Animation(e.targetName + "_" + e.property,e.property,DEFAULT_FRAME_RATE,Animation.ANIMATIONTYPE_FLOAT,Animation.ANIMATIONLOOPMODE_CYCLE),
            r.setKeys(e.keyFrame));
            let n = null;
            return "blockName"in e ? n = {
                animation: r,
                blockName: e.blockName,
                targetName: e.targetName,
                nodeIndex: e.index,
                loop: e.loop
            } : n = {
                animation: r,
                targetName: e.targetName,
                nodeIndex: e.index,
                loop: e.loop
            },
            n
        }
        );
        t.indexOf("./") == 0 && (t = t.slice(2)),
        this._abosoluteUrl = t,
        this._name = t.split("/").slice(-1)[0].split(".")[0].split("_")[1],
        this._rootDir = t.split("/").slice(0, -1).join("/") + "/",
        this._scene = e,
        this._meshGroups = new Map,
        this._animGroup = new AnimationGroup("SubSeqAnim_",this._scene),
        this._particleGroups = new Map,
        this._materialGroups = new Map,
        this._glowGroups = new Map,
        this._highLightGroups = new Map,
        this._spriteGroups = new Map,
        this._endFrame = 0,
        this._centerNode = new TransformNode("__rootSubSeq__",e),
        this._loaded = !1,
        this._isPaused = !0,
        this._isStarted = !1,
        this._centerNode.setEnabled(!1),
        this.urlTransformer = r,
        this._centerNode.onAfterWorldMatrixUpdateObservable.add(()=>{
            this.onSubSequenceTransformationChangeObservable.notifyObservers(this)
        }
        ),
        this._animGroup.onAnimationGroupPlayObservable.add(()=>{
            this._particleGroups.forEach(n=>{
                n.systems.forEach(o=>{
                    o.isStarted() || o.start()
                }
                )
            }
            ),
            this.show()
        }
        ),
        this._animGroup.onAnimationGroupLoopObservable.add(()=>{
            this._particleGroups.forEach(n=>{
                n.systems.forEach(o=>{
                    o.isStarted() || o.start()
                }
                )
            }
            ),
            this.show()
        }
        ),
        this._animGroup.onAnimationGroupEndObservable.add(()=>{
            this.hide()
        }
        )
    }
    dispose() {
        this._isDisposing = !0,
        this._spriteGroups.forEach(e=>{
            e.dispose()
        }
        ),
        this._glowGroups.forEach(e=>{
            e.dispose()
        }
        ),
        this._highLightGroups.forEach(e=>{
            e.dispose()
        }
        ),
        this._particleGroups.forEach(e=>{
            XParticleManager.disposeParticleSysSet(e)
        }
        ),
        this._animGroup.stop(),
        this._animGroup.dispose(),
        this._meshGroups.forEach(e=>{
            e.getChildren(void 0, !1).forEach(t=>{
                var r, n;
                (t.getClassName() === "AbstractMesh" || t.getClassName() === "Mesh") && ((r = t.skeleton) == null || r.dispose(),
                (n = t.material) == null || n.dispose(!0, !0)),
                t.dispose(!0, !0)
            }
            ),
            e.dispose(!1, !0)
        }
        ),
        this._centerNode.dispose(!1, !0),
        this._materialGroups.forEach(e=>{}
        ),
        this._materialGroups.clear(),
        this._spriteGroups.clear(),
        this._glowGroups.clear(),
        this._highLightGroups.clear(),
        this._meshGroups.clear(),
        this._particleGroups.clear(),
        this._loaded = !1
    }
    get animGroup() {
        return this._animGroup
    }
    get name() {
        return this._name
    }
    get path() {
        return this._abosoluteUrl
    }
    get position() {
        return xversePosition2Ue4(this.pos)
    }
    get rotation() {
        return xverseRotation2Ue4(this.rot)
    }
    get scaling() {
        return this.scal
    }
    get pos() {
        return this._centerNode.position
    }
    get rot() {
        return this._centerNode.rotation
    }
    get scal() {
        return this._centerNode.scaling
    }
    get root() {
        return this._centerNode
    }
    get loaded() {
        return this._loaded
    }
    get isPlaying() {
        return this._animGroup ? this._animGroup.isPlaying : this._isStarted && !this._isPaused
    }
    get isStarted() {
        return this._animGroup ? this._animGroup.isStarted : this._isStarted
    }
    get isPickable() {
        return this._pickable
    }
    set isPickable(e) {
        this._meshGroups.forEach(t=>{
            t.getChildMeshes().forEach(r=>{
                r.isPickable = e
            }
            )
        }
        ),
        this._spriteGroups.forEach(t=>{
            t.isPickable = e,
            t.sprites.forEach(r=>{
                r.isPickable = e
            }
            )
        }
        ),
        this._pickable = e
    }
    addAnimation(e) {
        this._animGroup.addTargetedAnimation(e, this._centerNode),
        this._spriteGroups.forEach(t=>{
            t.sprites.forEach(r=>{
                this._animGroup.addTargetedAnimation(e, r)
            }
            )
        }
        )
    }
    setStartFrame(e) {
        this._animGroup.stop(),
        this._animGroup.targetedAnimations.forEach(t=>{
            const r = t.animation.getKeys();
            r.forEach(n=>{
                e + r[0].frame > 0 ? n.frame += e : n.frame -= r[0].frame
            }
            )
        }
        )
    }
    lookAt(e) {
        ue4Position2Xverse(e) && this.root.lookAt(ue4Position2Xverse(e))
    }
    setPosition(e) {
        this.setPositionVector(ue4Position2Xverse(e))
    }
    setPositionVector(e) {
        this._centerNode.position = e,
        this._particleGroups.forEach(t=>{
            t.emitterNode == null || t.emitterNode instanceof Vector3 ? t.emitterNode = e : this._scene.getMeshByName(t.emitterNode.name) || (t.emitterNode = e)
        }
        ),
        this._spriteGroups.forEach(t=>{
            t.sprites.forEach((r,n)=>{
                r.position = e
            }
            )
        }
        )
    }
    setScaling(e) {
        this.setScalingVector(ue4Scaling2Xverse(e))
    }
    setScalingVector(e) {
        var t;
        this._centerNode.scaling = e,
        (t = this._particleGroups) == null || t.forEach(r=>{
            r.systems.forEach(n=>{
                XParticleManager.scalingInPlace(n, e.x)
            }
            )
        }
        ),
        this._spriteGroups.forEach(r=>{
            r.sprites.forEach(n=>{
                n.size *= e.x
            }
            )
        }
        )
    }
    setRotation(e) {
        this.setRotationVector(ue4Rotation2Xverse(e))
    }
    setRotationVector(e) {
        this._centerNode.rotation = e
    }
    hide() {
        this._centerNode.setEnabled(!1),
        this._particleGroups.forEach(e=>{
            e.systems.forEach(t=>{
                t.isStarted() && t.stop()
            }
            )
        }
        ),
        this._spriteGroups.forEach(e=>{
            e.sprites.forEach(t=>{
                t.isVisible = !1
            }
            )
        }
        )
    }
    show() {
        this._centerNode.setEnabled(!0),
        this._centerNode.getChildren().forEach(e=>{
            e.setEnabled(!0),
            e.getChildMeshes().forEach(t=>{
                t.setEnabled(!0)
            }
            )
        }
        ),
        this._particleGroups.forEach(e=>{
            e.systems.forEach(t=>{
                t.start()
            }
            )
        }
        ),
        this._spriteGroups.forEach(e=>{
            e.sprites.forEach(t=>{
                t.isVisible = !0
            }
            )
        }
        )
    }
    get totalFrame() {
        return this._endFrame
    }
    load(e) {
        return new Promise((t,r)=>{
            const n = e.Mesh
              , o = e.Sprite
              , a = e.Material
              , s = e.Glow
              , l = e.HighLight
              , u = e.Particle
              , c = e.MeshTrack
              , h = e.ParticleTrack
              , f = e.MaterialTrack;
            this._animGroup.name += e.Type;
            const d = Date.now();
            this._centerNode.name += e.Type;
            const _ = new Array
              , g = new Array;
            n != null && n.forEach(m=>{
                _.push(this.loadMesh(m))
            }
            ),
            o != null && o.forEach(m=>{
                g.push(this.loadSprite(m))
            }
            ),
            Promise.all(_).then(()=>{
                a != null && a.forEach(m=>{
                    g.push(this.loadMaterial(m))
                }
                ),
                u != null && u.forEach(m=>{
                    g.push(this.loadParticle(m))
                }
                ),
                Promise.all(g).then(()=>{
                    if (this._isDisposing) {
                        const v = Date.now() - d;
                        log$A.info(`subSequence: Load ${e.Type} takes ${v} ms`),
                        t(this);
                        return
                    }
                    if (s != null)
                        for (const v of s)
                            this.loadGlow(v);
                    if (l != null)
                        for (const v of l)
                            this.loadHighLight(v);
                    c != null && c.forEach(v=>{
                        const y = this._meshGroups.get(v.targetName);
                        if (y != null) {
                            const b = this.loadTrackToAnim(v);
                            ROOT_MESH_ANIM_PROPERTY.indexOf(b.animation.targetProperty) == -1 ? y.getChildMeshes().forEach(T=>{
                                b.animation.targetProperty in T && this._animGroup.addTargetedAnimation(b.animation, T)
                            }
                            ) : this._animGroup.addTargetedAnimation(b.animation, y)
                        }
                    }
                    ),
                    h != null && h.forEach(v=>{
                        var C;
                        const y = v.index
                          , b = v.targetName
                          , T = (C = this._particleGroups.get(b)) == null ? void 0 : C.systems[y];
                        if (T != null) {
                            const A = this.loadTrackToAnim(v);
                            this._animGroup.addTargetedAnimation(A.animation, T)
                        }
                    }
                    ),
                    f != null && f.forEach(v=>{
                        const y = this._materialGroups.get(v.targetName);
                        if (y) {
                            const b = y[0];
                            if (b != null)
                                if (b.getBlockByName(v.blockName) != null) {
                                    const T = this.loadTrackToAnim(v);
                                    y == null || y.forEach(C=>{
                                        this._animGroup.addTargetedAnimation(T.animation, C.getBlockByName(v.blockName))
                                    }
                                    )
                                } else
                                    console.error("property " + v.property + "is not in " + b.name)
                        }
                    }
                    );
                    const m = Date.now() - d;
                    log$A.info(`subSequence: Load ${e.Type} takes ${m} ms`),
                    t(this)
                }
                , ()=>{
                    log$A.error(`subSequence: Load ${e.Type} fail`),
                    r()
                }
                )
            }
            , ()=>{
                r()
            }
            )
        }
        )
    }
    loadMesh(e) {
        return new Promise((t,r)=>{
            const n = this._rootDir + e.uri;
            this.urlTransformer(n).then(o=>{
                if (this._isDisposing) {
                    t();
                    return
                }
                SceneLoader.LoadAssetContainer("", o, this._scene, a=>{
                    if (this._isDisposing) {
                        a.removeAllFromScene(),
                        t();
                        return
                    }
                    a.animationGroups.forEach(l=>{
                        l.stop()
                    }
                    ),
                    a.animationGroups.length != 0 && (a.animationGroups.forEach(l=>{
                        l.targetedAnimations.forEach(u=>{
                            this._animGroup.addTargetedAnimation(u.animation, u.target)
                        }
                        ),
                        l.dispose()
                    }
                    ),
                    a.animationGroups = [],
                    a.animations = [],
                    a.materials = []);
                    const s = new TransformNode("__root__" + e.name,this._scene);
                    if (e.uri.split(".")[1] == "glb")
                        a.meshes[0].parent = s;
                    else if (e.uri.split(".")[1] == "obj") {
                        const l = new TransformNode("__root__",this._scene);
                        a.meshes.forEach(u=>{
                            u.parent = l,
                            u.Type = MESH_TAG
                        }
                        ),
                        l.parent = s
                    }
                    s.getChildMeshes().forEach(l=>{
                        e.isPickable != null ? l.isPickable = e.isPickable : l.isPickable = !1,
                        l.xtype = "XSubSequence"
                    }
                    ),
                    this._meshGroups.set(e.name, s),
                    s.parent = this._centerNode,
                    a.addAllToScene(),
                    t()
                }
                , ()=>{}
                , ()=>{
                    log$A.error("subSequence:Load effect mesh fail"),
                    log$A.error(`Effect Mesh ${e.name} load error`),
                    r()
                }
                , ".glb")
            }
            , ()=>{
                log$A.error("http:Get effect mesh fail"),
                log$A.error(`Effect Mesh ${e.name} load error`),
                r()
            }
            )
        }
        )
    }
    loadSprite(e) {
        return new Promise((t,r)=>{
            if (this._isDisposing) {
                t();
                return
            }
            const n = this._rootDir + e.uri;
            if (e.uri !== "") {
                e.name;
                const o = new XMLHttpRequest;
                o.open("get", n),
                o.send(null),
                o.onload = ()=>{
                    if (o.status == 200) {
                        const a = JSON.parse(o.responseText)
                          , s = XSpriteManager.Parse(a, this._scene, this._rootDir);
                        s.sprites.forEach(l=>{
                            l.stopAnimation()
                        }
                        ),
                        this._spriteGroups.set(e.name, s),
                        t()
                    } else
                        log$A.error("subSequence:Load effect sprite fail"),
                        log$A.error(`Effect Sprite ${e.name} load error`),
                        r()
                }
            }
        }
        )
    }
    loadMaterial(e) {
        return new Promise((t,r)=>{
            if (this._isDisposing) {
                t();
                return
            }
            const n = this._rootDir + e.uri;
            if (e.uri !== "") {
                const o = e.name
                  , a = new NodeMaterial(`material_${o}`,this._scene,{
                    emitComments: !1
                });
                a.backFaceCulling = !1,
                this.urlTransformer(n).then(s=>{
                    if (this._isDisposing) {
                        a.dispose(!1, !0, !1),
                        t();
                        return
                    }
                    a.loadAsync(s).then(()=>{
                        if (this._isDisposing) {
                            a.dispose(!0, !0, !1),
                            t();
                            return
                        }
                        a.build(!1);
                        const l = new Array;
                        let u = !1;
                        for (let c = 0; c < e.meshName.length; c++)
                            this._meshGroups.forEach(h=>{
                                h.getChildMeshes().forEach(f=>{
                                    var d;
                                    if (f.name === e.meshName[c]) {
                                        u = !0,
                                        (d = f.material) == null || d.dispose(!0, !0);
                                        const _ = f;
                                        if (_.skeleton == null) {
                                            const g = a;
                                            _.material = g,
                                            l.push(g)
                                        } else if (_.numBoneInfluencers = 4,
                                        _.computeBonesUsingShaders = !0,
                                        c == 0) {
                                            const g = a;
                                            _.material = g,
                                            l.push(g)
                                        } else {
                                            const g = a.clone(`material_${o}` + String(c), !1);
                                            _.material = g,
                                            l.push(g)
                                        }
                                    }
                                }
                                )
                            }
                            );
                        u ? this._materialGroups.set(e.name, l) : a.dispose(!0, !0),
                        t()
                    }
                    , ()=>{
                        log$A.error("http:Get effect Material fail"),
                        log$A.error(`Effect NodeMaterial ${o} load error`),
                        r()
                    }
                    )
                }
                )
            }
        }
        )
    }
    async loadGlow(e) {
        const t = new GlowLayer(e.name,this._scene,{
            blurKernelSize: e.blurKernelSize
        });
        t.intensity = e.intensity,
        e.meshName.forEach(r=>{
            const n = this._scene.getMeshByName(r);
            n != null && t.addIncludedOnlyMesh(n)
        }
        ),
        this._glowGroups.set(e.name, t)
    }
    loadHighLight(e) {
        const t = new HighlightLayer(e.name,this._scene);
        e.meshName.forEach(r=>{
            const n = this._scene.getMeshByName(r);
            if (n != null) {
                const o = new Color3(e.color[0],e.color[1],e.color[2]);
                t.addMesh(n, o)
            }
        }
        ),
        this._highLightGroups.set(e.name, t)
    }
    loadParticle(e) {
        return new Promise((t,r)=>{
            const n = this._rootDir + e.rootDir
              , o = new XParticleManager(this._scene);
            this.urlTransformer(n + e.uri).then(a=>{
                if (this._isDisposing) {
                    t();
                    return
                }
                o.load(n, e.uri, e.name).then(s=>{
                    if (this._isDisposing) {
                        r();
                        return
                    }
                    this._particleGroups.set(e.name, s),
                    t()
                }
                , ()=>{
                    log$A.error(`SubSequence: ${e.name} particle load fail`),
                    r()
                }
                )
            }
            , ()=>{
                log$A.error(`http: ${n + e.uri} load fail`),
                r()
            }
            )
        }
        )
    }
}
const DefaultUrlTransformer = async i=>typeof i != "string" ? (console.warn("url transformer error", i),
i) : i.startsWith("blob:") ? i : http$2.get({
    url: i,
    useIndexedDb: !0,
    key: "url"
});
class XSequence {
    constructor(e, t, r="test", n=DefaultUrlTransformer) {
        E(this, "_scene");
        E(this, "_name");
        E(this, "_subSeqs");
        E(this, "_animGroup");
        E(this, "_targetSubSeqs");
        E(this, "_abosoluteUrl");
        E(this, "_rootDir");
        E(this, "urlTransformer");
        E(this, "init", async()=>new Promise(e=>{
            this.urlTransformer(this._abosoluteUrl).then(t=>{
                const r = new XMLHttpRequest;
                r.open("get", t),
                r.send(null),
                r.onload = ()=>{
                    if (r.status == 200) {
                        const n = JSON.parse(r.responseText);
                        this.load(n).then(()=>{
                            e()
                        }
                        )
                    }
                }
            }
            )
        }
        ));
        E(this, "getRootOfSubSeqs", ()=>{
            const e = new Array;
            return this._subSeqs.forEach(t=>{
                e.push(t.root)
            }
            ),
            e
        }
        );
        E(this, "play", async(e=!0)=>new Promise(t=>{
            this._animGroup.play(e),
            e ? this._animGroup.onAnimationGroupLoopObservable.addOnce(()=>{
                t()
            }
            ) : this._animGroup.onAnimationGroupEndObservable.addOnce(()=>{
                t()
            }
            )
        }
        ));
        E(this, "goToFrame", e=>{
            this._animGroup.goToFrame(e)
        }
        );
        E(this, "hide", ()=>{
            this._subSeqs.forEach(e=>{
                e.hide()
            }
            )
        }
        );
        E(this, "show", ()=>{
            this._subSeqs.forEach(e=>{
                e.show()
            }
            )
        }
        );
        E(this, "pause", ()=>{
            this._animGroup.pause()
        }
        );
        E(this, "reset", ()=>{
            this._animGroup.reset()
        }
        );
        this._scene = e,
        this._abosoluteUrl = t,
        this._rootDir = t.split("/").slice(0, -1).join("/") + "/",
        this._name = r,
        this._subSeqs = new Map,
        this._animGroup = new AnimationGroup("Seq_" + r,e),
        this._targetSubSeqs = new Map,
        this._animGroup.onAnimationGroupPlayObservable.add(()=>{
            this._subSeqs.forEach(o=>{
                o.show()
            }
            )
        }
        ),
        this._animGroup.onAnimationGroupEndObservable.add(()=>{
            this._subSeqs.forEach(o=>{
                o.hide()
            }
            )
        }
        ),
        this.urlTransformer = n
    }
    get animGroup() {
        return this._animGroup
    }
    serialize() {
        const e = {};
        return e.SubSequence = new Array,
        e.TimeLine = new Array,
        this._subSeqs.forEach(t=>{
            const r = {
                name: t.name,
                uri: t.path
            };
            e.SubSequence.push(r);
            const n = this._targetSubSeqs.get(t);
            n && e.TimeLine.push({
                frame: n == null ? void 0 : n.frame,
                position: n.position,
                rotation: n.rotation,
                scaling: n.scaling,
                name: t.name
            })
        }
        ),
        e
    }
    get isPlaying() {
        return this._animGroup.isPlaying
    }
    get isStarted() {
        return this._animGroup.isStarted
    }
    get loaded() {
        let e = !0;
        return this._subSeqs.forEach(t=>{
            e = e && t.loaded
        }
        ),
        e
    }
    dispose() {
        this._subSeqs.forEach(e=>{
            e.dispose()
        }
        ),
        this.animGroup.dispose()
    }
    setFrame(e, t) {
        const r = this._subSeqs.get(e);
        if (r) {
            const n = this._targetSubSeqs.get(r);
            n && (n.frame = t),
            n && this.update(r, n)
        }
    }
    get name() {
        return this._name
    }
    update(e, t) {
        if (t) {
            const r = {
                frame: t.frame,
                scaling: new Vector3(t.scaling[0],t.scaling[1],t.scaling[2]),
                position: new Vector3(t.position[0],t.position[1],t.position[2]),
                rotation: new Vector3(t.rotation[0] / 180 * Math.PI,t.rotation[1] / 180 * Math.PI,t.rotation[2] / 180 * Math.PI),
                name: t.name
            }
              , n = this._subSeqs.get(r.name);
            n && (n.setPositionVector(r.position),
            n.setRotationVector(r.rotation),
            n.setScalingVector(r.scaling),
            n.setStartFrame(r.frame),
            this._targetSubSeqs.set(n, t),
            n.onSubSequenceTransformationChangeObservable.add(()=>{
                const o = this._targetSubSeqs.get(n);
                o && (o.position = [n.pos.x, n.pos.y, n.pos.z]),
                o && (o.rotation = [n.rot.x, n.rot.y, n.rot.z]),
                o && (o.scaling = [n.scal.x, n.scal.y, n.scal.z])
            }
            ))
        }
    }
    load(e) {
        return new Promise((t,r)=>{
            const n = new Array
              , o = e.SubSequence
              , a = e.TimeLine;
            for (const s of o) {
                s.uri.indexOf("./") == 0 && (s.uri = s.uri.slice(2));
                const l = new XSubSequence(this._scene,this._rootDir + s.uri,this.urlTransformer);
                this._subSeqs.set(s.name, l),
                n.push(l.init())
            }
            Promise.all(n).then(()=>{
                a.forEach(s=>{
                    const l = this._subSeqs.get(s.name);
                    l && this.update(l, s)
                }
                ),
                this._subSeqs.forEach(s=>{
                    s.animGroup.targetedAnimations.forEach(l=>{
                        this._animGroup.addTargetedAnimation(l.animation, l.target)
                    }
                    )
                }
                ),
                t()
            }
            , ()=>{
                r()
            }
            )
        }
        )
    }
}
const log$z = new Logger$1("XStaticMesh");
class XStaticMesh {
    constructor({id: e, mesh: t, group: r="default", lod: n=0, xtype: o=EMeshType.XStaticMesh, skinInfo: a="default", url: s=""}) {
        E(this, "_mesh");
        E(this, "_id", "-1");
        E(this, "_group");
        E(this, "_lod");
        E(this, "_isMoving", !1);
        E(this, "_isRotating", !1);
        E(this, "_isVisible", !0);
        E(this, "_skinInfo");
        E(this, "setVisibility", (e,t)=>{
            Array.isArray(e) ? e.forEach(r=>{
                this.setVisibility(r, t)
            }
            ) : e.isAnInstance || (e.visibility = t)
        }
        );
        E(this, "setPickable", (e,t)=>{
            Array.isArray(e) ? e.forEach(r=>{
                this.setPickable(r, t)
            }
            ) : ("isPickable"in e && (e.isPickable = t),
            e.setEnabled(t))
        }
        );
        E(this, "hide", ()=>{
            var e;
            this._isVisible = !1,
            this.mesh && this.setVisibility(this.mesh, 0),
            this.mesh && this.setPickable(this.mesh, !1),
            (e = this.mesh) == null || e.getChildMeshes().forEach(t=>{
                this.setVisibility(t, 0),
                this.setPickable(t, !1)
            }
            )
        }
        );
        E(this, "show", ()=>{
            var e;
            this._isVisible = !0,
            this.mesh && this.setVisibility(this.mesh, 1),
            this.mesh && this.setPickable(this.mesh, !0),
            (e = this.mesh) == null || e.getChildMeshes().forEach(t=>{
                this.setVisibility(t, 1),
                this.setPickable(t, !0)
            }
            )
        }
        );
        E(this, "attachToAvatar", (e,t={
            x: 0,
            y: .5,
            z: 0
        },r={
            yaw: 0,
            pitch: 0,
            roll: 0
        },n={
            x: .35,
            y: .35,
            z: .35
        })=>{
            const o = ue4Scaling2Xverse(n)
              , a = ue4Rotation2Xverse(r)
              , s = ue4Position2Xverse(t)
              , l = this._mesh;
            e && l ? (e.setParent(l),
            e.position = s,
            e.rotation = a,
            e.scaling = o) : log$z.error("[Engine] avatar or attachment not found!")
        }
        );
        E(this, "detachFromAvatar", (e,t=!1)=>{
            this._mesh && e ? this._mesh.removeChild(e) : log$z.error("[Engine] avatar not found!")
        }
        );
        this._id = e,
        this._mesh = t,
        this._group = r,
        this._lod = n,
        this._skinInfo = a,
        this.unallowMove(),
        this._mesh.xtype = o,
        this._mesh.xid = e,
        this._mesh.xgroup = this._group,
        this._mesh.xlod = this._lod,
        this._mesh.xskinInfo = this._skinInfo,
        this._mesh.xurl = s
    }
    get mesh() {
        return this._mesh
    }
    get position() {
        var o;
        if (!this._mesh)
            return null;
        const {x: e, y: t, z: r} = (o = this._mesh) == null ? void 0 : o.position;
        return xversePosition2Ue4({
            x: e,
            y: t,
            z: r
        })
    }
    get id() {
        return this._id
    }
    get group() {
        return this._group
    }
    get isMoving() {
        return this._isMoving
    }
    get isVisible() {
        return this._isVisible
    }
    get isRotating() {
        return this._isRotating
    }
    get skinInfo() {
        return this._skinInfo
    }
    allowMove() {
        this._mesh != null && (this._mesh.getChildMeshes().forEach(e=>{
            e.unfreezeWorldMatrix()
        }
        ),
        this._mesh.unfreezeWorldMatrix())
    }
    unallowMove() {
        this._mesh != null && (this._mesh.getChildMeshes().forEach(e=>{
            e.freezeWorldMatrix()
        }
        ),
        this._mesh.freezeWorldMatrix())
    }
    getID() {
        return this._id
    }
    setPosition(e) {
        if (this._mesh) {
            const t = ue4Position2Xverse(e);
            this._mesh.position = t
        } else
            log$z.error("[Engine] no root for positioning")
    }
    setRotation(e) {
        const t = ue4Rotation2Xverse_mesh(e);
        this._mesh ? this._mesh.rotation = t : log$z.error("[Engine] no root for rotating")
    }
    setScale(e) {
        this._mesh ? this._mesh.scaling = new Vector3(e,e,-e) : log$z.error("[Engine] no root for scaling")
    }
    disableAvatar() {
        var e;
        (e = this._mesh) == null || e.setEnabled(!1)
    }
    enableAvatar() {
        var e;
        (e = this._mesh) == null || e.setEnabled(!0)
    }
    togglePickable(e) {
        var t;
        (t = this.mesh) == null || t.getChildMeshes().forEach(r=>{
            "instances"in r && "isPickable"in r && (r.isPickable = e)
        }
        ),
        this.mesh != null && "isPickable"in this.mesh && (this.mesh.isPickable = e)
    }
    setMaterial(e) {
        var t;
        (t = this.mesh) == null || t.getChildMeshes().forEach(r=>{
            "instances"in r && "material"in r && (r.material = e)
        }
        ),
        this.mesh != null && "material"in this.mesh && (this.mesh.material = e)
    }
    dispose(e=!1, t=!1) {
        !this.mesh.isDisposed() && this.mesh.dispose(e, t)
    }
}
class Timeout$1 {
    constructor(e, t, r=!0) {
        E(this, "_fn");
        E(this, "_delay");
        E(this, "_timeout");
        this._fn = e,
        this._delay = t,
        r && this.start()
    }
    get delay() {
        return this._delay
    }
    get isSet() {
        return !!this._timeout
    }
    setDelay(e) {
        this._delay = e
    }
    start() {
        this.isSet || (this._timeout = window.setTimeout(()=>{
            const e = this._fn;
            this.clear(),
            e()
        }
        , this._delay))
    }
    clear() {
        window.clearTimeout(this._timeout),
        this._timeout = void 0
    }
    reset() {
        this.clear(),
        this.start()
    }
}
class Stream$1 {
    constructor(e) {
        E(this, "el");
        E(this, "_streamPlayTimer", null);
        E(this, "play", ()=>new Promise((e,t)=>{
            this._streamPlayTimer = new Timeout$1(()=>{
                t("Stream play timeout")
            }
            ,5e3),
            this.el && this.el.play().then(()=>{
                var r;
                e(),
                (r = this._streamPlayTimer) == null || r.clear()
            }
            ).catch(r=>{
                var n;
                t("Media Failed to autoplay"),
                (n = this._streamPlayTimer) == null || n.clear()
            }
            )
        }
        ));
        if (!e) {
            this.el = this.createVideoElement();
            return
        }
        this.el = e
    }
    createVideoElement() {
        const e = document.createElement("video");
        return e.muted = !0,
        e.autoplay = !1,
        e.playsInline = !0,
        e.width = 360,
        e.height = 640,
        e.setAttribute("autostart", "false"),
        e.setAttribute("controls", "controls"),
        e.setAttribute("muted", "true"),
        e.setAttribute("preload", "auto"),
        e.setAttribute("hidden", "hidden"),
        document.body.appendChild(e),
        e
    }
}
var tvFragment = `precision highp float;
 
varying vec2 vUV;
uniform float tvWidthHeightScale;
uniform float mvWidthHeightScale;

uniform float bforceforceKeepContent;

 
uniform sampler2D texture_video; 

// \u7B49\u6BD4\u4F8B\u7F29\u653E\u753B\u9762\u5360\u6EE1\u5C4F\u5E55\uFF0C\u5B58\u5728\u5185\u5BB9\u7684\u4E22\u5931
vec2 equalScalingFitTvSize(vec2 uv, float tvWidthHeightScale, float mvWidthHeightScale)
{
    if( tvWidthHeightScale > mvWidthHeightScale )
    {
        float scale = mvWidthHeightScale/tvWidthHeightScale;
        uv.y = (uv.y - 0.5) * scale + 0.5;
    }else if( tvWidthHeightScale < mvWidthHeightScale )
    {
        float scale = tvWidthHeightScale/mvWidthHeightScale;
        uv.x = (uv.x - 0.5) * scale + 0.5;
    }
    return vec2( uv.x , uv.y);
}

// \u5F3A\u5236\u4FDD\u7559\u753B\u9762\u5185\u5BB9\uFF08\u5E26\u6709\u9ED1\u8FB9\uFF09
vec2 forceKeepContent(vec2 uv, float tvWidthHeightScale, float mvWidthHeightScale)
{
    if( tvWidthHeightScale > mvWidthHeightScale )
    {
        float scale = mvWidthHeightScale/tvWidthHeightScale;
        uv.x = (uv.x - 0.5) / scale + 0.5;
    }else if( tvWidthHeightScale < mvWidthHeightScale )
    {
        float scale = tvWidthHeightScale/mvWidthHeightScale;
        uv.y = (uv.y - 0.5) / scale + 0.5;
    }
    return vec2( uv.x , uv.y);
}

void main()
{     
    vec2 uv = vUV;
    vec3 rgb; 
    vec3 color = vec3(0,0,0);

    // \u4E00\u65E6\u8BBE\u7F6E\u4E86mvWidthHeightScale\uFF0C\u5C31\u4F1A\u89E6\u53D1\u7B49\u6BD4\u4F8B\u7F29\u653Eor\u5F3A\u5236\u4FDD\u5185\u5BB9
    if(tvWidthHeightScale > 0.0 && mvWidthHeightScale > 0.0)
    {
        if(bforceforceKeepContent > 0.0){
            uv = forceKeepContent(uv, tvWidthHeightScale, mvWidthHeightScale); 
        }else{
            uv = equalScalingFitTvSize(uv, tvWidthHeightScale, mvWidthHeightScale); 
        }
    }
    
    color = texture2D(texture_video, uv).rgb;
 
    if( uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0 )
    {
        color = vec3(0,0,0);
    }
    gl_FragColor = vec4(color, 1.0);  
}

`
  , tvVertex = `precision highp float;
 
varying vec2 vUV;

attribute vec2 uv;
attribute vec3 position;
 
uniform mat4 view;
uniform mat4 projection; 
uniform mat4 world; 

void main()
{  
    vUV = uv; 
    gl_Position = projection * view * world * vec4(position , 1.0); 
}
`;
const log$y = new Logger$1("XTelevision");
var EFitMode = (i=>(i.fill = "fill",
i.contain = "contain",
i.cover = "cover",
i))(EFitMode || {});
class XTelevision {
    constructor(e, t, r, n) {
        E(this, "videoElement");
        E(this, "meshPath");
        E(this, "scene");
        E(this, "tvMeshs", []);
        E(this, "vAng");
        E(this, "videoMat");
        E(this, "videoTexture");
        E(this, "widthHeightScale");
        E(this, "fitMode");
        E(this, "_scenemanager");
        if (this.scene = e,
        this.meshPath = t,
        this._scenemanager = r,
        n != null) {
            const {vAng: o=0, widthHeightScale: a=-1, fitMode: s="fill"} = n;
            this.vAng = o,
            this.widthHeightScale = a,
            this.fitMode = s
        }
    }
    set tvWidthHeightscale(e) {
        this.widthHeightScale = e
    }
    get tvWidthHeightscale() {
        return this.widthHeightScale
    }
    get tvFitMode() {
        return this.fitMode
    }
    set tvFitMode(e) {
        this.fitMode = e
    }
    setPlaySpeed(e) {
        this.videoElement != null && (this.videoElement.playbackRate = e)
    }
    getMesh() {
        return this.tvMeshs
    }
    createElement(e, t=!1) {
        const n = new Stream$1().el;
        return n.loop = t,
        n.autoplay = !0,
        n.src = e,
        n
    }
    async setUrl(e) {
        const {url: t, isLive: r=!1, poster: n=null, bLoop: o=!1, bMuted: a=!0} = e || {};
        if (typeof t != "string")
            return log$y.error("[Engine] Tv setUrl Error, url must be string: ", t),
            Promise.reject(new XTvMediaUrlError("[Engine] url must be string"));
        if (this.videoElement) {
            this.videoElement.src = t,
            n != null && n.length > 0 && (this.videoElement.poster = n);
            const l = this.play();
            return "bMuted"in e && l !== void 0 && l.then(()=>{
                this.videoElement.muted = a
            }
            ),
            this.videoElement.addEventListener("loadedmetadata", u=>{
                this.videoElement.videoWidth > 0 ? this.videoMat.setFloat("mvWidthHeightScale", this.videoElement.videoWidth / this.videoElement.videoHeight) : this.videoMat.setFloat("mvWidthHeightScale", 16 / 9)
            }
            ),
            Promise.resolve(this)
        }
        const s = this.createElement(t, o);
        return n != null && n.length > 0 && (s.poster = n),
        this.setVideo(s, r).then(()=>{
            var u;
            const l = (u = this.videoElement) == null ? void 0 : u.play();
            "bMuted"in e && l !== void 0 && l.then(()=>{
                this.videoElement.muted = a
            }
            )
        }
        ).catch(l=>{
            log$y.error("[Engine] setUrl  error! " + l),
            new XTvMediaUrlError("[Engine] setUrl  error! " + l)
        }
        )
    }
    setCurrentTime(e) {
        if (!this.videoElement) {
            log$y.warn("[Engine] The television is not been initialize succesfully");
            return
        }
        const {currentTime: t} = e;
        if (typeof t != "number") {
            log$y.warn("[Engine] video currentTime must be number");
            return
        }
        this.videoElement.currentTime = t / 1e3
    }
    getCurrentTime() {
        return this.videoElement ? this.videoElement.currentTime * 1e3 : -1
    }
    play() {
        return log$y.info("[Engine] Play television"),
        this.toggle(!0),
        this.videoElement ? this.videoElement.play() : Promise.resolve()
    }
    pause() {
        var e;
        return log$y.info("[Engine] Pause television"),
        (e = this.videoElement) == null ? void 0 : e.pause()
    }
    stop() {
        log$y.info("[Engine] Stop television"),
        this.pause(),
        setTimeout(()=>{
            this.setCurrentTime({
                currentTime: 0
            })
        }
        ),
        this.toggle(!1)
    }
    toggle(e) {
        log$y.info(`[Engine] Set Tv visibility = ${e}`);
        for (let t = 0; t < this.tvMeshs.length; ++t)
            e == !0 ? this.tvMeshs[t].show() : this.tvMeshs[t].hide()
    }
    getVideoMat() {
        return this.videoMat
    }
    changeTvFitMode() {
        this.fitMode == "contain" ? (this.widthHeightScale < 0 && (this.widthHeightScale = 2.4),
        this.videoMat.setFloat("tvWidthHeightScale", this.widthHeightScale),
        this.videoMat.setFloat("bforceforceKeepContent", 1)) : this.fitMode == "cover" ? (this.widthHeightScale < 0 && (this.widthHeightScale = this.calWidthHeightScale()),
        this.videoMat.setFloat("tvWidthHeightScale", this.widthHeightScale),
        this.videoMat.setFloat("bforceforceKeepContent", -1)) : this.videoMat.setFloat("tvWidthHeightScale", -1)
    }
    async setVideo(e, t=!1, r=!0) {
        return this.tvMeshs.length != 0 ? (log$y.warn(`[Engine] Set Video. length!=0, mesh: ${this.meshPath}, src: ${e.src}`),
        new Promise((n,o)=>{
            if (!(e instanceof HTMLVideoElement))
                return log$y.error("[Engine] Error, param of setVideo must be a HTMLVideoElement"),
                o(new XTvVideoElementError("[Engine] param of setVideo must be a HTMLVideoElement"));
            this.videoElement = e,
            r == !1 && (t == !1 || checkOS().isIOS) && e.crossOrigin !== "anonymous" && (e.crossOrigin = "anonymous",
            e.load()),
            this.videoElement.addEventListener("loadedmetadata", a=>{
                this.videoElement.videoWidth > 0 ? this.videoMat.setFloat("mvWidthHeightScale", this.videoElement.videoWidth / this.videoElement.videoHeight) : this.videoMat.setFloat("mvWidthHeightScale", 16 / 9)
            }
            ),
            this.videoTexture.updateURL(this.videoElement.src),
            n(this)
        }
        )) : (log$y.warn(`[Engine] Set Video. length==0, mesh: ${this.meshPath}, src: ${e.src}`),
        this.meshPath == "" ? (log$y.error("[Engine] Error, television meshPath is empty."),
        Promise.reject(new XTvVideoElementError("[Engine] Error, television meshPath is empty."))) : this._scenemanager.urlTransformer(this.meshPath).then(n=>new Promise((o,a)=>e instanceof HTMLVideoElement ? (this.videoElement = e,
        r == !1 && (t == !1 || checkOS().isIOS) && e.crossOrigin !== "anonymous" && (e.crossOrigin = "anonymous",
        e.load()),
        SceneLoader.LoadAssetContainerAsync("", n, this.scene, null, ".glb").then(s=>{
            for (let u = s.materials.length - 1; u >= 0; --u)
                s.materials[u].dispose();
            const l = [];
            this.videoTexture = new VideoTexture("videoTex_" + Date.now(),e,this.scene,!1,!0,void 0,{
                autoPlay: !0,
                autoUpdateTexture: !0,
                muted: !0
            }),
            this.videoTexture.vAng = this.vAng,
            this.videoMat = new ShaderMaterial("videoMat_" + Date.now(),this.scene,{
                vertexSource: tvVertex,
                fragmentSource: tvFragment
            },{
                attributes: ["uv", "position"],
                uniforms: ["view", "projection", "worldViewProjection", "world"]
            }),
            this.videoMat.setTexture("texture_video", this.videoTexture),
            this.videoMat.setFloat("tvWidthHeightScale", -1),
            this.videoMat.setFloat("mvWidthHeightScale", 16 / 9),
            this.videoMat.setFloat("bforceforceKeepContent", -1),
            this.videoMat.backFaceCulling = !1,
            this.videoMat.sideOrientation = Mesh.FRONTSIDE,
            this.videoElement.addEventListener("loadedmetadata", u=>{
                this.videoElement.videoWidth > 0 ? this.videoMat.setFloat("mvWidthHeightScale", this.videoElement.videoWidth / this.videoElement.videoHeight) : this.videoMat.setFloat("mvWidthHeightScale", 16 / 9)
            }
            );
            for (let u = 0; u < s.meshes.length; ++u)
                s.meshes[u].visibility = 1,
                s.meshes[u].isPickable = !0,
                s.meshes[u].checkCollisions = !1,
                s.meshes[u].material = this.videoMat,
                "hasVertexAlpha"in s.meshes[u] && (s.meshes[u].hasVertexAlpha = !1),
                this.scene.addMesh(s.meshes[u]),
                l.push(new XStaticMesh({
                    id: s.meshes[u].id,
                    mesh: s.meshes[u],
                    xtype: EMeshType.Tv
                }));
            this.changeTvFitMode(),
            this.tvMeshs = l,
            this.toggle(!0),
            o(this)
        }
        ).catch(s=>{
            log$y.error("[Engine] setVideo: create Tv by input mesh error! " + s),
            a(new XTvModelError("[Engine] setVideo: create Tv by input mesh error! " + s))
        }
        )) : a(new XTvVideoElementError("[Engine] param of setVideo must be a HTMLVideoElement")))))
    }
    async setSameVideo(e, t="") {
        return e == null || e == null ? (log$y.error("[Engine] setSameVideo: input material is null or undefined "),
        Promise.reject(new XTvModelError("[Engine] setSameVideo input material is null or undefined !"))) : this.tvMeshs.length != 0 && t == "" ? (log$y.warn(`[Engine] Set mirror video. length!=0, mesh: ${this.meshPath}`),
        new Promise((r,n)=>{
            try {
                this.videoMat = e,
                this.tvMeshs.forEach(o=>{
                    o.setMaterial(e)
                }
                ),
                this.changeTvFitMode(),
                r(this)
            } catch (o) {
                log$y.error("[Engine] setSameVideo: create Tv by input mesh error! " + o),
                n(new XTvModelError("[Engine] create Tv by input mesh error! " + o))
            }
        }
        )) : (t != "" && (this.meshPath = t,
        this.widthHeightScale = -1),
        this.meshPath == "" ? (log$y.error("[Engine] Error, setSameVideo television meshPath is empty."),
        Promise.reject(new XTvVideoElementError("[Engine] Error, setSameVideo television meshPath is empty."))) : (log$y.warn(`[Engine] Set mirror video. length==0, mesh: ${this.meshPath}`),
        this._scenemanager.urlTransformer(this.meshPath).then(r=>new Promise((n,o)=>(this.videoMat = e,
        e != null && e.getActiveTextures()[0] && (this.videoElement = e == null ? void 0 : e.getActiveTextures()[0].video),
        SceneLoader.LoadAssetContainerAsync("", r, this.scene, null, ".glb").then(a=>{
            for (let l = a.materials.length - 1; l >= 0; --l)
                a.materials[l].dispose();
            const s = [];
            for (let l = 0; l < a.meshes.length; ++l)
                a.meshes[l].visibility = 0,
                a.meshes[l].isPickable = !0,
                a.meshes[l].checkCollisions = !1,
                a.meshes[l].material = this.videoMat,
                "hasVertexAlpha"in a.meshes[l] && (a.meshes[l].hasVertexAlpha = !1),
                this.scene.addMesh(a.meshes[l]),
                s.push(new XStaticMesh({
                    id: a.meshes[l].id,
                    mesh: a.meshes[l],
                    xtype: EMeshType.Tv
                }));
            t != "" && this.cleanTv(!1, !1),
            this.tvMeshs = s,
            this.changeTvFitMode(),
            n(this)
        }
        ).catch(a=>{
            log$y.error("[Engine] setSameVideo: create Tv by input mesh error! " + a),
            o(new XTvModelError("[Engine] create Tv by input mesh error! " + a))
        }
        ))))))
    }
    async changeTvModel(e="") {
        return e != "" && (this.meshPath = e,
        this.widthHeightScale = -1),
        this.meshPath == "" ? (log$y.error("[Engine] Error,changeTvModel television meshPath is empty."),
        Promise.reject(new XTvVideoElementError("[Engine] Error, changeTvModel television meshPath is empty."))) : this.videoMat == null || this.videoMat == null ? (log$y.error("[Engine] changeTvModel: videoMat is null or undefined! "),
        Promise.reject(new XTvModelError("[Engine] changeTvModel: videoMat is null or undefined!"))) : this._scenemanager.urlTransformer(this.meshPath).then(t=>new Promise((r,n)=>SceneLoader.LoadAssetContainerAsync("", t, this.scene, null, ".glb").then(o=>{
            for (let s = o.materials.length - 1; s >= 0; --s)
                o.materials[s].dispose();
            const a = [];
            for (let s = 0; s < o.meshes.length; ++s)
                o.meshes[s].visibility = 0,
                o.meshes[s].isPickable = !0,
                o.meshes[s].checkCollisions = !1,
                o.meshes[s].material = this.videoMat,
                "hasVertexAlpha"in o.meshes[s] && (o.meshes[s].hasVertexAlpha = !1),
                this.scene.addMesh(o.meshes[s]),
                a.push(new XStaticMesh({
                    id: o.meshes[s].id,
                    mesh: o.meshes[s],
                    xtype: EMeshType.Tv
                }));
            e != "" && this.cleanTv(!1, !1),
            this.tvMeshs = a,
            this.changeTvFitMode(),
            r(this)
        }
        ).catch(o=>{
            log$y.error("[Engine] changeTvModel: create Tv by input mesh error! " + o),
            n(new XTvModelError("[Engine] changeTvModel: create Tv by input mesh error! " + o))
        }
        )))
    }
    calWidthHeightScale() {
        const e = [1e5, 1e5, 1e5]
          , t = [-1e5, -1e5, -1e5];
        for (let a = 0; a < this.tvMeshs.length; ++a)
            if (this.tvMeshs[a].mesh.name != "__root__") {
                const s = this.tvMeshs[a].mesh.getBoundingInfo().boundingBox.vectorsWorld;
                for (let l = 0; l < s.length; ++l)
                    e[0] > s[l].x && (e[0] = s[l].x),
                    e[1] > s[l].y && (e[1] = s[l].y),
                    e[2] > s[l].z && (e[2] = s[l].z),
                    t[0] < s[l].x && (t[0] = s[l].x),
                    t[1] < s[l].y && (t[1] = s[l].y),
                    t[2] < s[l].z && (t[2] = s[l].z);
                break
            }
        const r = t[0] - e[0]
          , n = t[1] - e[1]
          , o = t[2] - e[2];
        return Math.sqrt(r * r + o * o) / Math.abs(n)
    }
    cleanTv(e=!1, t=!0) {
        log$y.warn("[Engine] cleanTV");
        for (let r = 0; r < this.tvMeshs.length; ++r)
            this.tvMeshs[r].dispose(e, t);
        this.tvMeshs = [],
        this.meshPath = ""
    }
}
class XStats {
    constructor(e) {
        E(this, "scene");
        E(this, "sceneInstrumentation");
        E(this, "engineInstrumentation");
        E(this, "caps");
        E(this, "engine");
        E(this, "_canvas");
        E(this, "_osversion");
        E(this, "_scenemanager");
        this._scenemanager = e,
        this.scene = e.Scene,
        this._canvas = e.canvas,
        this.initSceneInstrument()
    }
    initSceneInstrument() {
        this.sceneInstrumentation = new SceneInstrumentation(this.scene),
        this.sceneInstrumentation.captureCameraRenderTime = !0,
        this.sceneInstrumentation.captureActiveMeshesEvaluationTime = !0,
        this.sceneInstrumentation.captureRenderTargetsRenderTime = !0,
        this.sceneInstrumentation.captureFrameTime = !0,
        this.sceneInstrumentation.captureRenderTime = !0,
        this.sceneInstrumentation.captureInterFrameTime = !0,
        this.sceneInstrumentation.captureParticlesRenderTime = !0,
        this.sceneInstrumentation.captureSpritesRenderTime = !0,
        this.sceneInstrumentation.capturePhysicsTime = !0,
        this.sceneInstrumentation.captureAnimationsTime = !0,
        this.engineInstrumentation = new EngineInstrumentation(this.scene.getEngine()),
        this.caps = this.scene.getEngine().getCaps(),
        this.engine = this.scene.getEngine(),
        this._osversion = this.osVersion()
    }
    getFrameTimeCounter() {
        return this.sceneInstrumentation.frameTimeCounter.current
    }
    getInterFrameTimeCounter() {
        return this.sceneInstrumentation.interFrameTimeCounter.current
    }
    getActiveMeshEvaluationTime() {
        return this.sceneInstrumentation.activeMeshesEvaluationTimeCounter.current
    }
    getDrawCall() {
        return this.sceneInstrumentation.drawCallsCounter.current
    }
    getDrawCallTime() {
        return this.sceneInstrumentation.renderTimeCounter.current
    }
    getAnimationTime() {
        return this.sceneInstrumentation.animationsTimeCounter.current
    }
    getActiveMesh() {
        return this.scene.getActiveMeshes().length
    }
    getActiveFaces() {
        return Math.round(this.scene.getActiveIndices() / 3)
    }
    getActiveBones() {
        return this.scene.getActiveBones()
    }
    getActiveAnimation() {
        return this.scene._activeAnimatables.length
    }
    getActiveParticles() {
        return this.scene.getActiveParticles()
    }
    getTotalMaterials() {
        return this.scene.materials.length
    }
    getTotalTextures() {
        return this.scene.textures.length
    }
    getTotalGeometries() {
        return this.scene.geometries.length
    }
    getTotalMeshes() {
        return this.scene.meshes.length
    }
    getCameraRenderTime() {
        return this.sceneInstrumentation.cameraRenderTimeCounter.current
    }
    getTotalRootNodes() {
        return this.scene.rootNodes.length
    }
    getRenderTargetRenderTime() {
        const e = this.getDrawCallTime()
          , t = this.getActiveMeshEvaluationTime()
          , r = this.getCameraRenderTime() - (t + e);
        return this.getRTT1Time() + r
    }
    getRegisterBeforeRenderTime() {
        return this.sceneInstrumentation.registerBeforeTimeCounter.current
    }
    getRegisterAfterRenderTime() {
        return this.sceneInstrumentation.registerAfterTimeCounter.current
    }
    getRTT1Time() {
        return this.sceneInstrumentation.getRTT1TimeCounter.current
    }
    getRegisterBeforeRenderObserverLength() {
        return this.scene.onBeforeRenderObservable.observers.length
    }
    getRegisterAfterRenderObserverLength() {
        return this.scene.onAfterRenderObservable.observers.length
    }
    getTotalMeshByType() {
        const e = new Map;
        return this.scene.meshes.forEach(t=>{
            e.has(t.xtype) ? e.set(t.xtype, e.get(t.xtype) + 1) : e.set(t.xtype, 1)
        }
        ),
        e
    }
    getHardwareRenderInfo() {
        return {
            maxTexturesUnits: this.caps.maxTexturesImageUnits,
            maxVertexTextureImageUnits: this.caps.maxVertexTextureImageUnits,
            maxCombinedTexturesImageUnits: this.caps.maxCombinedTexturesImageUnits,
            maxTextureSize: this.caps.maxTextureSize,
            maxSamples: this.caps.maxSamples,
            maxCubemapTextureSize: this.caps.maxCubemapTextureSize,
            maxRenderTextureSize: this.caps.maxRenderTextureSize,
            maxVertexAttribs: this.caps.maxVertexAttribs,
            maxVaryingVectors: this.caps.maxVaryingVectors,
            maxVertexUniformVectors: this.caps.maxVertexUniformVectors,
            maxFragmentUniformVectors: this.caps.maxFragmentUniformVectors,
            standardDerivatives: this.caps.standardDerivatives,
            supportTextureCompress: {
                s3tc: this.caps.s3tc !== void 0,
                s3tc_srgb: this.caps.s3tc_srgb !== void 0,
                pvrtc: this.caps.pvrtc !== void 0,
                etc1: this.caps.etc1 !== void 0,
                etc2: this.caps.etc2 !== void 0,
                astc: this.caps.astc !== void 0,
                bptc: this.caps.bptc !== void 0
            },
            textureFloat: this.caps.textureFloat,
            vertexArrayObject: this.caps.vertexArrayObject,
            textureAnisotropicFilterExtension: this.caps.textureAnisotropicFilterExtension !== void 0,
            maxAnisotropy: this.caps.maxAnisotropy,
            instancedArrays: this.caps.instancedArrays,
            uintIndices: this.caps.uintIndices,
            highPrecisionShaders: this.caps.highPrecisionShaderSupported,
            fragmentDepth: this.caps.fragmentDepthSupported,
            textureFloatLinearFiltering: this.caps.textureFloatLinearFiltering,
            renderToTextureFloat: this.caps.textureFloatRender,
            textureHalfFloat: this.caps.textureHalfFloat,
            textureHalfFloatLinearFiltering: this.caps.textureHalfFloatLinearFiltering,
            textureHalfFloatRender: this.caps.textureHalfFloatRender,
            textureLOD: this.caps.textureLOD,
            drawBuffersExtension: this.caps.drawBuffersExtension,
            depthTextureExtension: this.caps.depthTextureExtension,
            colorBufferFloat: this.caps.colorBufferFloat,
            supportTimerQuery: this.caps.timerQuery !== void 0,
            canUseTimestampForTimerQuery: this.caps.canUseTimestampForTimerQuery,
            supportOcclusionQuery: this.caps.supportOcclusionQuery,
            multiview: this.caps.multiview,
            oculusMultiview: this.caps.oculusMultiview,
            maxMSAASamples: this.caps.maxMSAASamples,
            blendMinMax: this.caps.blendMinMax,
            canUseGLInstanceID: this.caps.canUseGLInstanceID,
            canUseGLVertexID: this.caps.canUseGLVertexID,
            supportComputeShaders: this.caps.supportComputeShaders,
            supportSRGBBuffers: this.caps.supportSRGBBuffers,
            supportStencil: this.engine.isStencilEnable
        }
    }
    getSystemInfo() {
        return {
            resolution: "real: " + this.engine.getRenderWidth() + "x" + this.engine.getRenderHeight() + "	 cavs: " + this._canvas.clientWidth + "x" + this._canvas.clientHeight,
            hardwareScalingLevel: this.engine.getHardwareScalingLevel().toFixed(2).toString() + "_" + this._scenemanager.initEngineScaleNumber.toFixed(2).toString(),
            driver: this.engine.getGlInfo().renderer,
            vender: this.engine.getGlInfo().vendor,
            version: this.engine.getGlInfo().version,
            os: this._osversion
        }
    }
    getFps() {
        const e = this.sceneInstrumentation.frameTimeCounter.lastSecAverage
          , t = this.sceneInstrumentation.interFrameTimeCounter.lastSecAverage;
        return 1e3 / (e + t)
    }
    osVersion() {
        const e = window.navigator.userAgent;
        let t;
        return /iphone|ipad|ipod/gi.test(e) ? t = e.match(/OS (\d+)_(\d+)_?(\d+)?/) : /android/gi.test(e) && (t = e.match(/Android (\d+)/)),
        t != null && t.length > 0 ? t[0] : null
    }
}
class RunTimeArray {
    constructor() {
        E(this, "circularData");
        this.circularData = []
    }
    add(e) {
        this.circularData.length > 1e3 && this.circularData.shift(),
        this.circularData.push(e)
    }
    getAvg() {
        let e = 0;
        for (let t = 0; t < this.circularData.length; t++)
            e += this.circularData[t];
        return {
            sum: e,
            avg: e / this.circularData.length || 0
        }
    }
    getMax() {
        let e = 0;
        for (let t = 0; t < this.circularData.length; t++)
            e < this.circularData[t] && (e = this.circularData[t]);
        return e || 0
    }
    clear() {
        this.circularData = []
    }
    getStat() {
        const e = this.getAvg()
          , t = {
            sum: e.sum,
            avg: e.avg,
            max: this.getMax()
        };
        return this.clear(),
        t
    }
}
class XEngineRunTimeStats {
    constructor() {
        E(this, "timeArray_loadStaticMesh", new RunTimeArray);
        E(this, "timeArray_updateStaticMesh", new RunTimeArray);
        E(this, "timeArray_addAvatarToScene", new RunTimeArray)
    }
}
const log$x = new Logger$1("XDecalManager");
class XDecalManager {
    constructor(e) {
        E(this, "scene");
        E(this, "_decal");
        E(this, "_mat");
        E(this, "_sharedMat");
        E(this, "_scenemanager");
        this._decal = new Map,
        this._mat = new Map,
        this._sharedMat = new Map,
        this._scenemanager = e,
        this.scene = e.Scene
    }
    get decals() {
        return Array.from(this._decal.values())
    }
    getMesh() {
        return this._decal
    }
    async addDecal(e) {
        const {id: t, meshPath: r, skinInfo: n="default"} = e;
        return this._decal.get(t) ? (log$x.warn(`[Engine] Cannot add decal with an existing id: [${t}], meshPath: ${r}, skinInfo:${n}`),
        Promise.resolve(!0)) : (log$x.info(`[Engine] addDecal wiht id:[${t}], meshPath: ${r}, skinInfo:${n}`),
        new Promise((o,a)=>this._scenemanager.urlTransformer(r).then(s=>new Promise((l,u)=>{
            if (this._decal.get(t))
                l(!0);
            else {
                const c = new XDecal({
                    id: t,
                    scene: this.scene,
                    meshPath: s,
                    skinInfo: n
                });
                this._decal.set(t, c),
                c.loadModel().then(()=>{
                    l(!0)
                }
                ).catch(h=>{
                    log$x.error(`[Engine] addDecal Error! id: [${t}], meshpath:${r}, skin: ${n}. ${h}`),
                    u(new XDecalError(`[Engine] addDecal Error! id: [${t}], meshpath:${r}, skin: ${n}. ${h}`))
                }
                )
            }
        }
        )).then(s=>{
            s == !0 ? o(!0) : a(!1)
        }
        ).catch(s=>{
            log$x.error(`[Engine] Add Decal error! id: [${t}], meshpath:${r}, skin:${n}. ${s}`),
            a(new XDecalError(`[Engine] addDecal  error! id: [${t}], meshpath:${r}, skin:${n}. ${s}`))
        }
        )))
    }
    setDecalTexture(e) {
        const {id: t, buffer: r, isDynamic: n=!1, width: o=1100, height: a=25, slots: s=1, visibleSlots: l=1} = e
          , u = !0;
        return log$x.info(`[Engine] setDecalTexture wiht id:[${t}]`),
        new Promise((c,h)=>{
            const f = this._decal.get(t);
            if (f != null)
                if (this._mat.get(t) != null)
                    this.changeDecalTexture({
                        id: t,
                        buffer: r,
                        isUrl: u,
                        isDynamic: n,
                        width: o,
                        height: a,
                        slots: s,
                        visibleSlots: l
                    }),
                    c(!0);
                else {
                    const d = new XDecalMaterial(t,this.scene);
                    d.setTexture(r, u, n, o, a, s, l).then(()=>{
                        f.setMat(d.getMat()),
                        this._decal.set(t, f),
                        this._mat.set(t, d),
                        c(!0)
                    }
                    ).catch(_=>{
                        log$x.error("[Engine] setDecalTexture Error! " + _),
                        h(new XDecalTextureError(`[Engine] decal set texture error! ${_}`))
                    }
                    )
                }
            else
                log$x.error("[Engine] Error! decal id: [" + t + "] is not find!"),
                h(new XDecalTextureError(`[Engine] decal id: [${t}] is not find!`))
        }
        )
    }
    async shareDecal(e) {
        const {idTar: t, meshPath: r, idSrc: n, skinInfo: o="default"} = e;
        return this._decal.has(n) && !this._decal.has(t) && this._mat.has(n) && !this._mat.has(t) ? (log$x.info(`[Engine] shareDecal wiht idTar:[${t}], idSrc:[${n}], skinInfo: ${o}, meshPath: ${r}`),
        new Promise((a,s)=>this._scenemanager.urlTransformer(r).then(l=>{
            const u = new XDecal({
                id: t,
                scene: this.scene,
                meshPath: l,
                skinInfo: o
            })
              , c = this._mat.get(n);
            c != null && (u.setMat(c.getMat()),
            u.sourceMatId = n,
            this._decal.set(t, u),
            this.addSharedMatCount(n)),
            a(!0)
        }
        ).catch(l=>{
            s(new XDecalError(`[Engine] decal shareDecal error! ${l}`))
        }
        ))) : (log$x.error(`[Engine] shareDecal Error. idSrc: [${n}] not exist! or idTar: [${t}] exists!`),
        Promise.reject(`[Engine] shareDecal Error. idSrc: [${n}] not exist! or idTar: [${t}] exists!`))
    }
    async changeDecalModel(e) {
        const {id: t, meshPath: r} = e
          , n = this._decal.get(t);
        return new Promise((o,a)=>n != null ? (log$x.info(`[Engine] changeDecalModel id:${t}`),
        n.changeModel(r).then(()=>{
            this._decal.set(t, n),
            o(!0)
        }
        )) : (log$x.warn(`[Engine] changeDecalModel id:${t} is not exist`),
        a(`[Engine] changeDecalModel id:${t} is not exist`)))
    }
    changeDecalTexture(e) {
        const {id: t, buffer: r, isUrl: n=!1, isDynamic: o=!1, width: a=1110, height: s=25, slots: l=1, visibleSlots: u=1} = e
          , c = this._mat.get(t);
        c != null && this._decal.has(t) ? (c.changeTexture(r, n, o, a, s, l, u),
        this._mat.set(t, c)) : log$x.error(`[Engine] changeDecalTexture Error. id:${t} is not exist`)
    }
    deleteDecal(e) {
        var t, r;
        if (this._decal.has(e)) {
            const n = this._decal.get(e);
            n != null && n.cleanMesh(),
            this._sharedMat.get(e) != null ? this.minusSharedMatCount(e) : this._mat.get(e) != null ? ((t = this._mat.get(e)) == null || t.cleanTexture(),
            this._mat.delete(e)) : ((r = n.sourceMatId) == null ? void 0 : r.length) > 0 && this.minusSharedMatCount(n.sourceMatId),
            this._decal.delete(e)
        }
    }
    deleteDecalBySkinInfo(e) {
        for (const [t,r] of this._decal.entries())
            r.skinInfo == e && this.deleteDecal(t)
    }
    addSharedMatCount(e) {
        const t = this._sharedMat.get(e);
        t != null ? this._sharedMat.set(e, t + 1) : this._sharedMat.set(e, 1)
    }
    minusSharedMatCount(e) {
        var r;
        const t = this._sharedMat.get(e);
        t != null && (this._sharedMat.set(e, t - 1),
        t == 0 && (this._sharedMat.delete(e),
        (r = this._mat.get(e)) == null || r.cleanTexture(),
        this._mat.delete(e)))
    }
    toggle(e, t) {
        const r = this._decal.get(e);
        r == null || r.toggle(t)
    }
    toggleDecalBySkinInfo(e, t) {
        for (const [r,n] of this._decal.entries())
            n.skinInfo == e && n.toggle(t)
    }
    updateTexAsWords(e, t, r={}) {
        const {clearArea: n=!0, w: o=480, h: a=480, y: s=a / 2, fontsize: l=70, slots: u=1, visibleSlots: c=1, font: h="black-body", color: f="white", fontweight: d=100} = r;
        let {x: _=o / 2} = r;
        const g = this._mat.get(e);
        if (g) {
            _ == -1 && (_ = (g.getUOffset() + c / u) % 1 * o * u);
            const v = g.getMat().diffuseTexture
              , y = v.getContext();
            n && y.clearRect(_ - o / 2, s - a / 2, o, a),
            y.textAlign = "center",
            y.textBaseline = "middle",
            v.drawText(t, _, s, d + " " + l + "px " + h, f, "transparent", !0),
            v.hasAlpha = !0,
            v.update()
        }
    }
    async updateTexAsImg(e, t, r={}) {
        const {clearArea: n=!0, w: o=480, h: a=480, x: s=o / 2, y: l=a / 2, clearW: u=o, clearH: c=a} = r;
        return t == null || t == null || t == "" ? (log$x.error(`[Engine] updateTexAsImg Error. id: [${e}], newBuffer is Null or ""!`),
        Promise.reject(new XDecalError(`[Engine] updateTexAsImg Error. id: [${e}], newBuffer is Null or ""!`))) : new Promise((h,f)=>this._scenemanager.urlTransformer(t).then(d=>new Promise((_,g)=>{
            const m = this._mat.get(e);
            if (m) {
                const y = m.getMat().diffuseTexture;
                if (typeof t == "string") {
                    const b = new Image;
                    b.crossOrigin = "anonymous",
                    b.src = d,
                    b.onload = ()=>{
                        const T = y.getContext();
                        n && T.clearRect(s - u / 2, l - c / 2, u, c),
                        T.drawImage(b, s - o / 2, l - a / 2, o, a),
                        y.update(),
                        _(!0)
                    }
                    ,
                    b.onerror = ()=>{
                        log$x.error(`[Engine] updateTexAsImg Error.newImg load error. id: [${e}], decalMat is Null or undefined!`),
                        g(new XDecalError(`[Engine] updateTexAsImg Error. id: [${e}], decalMat is Null or undefined!`))
                    }
                } else
                    log$x.error(`[Engine] updateTexAsImg Error. id: [${e}], Buffer is not string!`),
                    g(new XDecalError(`[Engine] updateTexAsImg Error. id: [${e}], Buffer is not string!`))
            } else
                log$x.error(`[Engine] updateTexAsImg Error. id: [${e}], decalMat is Null or undefined!`),
                g(new XDecalError(`[Engine] updateTexAsImg Error. id: [${e}], decalMat is Null or undefined!`))
        }
        ).then(_=>{
            _ == !0 ? h(!0) : (log$x.error(`[Engine] updateTexAsImg Error. id: [${e}] !`),
            f(new XDecalError(`[Engine] updateTexAsImg error! id: [${e}]`)))
        }
        ).catch(_=>{
            log$x.error(`[Engine] updateTexAsImg Error. id: [${e}]. ${_}`)
        }
        )))
    }
    startAnime(e, t) {
        log$x.info(`[Engine] Decal Start Anime. [${e}]`);
        const {speed: r=.001, callback: n} = t
          , o = this._mat.get(e);
        o ? (o.do_animation(r),
        n && o.uOffsetObserverable.add(n)) : (log$x.error(`[Engine] startAnime Error. id: [${e}] is not exist!`),
        new XDecalError(`[Engine] startAnime Error. id: [${e}] is not exist!`))
    }
}
class XDecalMaterial {
    constructor(e, t) {
        E(this, "_id");
        E(this, "_tex");
        E(this, "scene");
        E(this, "_mat");
        E(this, "_speed", .001);
        E(this, "_slots", 1);
        E(this, "_visibleSlots", 1);
        E(this, "_isRegisterAnimation");
        E(this, "_animeObserver", null);
        E(this, "_uOffsetObserverable");
        E(this, "reg_mat_update", ()=>{
            const e = this._mat.diffuseTexture;
            e != null && (e.uOffset = e.uOffset + this._speed,
            e.uOffset > 1 && (e.uOffset -= 1),
            Math.round(e.uOffset % (1 / this._slots) / this._speed) == 0 && this._uOffsetObserverable.notifyObservers(this))
        }
        );
        E(this, "setTexture", async(e,t=!0,r=!1,n=1,o=1,a=1,s=1)=>new Promise((l,u)=>{
            this._slots = a,
            this._visibleSlots = s;
            const c = this._tex;
            r ? (this._tex = new DynamicTexture("dyTex",{
                width: n,
                height: o
            },this.scene,!0,Texture.BILINEAR_SAMPLINGMODE),
            this._tex.name = "decal_dy_" + this._id,
            this._tex.uScale = s / a,
            this._tex.vScale = -1,
            this._tex.vOffset = 1,
            this._tex.wrapU = 1,
            this._mat.emissiveColor = new Color3(.95,.95,.95),
            this._mat.diffuseTexture = this._tex,
            this._mat.diffuseTexture.hasAlpha = !0,
            this._mat.useAlphaFromDiffuseTexture = !0,
            this._mat.backFaceCulling = !1,
            this._mat.transparencyMode = Material.MATERIAL_ALPHATEST,
            c != null && c.dispose(),
            l(!0)) : !r && t && typeof e == "string" ? this._tex = new Texture(e,this.scene,!0,!1,Texture.BILINEAR_SAMPLINGMODE,()=>{
                this._tex.name = "decal_" + this._id,
                this._mat.emissiveTexture = this._tex,
                this._mat.diffuseTexture = this._tex,
                this._mat.diffuseTexture.hasAlpha = !0,
                this._mat.useAlphaFromDiffuseTexture = !0,
                this._mat.transparencyMode = Material.MATERIAL_ALPHATEST,
                c != null && c.dispose(),
                l(!0)
            }
            ,()=>{
                log$x.error("[Engine] decal create texture error!"),
                u(new XDecalTextureError("[Engine] decal create texture error!"))
            }
            ,null,!0) : this._tex = new Texture("data:decal_" + this._id,this.scene,!0,!1,Texture.BILINEAR_SAMPLINGMODE,()=>{
                this._tex.name = "decal_" + this._id,
                this._mat.emissiveTexture = this._tex,
                this._mat.diffuseTexture = this._tex,
                this._mat.diffuseTexture.hasAlpha = !0,
                this._mat.useAlphaFromDiffuseTexture = !0,
                this._mat.transparencyMode = Material.MATERIAL_ALPHATEST,
                c != null && c.dispose(),
                l(!0)
            }
            ,()=>{
                log$x.error("[Engine] decal create texture error!"),
                u(new XDecalTextureError("[Engine] decal create texture error!"))
            }
            ,e,!0)
        }
        ));
        this._id = e,
        this.scene = t,
        this._mat = new StandardMaterial("decalMat_" + this._id,this.scene),
        this._isRegisterAnimation = !1,
        this._uOffsetObserverable = new Observable
    }
    get uOffsetObserverable() {
        return this._uOffsetObserverable
    }
    getMat() {
        return this._mat
    }
    set speed(e) {
        this._speed = e
    }
    getUOffset() {
        return this._tex.uOffset
    }
    do_animation(e) {
        this._speed = e,
        this._isRegisterAnimation == !1 && (this._isRegisterAnimation = !0,
        this._animeObserver = this.scene.onBeforeRenderObservable.add(()=>{
            this.reg_mat_update()
        }
        ))
    }
    changeTexture(e, t=!1, r=!1, n=1, o=1, a=1, s=1) {
        return this._mat == null || this._tex == null ? (log$x.error("[Engine] Decal Mat is null or tex is null"),
        Promise.reject(new XDecalTextureError("[Engine] Decal Mat is null or tex is null"))) : this.setTexture(e, t, r, n, o, a, s)
    }
    cleanTexture() {
        log$x.info("[Engine] Decal clean Texture"),
        this.scene.onBeforeRenderObservable.remove(this._animeObserver),
        this._uOffsetObserverable.clear(),
        this._tex.dispose(),
        this._mat.dispose()
    }
}
class XDecal {
    constructor(e) {
        E(this, "_id");
        E(this, "meshPath");
        E(this, "_low_model", []);
        E(this, "_mat", null);
        E(this, "scene");
        E(this, "_skinInfo");
        E(this, "sourceMatId", "");
        E(this, "loadModel", async()=>new Promise((e,t)=>{
            typeof this.meshPath == "string" ? SceneLoader.LoadAssetContainerAsync("", this.meshPath, this.scene, null, ".glb").then(r=>{
                for (let n = r.materials.length - 1; n >= 0; --n)
                    r.materials[n].dispose();
                for (let n = 0; n < r.meshes.length; ++n)
                    r.meshes[n].visibility = 1,
                    r.meshes[n].isPickable = !0,
                    r.meshes[n].checkCollisions = !1,
                    "hasVertexAlpha"in r.meshes[n] && (r.meshes[n].hasVertexAlpha = !1),
                    this.scene.addMesh(r.meshes[n]),
                    this._low_model.push(new XStaticMesh({
                        id: this._id,
                        mesh: r.meshes[n],
                        xtype: EMeshType.Decal,
                        skinInfo: this._skinInfo
                    })),
                    this.toggle(!1);
                e(!0)
            }
            ).catch(r=>{
                t(new XDecalError(`[Engine] decal load model error! ${r}`))
            }
            ) : t(new XDecalError("[Engine] decal inport mesh is not string!"))
        }
        ).catch(e=>{
            new XDecalError(`[Engine] decal loadModel ${e}`)
        }
        ));
        const {id: t, scene: r, meshPath: n, skinInfo: o="default"} = e;
        this._id = t,
        this.scene = r,
        this.meshPath = n,
        this._skinInfo = o
    }
    get skinInfo() {
        return this._skinInfo
    }
    getMesh() {
        return this._low_model
    }
    getMat() {
        return this._mat
    }
    get id() {
        return this._id
    }
    toggle(e) {
        for (let t = 0; t < this._low_model.length; ++t)
            e == !0 ? this._low_model[t].show() : this._low_model[t].hide()
    }
    setMat(e) {
        this._mat = e;
        for (let t = 0; t < this._low_model.length; ++t)
            this._low_model[t].mesh.material = this._mat;
        this.toggle(!0)
    }
    changeModel(e="") {
        return e != "" && (this.meshPath = e),
        this.meshPath == "" ? (log$x.error("[Engine] changeModel Error! meshPath is empty"),
        Promise.reject(new XDecalTextureError("[Engine] changeModel Error! meshPath is empty"))) : new Promise((t,r)=>SceneLoader.LoadAssetContainerAsync("", this.meshPath, this.scene, null, ".glb").then(n=>{
            for (let a = n.materials.length - 1; a >= 0; --a)
                n.materials[a].dispose();
            const o = [];
            for (let a = 0; a < n.meshes.length; ++a)
                n.meshes[a].visibility = 0,
                n.meshes[a].isPickable = !0,
                n.meshes[a].checkCollisions = !1,
                "hasVertexAlpha"in n.meshes[a] && (n.meshes[a].hasVertexAlpha = !1),
                this._mat != null && (n.meshes[a].material = this._mat),
                this.scene.addMesh(n.meshes[a]),
                o.push(new XStaticMesh({
                    id: this._id,
                    mesh: n.meshes[a],
                    xtype: EMeshType.Decal,
                    skinInfo: this._skinInfo
                }));
            e != "" && this.cleanMesh(),
            this._low_model = o,
            this._mat != null && this.toggle(!0),
            t(this)
        }
        ).catch(n=>{
            log$x.error("[Engine] Create decal error! " + n),
            r(new XDecalError("[Engine] Create decal error! " + n))
        }
        ))
    }
    cleanMesh(e=!1, t=!1) {
        log$x.info("[Engine] Decal Model clean mesh");
        for (let r = 0; r < this._low_model.length; ++r)
            this._low_model[r].dispose(e, t)
    }
}
const log$w = new Logger$1("XBreathPointManager");
class XBreathPointManager {
    constructor(e) {
        E(this, "_scene");
        E(this, "materialMap", new Map);
        E(this, "breathPoints", new Map);
        E(this, "_sceneManager");
        E(this, "_allIds", new Set);
        E(this, "_loopBPKeys", []);
        E(this, "addBreathPoint", async e=>{
            const t = [{
                url: "https://static.xverse.cn/qqktv/texture.png"
            }];
            if (t.length <= 0) {
                log$w.warn("[Engine] BreathPoint get texture list error: textureList.length <= 0"),
                new XBreathPointError("[Engine] BreathPoint get texture list error!");
                return
            }
            const r = t[0]
              , {id: n, spriteSheet: o=r.url, spriteWidthNumber: a=20, spriteHeightNumber: s=1, position: l, rotation: u={
                pitch: -90,
                yaw: 270,
                roll: 0
            }, size: c=.6, width: h=-1, height: f=-1, fps: d=30, billboardMode: _=!1, forceLeaveGround: g=!1, type: m="default", lifeTime: v=-1, backfaceculling: y=!0, maxVisibleRegion: b=-1, skinInfo: T="default"} = e;
            if (this.breathPoints.get(n)) {
                log$w.warn("[Engine] Cannot add breathPoint with an existing id: [" + n + "]"),
                new XBreathPointError("[Engine] Cannot add breathPoint with an existing id: [" + n + "]");
                return
            }
            if (g) {
                const I = this.castRay(new Vector3(l.x,l.y,l.z)) * scaleFromUE4toXverse;
                I != 0 ? l.z = l.z - I + 1 : l.z = l.z + 1
            }
            let C;
            if (this.materialMap.get(m)) {
                const I = this.materialMap.get(m);
                I.count = I.count + 1,
                C = I.mat
            } else {
                const I = new Texture(o,this._scene,!0,!0,Texture.BILINEAR_SAMPLINGMODE,null,()=>{
                    log$w.error("[Engine] Breathpoint create texture error."),
                    new XBreathPointError("[Engine] Breathpoint create texture error.")
                }
                ,null,!0);
                I.name = "TexBreathPoint_" + n,
                C = new StandardMaterial(`MaterialBreathPoint_${n}`,this._scene),
                C.alpha = 1,
                C.emissiveTexture = I,
                C.backFaceCulling = y,
                C.diffuseTexture = I,
                C.diffuseTexture.hasAlpha = !0,
                C.useAlphaFromDiffuseTexture = !0,
                this.materialMap.set(m, {
                    mat: C,
                    count: 1,
                    lastRenderTime: Date.now(),
                    fps: d,
                    spriteWidthNumber: a,
                    spriteHeightNumber: s,
                    spriteSheet: o,
                    texture: I
                })
            }
            const A = new Array(6);
            for (let I = 0; I < 6; I++)
                A[I] = new Vector4(0,0,0,0);
            A[0] = new Vector4(0,0,1 / a,1 / s),
            A[1] = new Vector4(0,0,1 / a,1 / s);
            let S = {};
            h > 0 && f > 0 ? S = {
                width: h,
                height: f,
                depth: .01,
                faceUV: A
            } : S = {
                size: c,
                depth: .01,
                faceUV: A
            };
            const P = MeshBuilder.CreateBox(n, S, this._scene);
            P.material = C;
            const R = new XStaticMesh({
                id: n,
                mesh: P,
                xtype: EMeshType.XBreathPoint,
                skinInfo: T
            });
            let M = u;
            _ && (P.billboardMode = Mesh.BILLBOARDMODE_ALL,
            R.allowMove(),
            M = {
                pitch: 0,
                yaw: 270,
                roll: 0
            });
            const x = new BreathPoint({
                type: m,
                mesh: R,
                id: n,
                position: l,
                rotation: M,
                mat: C,
                maxVisibleRegion: b,
                scene: this._scene,
                skinInfo: T
            });
            this.breathPoints.set(n, x),
            this._allIds.add(n),
            v > 0 && setTimeout(()=>{
                this.clearBreathPoints(n)
            }
            , v * 1e3)
        }
        );
        E(this, "reg_breathpoint_update", ()=>{
            const e = new Date().getTime();
            if (this.materialMap != null)
                for (const [t,r] of this.materialMap)
                    e - r.lastRenderTime > 1e3 / r.fps && (r.lastRenderTime = e,
                    Math.abs(r.mat.diffuseTexture.uOffset - (1 - 1 / r.spriteWidthNumber)) < 1e-6 ? (r.mat.diffuseTexture.uOffset = 0,
                    Math.abs(r.mat.diffuseTexture.vOffset - (1 - 1 / r.spriteHeightNumber)) < 1e-6 ? r.mat.diffuseTexture.vOffset = 0 : r.mat.diffuseTexture.vOffset += 1 / r.spriteHeightNumber) : r.mat.diffuseTexture.uOffset += 1 / r.spriteWidthNumber)
        }
        );
        E(this, "reg_breathpoint_autovisible", ()=>{
            if (this._scene.getFrameId() % 2 == 0)
                if (this._loopBPKeys.length == 0)
                    this._loopBPKeys = Array.from(this._allIds);
                else {
                    const e = this._getMainPlayerPosition();
                    for (let t = 0; t < 5 && this._loopBPKeys.length > 0; ++t) {
                        const r = this._loopBPKeys.pop();
                        if (r != null) {
                            const n = this.getBreathPoint(r);
                            if (n != null && n.maxvisibleregion >= 0 && n.mesh.visibility == 1) {
                                const o = n.mesh.position;
                                calcDistance3DVector(e, o) >= n.maxvisibleregion ? n == null || n.removeFromScene() : n == null || n.addToScene()
                            }
                        }
                    }
                }
        }
        );
        this._sceneManager = e,
        this._scene = e.Scene,
        this._scene.registerBeforeRender(this.reg_breathpoint_update),
        this._scene.registerBeforeRender(this.reg_breathpoint_autovisible)
    }
    setAllBreathPointVisibility(e) {
        for (const [t,r] of this.breathPoints.entries())
            r.toggleVisibility(e)
    }
    toggleBPVisibilityBySkinInfo(e, t) {
        for (const [r,n] of this.breathPoints.entries())
            n.skinInfo == e && n.toggleVisibility(t)
    }
    toggleBPVisibilityById(e, t) {
        const r = this.getBreathPoint(e);
        r != null && r.toggleVisibility(t)
    }
    getBreathPointBySkinInfo(e) {
        const t = [];
        for (const [r,n] of this.breathPoints.entries())
            n.skinInfo == e && t.push(n);
        return t
    }
    getAllBreathPoint() {
        return this.breathPoints
    }
    getBreathPoint(e) {
        return this.breathPoints.get(e)
    }
    delete(e) {
        const t = this.breathPoints.get(e);
        if (t != null) {
            t.dispose(),
            this._allIds.delete(e);
            const r = this.materialMap.get(t._type);
            r != null && (r.count = r.count - 1,
            r.count <= 0 && (r.count = 0,
            r.texture.dispose(),
            r.mat.dispose(!0, !0),
            this.materialMap.delete(t._type))),
            this.breathPoints.delete(e)
        }
    }
    castRay(e) {
        var s;
        e = ue4Position2Xverse({
            x: e.x,
            y: e.y,
            z: e.z
        });
        const t = new Vector3(0,-1,0)
          , r = new Ray(e,t,length)
          , n = []
          , o = (s = this._sceneManager) == null ? void 0 : s.getGround({
            x: e.x,
            y: e.y,
            z: e.z
        });
        let a = r.intersectsMeshes(o);
        if (a.length > 0) {
            const l = a[0];
            if (l && l.pickedMesh) {
                const u = l.distance;
                t.y = 1;
                const c = r.intersectsMeshes(n);
                let h = 1e8;
                if (c.length > 0) {
                    const f = c[0];
                    return f && f.pickedMesh && (h = -f.distance),
                    h == 1e8 ? u : Math.abs(h) < Math.abs(u) ? h : u
                }
            }
        } else if (t.y = 1,
        a = r.intersectsMeshes(n),
        a.length > 0) {
            const l = a[0];
            if (l && l.pickedMesh)
                return l.distance
        }
        return 0
    }
    changePickable(e) {
        for (const [t,r] of this.breathPoints.entries())
            r.changePickable(e)
    }
    clearBreathPoints(e) {
        log$w.info(`[Engine] clearBreathPoints: ${e}`);
        for (const [t,r] of this.breathPoints.entries())
            (r._type == e || r._id == e) && this.delete(r._id)
    }
    clearBreathPointsBySkinInfo(e) {
        log$w.info(`[Engine] clearBreathPointsBySkinInfo: ${e}`);
        for (const [t,r] of this.breathPoints.entries())
            r.skinInfo == e && this.delete(r._id)
    }
    clearAllBreathPoints() {
        log$w.info("[Engine] ClearAllBreathPoints");
        for (const [e,t] of this.breathPoints.entries())
            this.delete(t._id)
    }
    _getMainPlayerPosition() {
        var r;
        const e = this._sceneManager.cameraComponent.MainCamera.position
          , t = this._sceneManager.avatarComponent.getMainAvatar();
        if (t != null && t != null) {
            const n = (r = t == null ? void 0 : t.rootNode) == null ? void 0 : r.position;
            if (n != null)
                return n
        }
        return e
    }
    changeBreathPointPose(e, t, r) {
        const n = new Vector3(e.position.x,e.position.y,e.position.z);
        if (this.breathPoints.get(r) != null) {
            log$w.info(`[Engine] changeBreathPointPose, id:${r}`);
            const o = this.breathPoints.get(r)
              , a = o.mesh.position;
            let s = a.subtract(n);
            s = Vector3.Normalize(s);
            const l = Vector3.Distance(a, n)
              , u = new Ray(n,s,l)
              , c = this._scene.multiPickWithRay(u);
            if (c) {
                for (let h = 0; h < c.length; h++)
                    if (c[h].pickedMesh != null && t.mesh.name.indexOf(c[h].pickedMesh.name) >= 0) {
                        const f = c[h].pickedPoint;
                        o.mesh.position = n.add(f.subtract(n).scale(.99)),
                        this.breathPoints.set(r, o)
                    }
            }
        } else
            log$w.warn(`[Engine] changeBreathPointPose, id:${r} is not existing!`)
    }
}
class BreathPoint {
    constructor(e) {
        E(this, "_staticmesh");
        E(this, "_id");
        E(this, "_mat");
        E(this, "_type");
        E(this, "_maxVisibleRegion");
        E(this, "_skinInfo");
        E(this, "_scene");
        E(this, "_isInScene");
        const {mesh: t, id: r, position: n, rotation: o, mat: a, type: s="default", maxVisibleRegion: l=-1, scene: u, skinInfo: c="default"} = e;
        this._id = r,
        t.mesh.position = ue4Position2Xverse(n),
        t.mesh.rotation = ue4Rotation2Xverse(o),
        this._staticmesh = t,
        this._mat = a,
        this._type = s,
        this._maxVisibleRegion = l,
        this._scene = u,
        this._skinInfo = c,
        this._isInScene = !0
    }
    get isInScene() {
        return this._isInScene
    }
    get skinInfo() {
        return this._skinInfo
    }
    get maxvisibleregion() {
        return this._maxVisibleRegion
    }
    getMesh() {
        return this._staticmesh
    }
    get mesh() {
        return this._staticmesh.mesh
    }
    toggleVisibility(e) {
        e == !0 ? this._staticmesh.show() : this._staticmesh.hide()
    }
    changePickable(e) {
        this._staticmesh.mesh.isPickable = e
    }
    removeFromScene() {
        this._isInScene && (this._staticmesh.mesh != null && this._scene.removeMesh(this._staticmesh.mesh),
        this._isInScene = !1)
    }
    addToScene() {
        this._isInScene == !1 && (this._staticmesh.mesh != null && this._scene.addMesh(this._staticmesh.mesh),
        this._isInScene = !0)
    }
    dispose() {
        var e;
        (e = this._staticmesh.mesh) == null || e.dispose(!1, !1)
    }
    set position(e) {
        this._staticmesh.mesh.position = ue4Position2Xverse(e)
    }
    get position() {
        return xversePosition2Ue4(this._staticmesh.mesh.position)
    }
    set rotation(e) {
        this._staticmesh.mesh.rotation = ue4Rotation2Xverse(e)
    }
    get rotation() {
        return xverseRotation2Ue4(this._staticmesh.mesh.rotation)
    }
}
var pureVideoFragment = `precision highp  float;

varying vec3 ModelPos;

uniform float isYUV;  // false: 0, true: 1.0
uniform sampler2D texture_video;
// uniform sampler2D chrominanceYTexture;
// uniform sampler2D chrominanceUTexture;
// uniform sampler2D chrominanceVTexture;

uniform float haveShadowLight;
varying vec4 vPositionFromLight;
uniform float fireworkLight;
varying float fireworkDistance;
varying float fireworkCosTheta;

uniform sampler2D shadowSampler;

// uniform float focal;
// uniform float captureWidth;
// uniform float captureHeight;
uniform vec3 focal_width_height;

const float inv_2_PI = 0.1591549; // 1 / (2 * pi)
const float inv_PI =   0.3183099; // 1 / (  pi)
const vec2 invAtan = vec2(0.1591549, 0.3183099);

float unpack(vec4 color)
{
    const vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);
    return dot(color, bit_shift);
}

float ShadowCalculation(vec4 vPositionFromLight, sampler2D ShadowMap)
{
    vec3 projCoords = vPositionFromLight.xyz / vPositionFromLight.w;
    vec3 depth = 0.5 * projCoords + vec3(0.5);
    vec2 uv = depth.xy;
    if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0)
    {
        return 1.0;
    }
    #ifndef SHADOWFULLFLOAT
        float shadow = unpack(texture2D(ShadowMap, uv));
    #else
        float shadow = texture2D(ShadowMap, uv).x;
    #endif

    if (depth.z > shadow - 1e-4)
    {
        return 0.7;
    }
    else
    {
        return 1.0;
    }
}

// const float f = 514.133282; //937.83246;
// const float w = 720.0;
// const float h = 1280.0;


// vec2 SampleTex(vec3 pt3d, vec2 widthHeight)
vec2 SampleTex(vec3 pt3d)
{
    // // vec2 uv = vec2(  f/w*pt3d.x/pt3d.z, f/h*pt3d.y/pt3d.z ); // \u6A21\u578B\u53D8\u6362\u5230\u76F8\u673A\u5750\u6807\u7CFB\u4E0B
    // vec2 uv = vec2(  focal/captureWidth*pt3d.x/pt3d.z, focal/captureHeight*pt3d.y/pt3d.z ); // \u6A21\u578B\u53D8\u6362\u5230\u76F8\u673A\u5750\u6807\u7CFB\u4E0B
    // uv.x = uv.x + 0.5;
    // uv.y = uv.y + 0.5;
    // return uv;
    return focal_width_height.x / focal_width_height.yz *pt3d.xy/pt3d.z + 0.5;
}
 
void main()
{    
    vec3 yuv;
    vec3 rgb;
    vec2 uv;
    vec3 color = vec3(0,0,0);
    vec3 flash_color = fireworkLight * 1000.0 / fireworkDistance * fireworkCosTheta * vec3(1,0,0); 
    float shadow = 1.0;
    if (haveShadowLight > 0.5)
    {
        shadow = ShadowCalculation(vPositionFromLight, shadowSampler);
    }

    // uv =  SampleTex( normalize(ModelPos), vec2(captureWidth, captureHeight));
    uv =  SampleTex( normalize(ModelPos) );
    if( isYUV < 0.5 )
    {
        color = texture2D(texture_video, uv).rgb;
    }else{
        const mat4 YUV2RGB = mat4
        (
            1.1643828125, 0, 1.59602734375, -.87078515625,
            1.1643828125, -.39176171875, -.81296875, .52959375,
            1.1643828125, 2.017234375, 0, -1.081390625,
            0, 0, 0, 1
        );    
        
       vec4 result = vec4( 
                        texture2D(texture_video, vec2(uv.x, uv.y*0.666666 + 0.333333 ) ).x,
                        texture2D(texture_video, vec2(uv.x * 0.5, uv.y*0.333333 ) ).x, 
                        texture2D(texture_video, vec2(0.5 + uv.x * 0.5,  uv.y*0.333333 ) ).x,
                        1) * YUV2RGB;  
        color = clamp(result.rgb, 0.0, 1.0); 
    }
    if( uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0 )
    {
        color = vec3(0,0,0);
    }
    // gl_FragColor = vec4(shadow, shadow, shadow, 1.0); 
    gl_FragColor = vec4(shadow * (color + flash_color) * 1.0, 1.0); 
}

`
  , pureVideoVertex = `precision highp float;

varying vec3 ModelPos;

varying vec4 vPositionFromLight;
varying float fireworkDistance;
varying float fireworkCosTheta;

attribute vec2 uv;
attribute vec3 position;

attribute vec4 world0;
attribute vec4 world1;
attribute vec4 world2;
attribute vec4 world3;

#ifdef NORMAL
attribute vec3 normal;
#endif



uniform vec3 fireworkLightPosition;
uniform mat4 view;
uniform mat4 projection;
uniform mat4 lightSpaceMatrix;

uniform mat4 world;
uniform mat4 worldViewProjection;
float DistanceCalculation(vec3 Q, vec3 P)
{
    return (Q.x - P.x) * (Q.x - P.x) + (Q.y - P.y) * (Q.y - P.y) + (Q.z - P.z) * (Q.z - P.z);
}
float CosThetaCalculation(vec3 Q, vec3 P)
{
    return max(0.,dot(Q, P));
}
void main()
{
    
    #include<instancesVertex>

    vPositionFromLight =  lightSpaceMatrix * finalWorld * vec4(position, 1.0);
    
    // fireworkDistance = DistanceCalculation(vec3(finalWorld * vec4(position, 1.0)), fireworkLightPosition);
    fireworkDistance = distance(vec3(finalWorld * vec4(position, 1.0)), fireworkLightPosition);
     
    
    fireworkCosTheta = 1.0;
    #ifdef NORMAL
    vec3 directionFirework = fireworkLightPosition.xyz - vec3(finalWorld * vec4(position, 1.0));
    directionFirework = normalize(directionFirework);
    // directionFirework = directionFirework / (directionFirework.x * directionFirework.x + directionFirework.y * directionFirework.y + directionFirework.z * directionFirework.z);
    fireworkCosTheta = CosThetaCalculation(directionFirework, normal);
    #endif
    
    ModelPos = vec3( view * finalWorld * vec4(position , 1.0));
    gl_Position = projection * view * finalWorld * vec4(position , 1.0); 
}
`
  , panoFragment = `precision highp float;

uniform float isYUV;  // false: 0, true: 1.0

varying vec2 TexCoords;
varying vec3 WorldPos;  
varying vec3 vNormal;

uniform float haveShadowLight;
varying vec4 vPositionFromLight;
uniform float fireworkLight;
varying float fireworkDistance;
varying float fireworkCosTheta;

uniform sampler2D shadowSampler;

uniform vec3 centre_pose;  
uniform sampler2D texture_pano; 
const float inv_2_PI = 0.1591549; // 1 / (2 * pi)
const float inv_PI =   0.3183099; // 1 / (  pi)
const vec2 invAtan = vec2(0.1591549, 0.3183099);

float unpack(vec4 color)
{
    const vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);
    return dot(color, bit_shift);
}
  

float ShadowCalculation(vec4 vPositionFromLight, sampler2D ShadowMap)
{
    vec3 projCoords = vPositionFromLight.xyz / vPositionFromLight.w;
    vec3 depth = 0.5 * projCoords + vec3(0.5);
    vec2 uv = depth.xy;
    if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0)
    {
        return 1.0;
    }
    #ifndef SHADOWFULLFLOAT
        float shadow = unpack(texture2D(ShadowMap, uv));
    #else
        float shadow = texture2D(ShadowMap, uv).x;
    #endif

    if (depth.z > shadow)
    {
        return 0.7;
    }
    else
    {
        return 1.0;
    }
}
 
vec2 SampleSphericalMap(vec3 pt3d)
{
    vec2 uv = vec2( atan(-pt3d.z,pt3d.x), atan( pt3d.y, sqrt(pt3d.x*pt3d.x + pt3d.z * pt3d.z))); 
    uv.x = 0.5 + uv.x * inv_2_PI ;     // yaw:   \u6C34\u5E73\u65B9\u5411 \uFF0C0 \u5230 360 \uFF0C \u5BF9\u5E948k\u7684\u5BBD  
    uv.y = 0.5 + uv.y * inv_PI ;       // pitch: \u7AD6\u76F4\u65B9\u5411\uFF0C -64 \u5230 64 \uFF0C\u5BF9\u5E944k\u7684\u957F

    return vec2(uv.x,uv.y);
} 

vec3 fitUint8Range(vec3 color)
{
    if( color.x < 0.0 ){color.x = 0.0;}
    if( color.x > 1.0 ){color.x = 1.0;}
    if( color.y < 0.0 ){color.y = 0.0;}
    if( color.y > 1.0 ){color.y = 1.0;}
    if( color.z < 0.0 ){color.z = 0.0;}
    if( color.z > 1.0 ){color.z = 1.0;}
    return color;
}

void main()
{    
//  // Debug
    // vec3 vLightPosition = vec3(0,10,100); 
    // // World values
    // vec3 vPositionW = vec3( WorldPos.x, WorldPos.y, WorldPos.z );
    // vec3 vNormalW = normalize( vNormal) ;
    // vec3 viewDirectionW = normalize(vPositionW);
    // // Light
    // vec3 lightVectorW = normalize(vLightPosition - vPositionW); 
    // // diffuse
    // float ndl = max(0., dot(vNormalW, lightVectorW));
    // gl_FragColor = vec4( ndl, ndl, ndl, 1.);

    vec2 uv;
    vec3 color = vec3(0,0,0);  
 
    vec3 flash_color = fireworkLight * 1000.0 / fireworkDistance * fireworkCosTheta * vec3(1,0,0); 
    float shadow = 1.0;
    if (haveShadowLight > 0.5)
    {
        shadow = ShadowCalculation(vPositionFromLight, shadowSampler);
    }

    uv = SampleSphericalMap(normalize( WorldPos - centre_pose ));

    if( isYUV < 0.5 )
    {
        color = texture2D(texture_pano, uv).rgb;  
    }else{
        const mat4 YUV2RGB = mat4
                (
                    1.1643828125, 0, 1.59602734375, -.87078515625,
                    1.1643828125, -.39176171875, -.81296875, .52959375,
                    1.1643828125, 2.017234375, 0, -1.081390625,
                    0, 0, 0, 1
                );    
                
        vec4 result = vec4( 
                            texture2D(texture_pano, vec2(uv.x, uv.y*0.666666 + 0.333333 ) ).x,
                            texture2D(texture_pano, vec2(uv.x * 0.5, uv.y*0.333333 ) ).x, 
                            texture2D(texture_pano, vec2(0.5 + uv.x * 0.5,  uv.y*0.333333 ) ).x,
                            1) * YUV2RGB;  
        color = fitUint8Range(result.rgb);        
    }
    if( uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0 )
    {
        color = vec3(0,0,0);
    }
    gl_FragColor = vec4( shadow * (color + flash_color), 1.0); 
}`
  , panoVertex = `precision highp float;

varying vec2 TexCoords;
varying vec3 vNormal;
varying vec3 WorldPos; 

varying vec4 vPositionFromLight;
varying float fireworkDistance;
varying float fireworkCosTheta;
uniform vec3 fireworkLightPosition;
uniform mat4 lightSpaceMatrix;

attribute vec3 normal;
attribute vec2 uv; 
attribute vec3 position;  

uniform mat4 view;
uniform mat4 projection; 
uniform mat4 world;
uniform mat4 worldViewProjection;
 
attribute vec4 world0;
attribute vec4 world1;
attribute vec4 world2;
attribute vec4 world3;

float DistanceCalculation(vec3 Q, vec3 P)
{
    return (Q.x - P.x) * (Q.x - P.x) + (Q.y - P.y) * (Q.y - P.y) + (Q.z - P.z) * (Q.z - P.z);
}
float CosThetaCalculation(vec3 Q, vec3 P)
{
    return max(0.,dot(Q, P));
}

void main()
{ 
    #include<instancesVertex>

    vPositionFromLight =  lightSpaceMatrix * world * vec4(position, 1.0);
    fireworkDistance = DistanceCalculation(vec3(finalWorld * vec4(position, 1.0)), fireworkLightPosition);
    fireworkCosTheta = 1.0;
    vec3 newP = vec3( finalWorld * vec4(position, 1.0) );
    WorldPos = newP;
    TexCoords = uv;     
    vNormal = normal; 
    gl_Position = projection * view * vec4(newP , 1.0); 
}

`;
class XVideoRawYUV {
    constructor(e, t) {
        E(this, "scene");
        E(this, "_videoRawYUVTexture");
        E(this, "videosResOriArray");
        E(this, "_currentVideoId");
        this.scene = e,
        this._videoRawYUVTexture = [],
        this.videosResOriArray = t,
        this._currentVideoId = -1;
        for (let r = 0; r < t.length; ++r)
            (n=>{
                const o = RawTexture.CreateLuminanceTexture(null, t[n].width, t[n].height * 1.5, this.scene, !1, !0);
                o.name = "videoTex_" + t[n].width + "_" + t[n].height,
                this._videoRawYUVTexture.push(o)
            }
            )(r)
    }
    inRange(e) {
        return e >= 0 && e < this._videoRawYUVTexture.length
    }
    getVideoYUVTex(e) {
        return this.inRange(e) ? this._videoRawYUVTexture[e] : null
    }
    findId(e, t) {
        let r = 0;
        for (let n = 0; n < this.videosResOriArray.length; ++n)
            if (this.videosResOriArray[n].width == e && this.videosResOriArray[n].height == t) {
                r = n;
                break
            }
        return r
    }
    getCurrentVideoTexId() {
        return this._currentVideoId
    }
    setCurrentVideoTexId(e) {
        this._currentVideoId = e
    }
}
const log$v = new Logger$1("XMaterial");
var EShaderMode = (i=>(i[i.default = 0] = "default",
i[i.video = 1] = "video",
i[i.videoAndPano = 2] = "videoAndPano",
i))(EShaderMode || {});
class XMaterialComponent {
    constructor(e, t) {
        E(this, "scene");
        E(this, "engine");
        E(this, "yuvInfo");
        E(this, "shaderMode");
        E(this, "_panoInfo");
        E(this, "_dynamic_size");
        E(this, "_dynamic_babylonpose");
        E(this, "_dynamic_textures");
        E(this, "_dynamic_shaders");
        E(this, "_scenemanager");
        E(this, "_videoTexture");
        E(this, "_videoElement");
        E(this, "_lowModelShader");
        E(this, "_defaultShader");
        E(this, "_inputYUV420", !0);
        E(this, "_inputPanoYUV420", !0);
        E(this, "_videoRawYUVTexArray");
        E(this, "_isUpdateYUV", !0);
        E(this, "initMaterial", async()=>new Promise((e,t)=>{
            this._initDefaultShader(),
            this.shaderMode == 2 ? this.initDynamicData(this._panoInfo.dynamicRange, this._panoInfo.width, this._panoInfo.height).then(()=>{
                this._initPureVideoShader(),
                this._prepareRender(this.yuvInfo)
            }
            ) : this.shaderMode == 1 ? (this._initPureVideoShader(),
            this._prepareRender(this.yuvInfo)) : this.shaderMode == 0,
            e(!0)
        }
        ));
        E(this, "_initPureVideoContent", e=>{
            this._inputYUV420 ? this._videoRawYUVTexArray.getVideoYUVTex(0) != null && (this._lowModelShader.setTexture("texture_video", this._videoRawYUVTexArray.getVideoYUVTex(0)),
            this._lowModelShader.setFloat("isYUV", 1),
            Texture.WhenAllReady([this._videoRawYUVTexArray.getVideoYUVTex(0)], ()=>{
                this._changePureVideoLowModelShaderCanvasSize(e)
            }
            )) : (this._videoElement = e.videoElement,
            this._videoTexture || (this._videoTexture = new VideoTexture("InterVideoTexture",this._videoElement,this.scene,!0,!1)),
            Texture.WhenAllReady([this._videoTexture], ()=>{
                this._changePureVideoLowModelShaderCanvasSize({
                    width: this._videoElement.height,
                    height: this._videoElement.width,
                    fov: e.fov
                })
            }
            ),
            this._lowModelShader.setTexture("texture_video", this._videoTexture),
            this._lowModelShader.setFloat("isYUV", 0))
        }
        );
        E(this, "_changePureVideoLowModelShaderCanvasSize", e=>{
            var a;
            const t = e.fov || 50
              , r = e.width || 720
              , n = e.height || 1280
              , o = r / (2 * Math.tan(Math.PI * t / 360));
            (a = this._lowModelShader) == null || a.setVector3("focal_width_height", new Vector3(o,r,n))
        }
        );
        E(this, "updateRawYUVData", (e,t,r,n=-1)=>{
            var o, a;
            if (n == -1 && (n = this.yuvInfo.fov),
            this._isUpdateYUV == !0) {
                const s = {
                    width: t,
                    height: r,
                    fov: n
                }
                  , l = this._videoRawYUVTexArray.findId(t, r)
                  , u = this._videoRawYUVTexArray.getCurrentVideoTexId();
                (u < 0 || l != u || n != this.yuvInfo.fov) && (this.yuvInfo.width = t,
                this.yuvInfo.height = r,
                this.yuvInfo.fov = n,
                this._videoRawYUVTexArray.setCurrentVideoTexId(l),
                this._changeVideoRes(l),
                this._changePureVideoLowModelShaderCanvasSize(s),
                this._scenemanager.cameraComponent.cameraFovChange(s),
                this._scenemanager.yuvInfo = s),
                (o = this._videoRawYUVTexArray.getVideoYUVTex(l)) == null || o.update(e),
                (a = this._videoRawYUVTexArray.getVideoYUVTex(l)) == null || a.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE)
            }
        }
        );
        E(this, "_changeVideoRes", e=>{
            this._lowModelShader.setTexture("texture_video", this._videoRawYUVTexArray.getVideoYUVTex(e))
        }
        );
        E(this, "initDynamicData", (e,t,r)=>new Promise((n,o)=>{
            this.setDynamicSize(e).then(a=>{
                if (a) {
                    for (let s = 0; s < e; ++s)
                        (l=>{
                            this.initDynamicTexture(l, t, r),
                            this.initDynamicShaders(l).then(()=>{
                                this._updatePanoShaderInput(l)
                            }
                            )
                        }
                        )(s);
                    n(!0)
                } else
                    o(new XMaterialError(`[Engine] DynamicRoomSize (${e}) is too small`))
            }
            )
        }
        ).catch(n=>log$v.error(`[Engine] ${n}`)));
        E(this, "_initDefaultShader", ()=>{
            this._defaultShader == null && (this._defaultShader = new GridMaterial("GridShader",this.scene),
            this._defaultShader.gridRatio = 50,
            this._defaultShader.lineColor = new Color3(0,0,.5),
            this._defaultShader.majorUnitFrequency = 1,
            this._defaultShader.mainColor = new Color3(.6,.6,.6),
            this._defaultShader.backFaceCulling = !1)
        }
        );
        E(this, "_initPureVideoShader", ()=>{
            if (this._lowModelShader == null) {
                const e = new ShaderMaterial("PureVideoShader",this.scene,{
                    vertexSource: pureVideoVertex,
                    fragmentSource: pureVideoFragment
                },{
                    attributes: ["uv", "position", "world0", "world1", "world2", "world3"],
                    uniforms: ["view", "projection", "worldViewProjection", "world"],
                    defines: ["#define SHADOWFULLFLOAT"]
                });
                e.setTexture("shadowSampler", null),
                e.setMatrix("lightSpaceMatrix", null),
                e.setFloat("haveShadowLight", 0),
                e.setTexture("texture_video", null),
                e.setFloat("isYUV", this._inputYUV420 ? 1 : 0),
                e.setFloat("fireworkLight", 0),
                e.setVector3("fireworkLightPosition", new Vector3(0,0,0)),
                e.setVector3("focal_width_height", new Vector3(772.022491,720,1280)),
                e.backFaceCulling = !1,
                this._lowModelShader = e
            }
        }
        );
        E(this, "setDynamicSize", e=>new Promise((t,r)=>{
            e >= 1 && e <= 100 ? (this._dynamic_size = e,
            t(!0)) : (this._dynamic_size = 1,
            t(!1))
        }
        ));
        E(this, "_isInDynamicRange", e=>e < this._dynamic_size && e >= 0);
        E(this, "initDynamicTexture", (e,t,r)=>{
            this._isInDynamicRange(e) && (this._dynamic_textures[e] != null && (this._dynamic_textures[e].dispose(),
            this._dynamic_textures[e] = null),
            this._dynamic_textures[e] = new RawTexture(null,t,r * 1.5,Engine.TEXTUREFORMAT_LUMINANCE,this.scene,!1,!0,Texture.NEAREST_SAMPLINGMODE,Engine.TEXTURETYPE_UNSIGNED_BYTE),
            this._dynamic_textures[e].name = "Pano_Dynamic_" + e + "_" + Date.now())
        }
        );
        E(this, "initDynamicShaders", e=>(log$v.info("[Engine] Material init dynamic shader."),
        new Promise((t,r)=>{
            this._dynamic_shaders[e] != null && this._dynamic_shaders[e].dispose();
            const n = new ShaderMaterial("Pano_Shader_" + e,this.scene,{
                vertexSource: panoVertex,
                fragmentSource: panoFragment
            },{
                attributes: ["uv", "position", "world0", "world1", "world2", "world3"],
                uniforms: ["view", "projection", "worldViewProjection", "world"],
                defines: ["#define SHADOWFULLFLOAT"]
            });
            n.setTexture("texture_pano", null),
            n.setVector3("centre_pose", new Vector3(0,0,0)),
            n.setFloat("isYUV", this._inputPanoYUV420 ? 1 : 0),
            n.setTexture("shadowSampler", null),
            n.setMatrix("lightSpaceMatrix", null),
            n.setFloat("haveShadowLight", 0),
            n.setFloat("fireworkLight", 0),
            n.setVector3("fireworkLightPosition", new Vector3(0,0,0)),
            n.backFaceCulling = !1,
            this._dynamic_shaders[e] = n,
            t(!0)
        }
        )));
        this._scenemanager = e,
        this.scene = e.Scene,
        this.engine = this.scene.getEngine(),
        this.shaderMode = 1,
        this._dynamic_textures = [],
        this._dynamic_shaders = [],
        this._dynamic_babylonpose = [],
        this._videoRawYUVTexArray = new XVideoRawYUV(this.scene,t.videoResOriArray),
        this.shaderMode = t.shaderMode,
        t.yuvInfo != null && (this.yuvInfo = t.yuvInfo),
        t.panoInfo != null && this.setPanoInfo(t.panoInfo)
    }
    stopYUVUpdate() {
        this._isUpdateYUV = !1
    }
    allowYUVUpdate() {
        this._isUpdateYUV = !0
    }
    setPanoInfo(e) {
        this._panoInfo = e
    }
    _prepareRender(e) {
        e && (this._initPureVideoContent(e),
        this._updatePureVideoShaderInput())
    }
    getPureVideoShader() {
        return this._lowModelShader
    }
    getDefaultShader() {
        return this._defaultShader
    }
    updatePanoPartYUV(e, t, r) {
        const n = t.subarray(0, r.width * r.height)
          , o = t.subarray(r.width * r.height, r.width * r.height * 1.25)
          , a = t.subarray(r.width * r.height * 1.25)
          , s = this._panoInfo.width
          , l = this._panoInfo.height;
        if (this._dynamic_textures[e] != null) {
            const u = this._dynamic_textures[e].getInternalTexture();
            if (u != null && u != null) {
                const c = this.engine._getTextureTarget(u);
                this.engine._bindTextureDirectly(c, u, !0),
                this.engine.updateTextureData(u, n, r.startX, l * 1.5 - r.startY - r.height, r.width, r.height),
                this.engine.updateTextureData(u, o, r.startX * .5, (l - r.startY - r.height) * .5, r.width * .5 - 1, r.height * .5 - 1),
                this.engine.updateTextureData(u, a, r.startX * .5 + s * .5, (l - r.startY - r.height) * .5, r.width * .5, r.height * .5),
                this.engine._bindTextureDirectly(c, null)
            }
        }
    }
    changePanoImg(e, t) {
        if (log$v.info(`[Engine] changePanoImg, id=${e}, pose=${t.pose.position.x},${t.pose.position.y},${t.pose.position.z}`),
        !this._isInDynamicRange(e))
            return log$v.error(`[Engine] ${e} is bigger than dynamic size set in PanoInfo`),
            Promise.reject(new XMaterialError(`[Engine] ${e} is bigger than dynamic size set in PanoInfo`));
        const r = ue4Position2Xverse(t.pose.position);
        return r && (this._dynamic_babylonpose[e] = {
            position: r
        }),
        new Promise((n,o)=>{
            try {
                typeof t.data == "string" ? (this.setPanoYUV420(!1),
                this._dynamic_textures[e].updateURL(t.data, null, ()=>{
                    this._dynamic_textures[e].updateSamplingMode(Texture.NEAREST_SAMPLINGMODE)
                }
                )) : (this.isPanoYUV420() == !1 && this.initDynamicTexture(e, this._panoInfo.width, this._panoInfo.height),
                this.setPanoYUV420(!0),
                this._dynamic_textures[e].update(t.data),
                this._dynamic_textures[e].updateSamplingMode(Texture.NEAREST_SAMPLINGMODE)),
                n(this)
            } catch (a) {
                o(new XMaterialError(`[Engine] ChangePanoImg Error! ${a}`))
            }
        }
        ).then(n=>(t.fov != null && this._scenemanager.cameraComponent.changeCameraFov(t.fov * Math.PI / 180),
        this._dynamic_shaders[e].setFloat("isYUV", this._inputPanoYUV420 ? 1 : 0),
        this._dynamic_shaders[e].setTexture("texture_pano", this._dynamic_textures[e]),
        this._dynamic_shaders[e].setVector3("centre_pose", this._dynamic_babylonpose[e].position),
        !0))
    }
    setYUV420(e) {
        this._inputYUV420 = e
    }
    isYUV420() {
        return this._inputYUV420
    }
    setPanoYUV420(e) {
        this._inputPanoYUV420 = e
    }
    isPanoYUV420() {
        return this._inputPanoYUV420
    }
    getDynamicShader(e) {
        return this._dynamic_shaders[e]
    }
    _updatePureVideoShaderInput() {
        var e, t, r, n, o, a, s, l, u, c;
        if (this.scene.getLightByName("AvatarLight") ? ((e = this._lowModelShader) == null || e.setFloat("haveShadowLight", 1),
        (n = this._lowModelShader) == null || n.setTexture("shadowSampler", (r = (t = this.scene.getLightByName("AvatarLight")) == null ? void 0 : t.getShadowGenerator()) == null ? void 0 : r.getShadowMapForRendering()),
        (s = this._lowModelShader) == null || s.setMatrix("lightSpaceMatrix", (a = (o = this.scene.getLightByName("AvatarLight")) == null ? void 0 : o.getShadowGenerator()) == null ? void 0 : a.getTransformMatrix())) : ((l = this._lowModelShader) == null || l.setTexture("shadowSampler", this._videoTexture),
        (u = this._lowModelShader) == null || u.setMatrix("lightSpaceMatrix", new Matrix),
        (c = this._lowModelShader) == null || c.setFloat("haveShadowLight", 0)),
        this.scene.getLightByName("fireworkLight"))
            this.scene.registerBeforeRender(()=>{
                var h;
                this._lowModelShader.setFloat("fireworkLight", this.scene.getLightByName("fireworkLight").getScaledIntensity()),
                this._lowModelShader.setVector3("fireworkLightPosition", (h = this.scene.getLightByName("fireworkLight")) == null ? void 0 : h.position)
            }
            );
        else {
            const h = new PointLight("fireworkLight",new Vector3(0,0,0),this.scene);
            h.intensity = 0
        }
    }
    _updatePanoShaderInput(e) {
        var t, r, n, o, a, s, l, u, c, h;
        if (this._isInDynamicRange(e))
            if (this.scene.getLightByName("AvatarLight") ? ((t = this._dynamic_shaders[e]) == null || t.setFloat("haveShadowLight", 1),
            (o = this._dynamic_shaders[e]) == null || o.setTexture("shadowSampler", (n = (r = this.scene.getLightByName("AvatarLight")) == null ? void 0 : r.getShadowGenerator()) == null ? void 0 : n.getShadowMapForRendering()),
            (l = this._dynamic_shaders[e]) == null || l.setMatrix("lightSpaceMatrix", (s = (a = this.scene.getLightByName("AvatarLight")) == null ? void 0 : a.getShadowGenerator()) == null ? void 0 : s.getTransformMatrix())) : ((u = this._dynamic_shaders[e]) == null || u.setTexture("shadowSampler", null),
            (c = this._dynamic_shaders[e]) == null || c.setMatrix("lightSpaceMatrix", new Matrix),
            (h = this._dynamic_shaders[e]) == null || h.setFloat("haveShadowLight", 0)),
            this.scene.getLightByName("fireworkLight"))
                this.scene.registerBeforeRender(()=>{
                    var f;
                    this._dynamic_shaders[e].setFloat("fireworkLight", this.scene.getLightByName("fireworkLight").getScaledIntensity()),
                    this._dynamic_shaders[e].setVector3("fireworkLightPosition", (f = this.scene.getLightByName("fireworkLight")) == null ? void 0 : f.position)
                }
                );
            else {
                const f = new PointLight("fireworkLight",new Vector3(0,0,0),this.scene);
                f.intensity = 0
            }
    }
}
class XCameraComponent {
    constructor(e, t, r) {
        E(this, "maincameraRotLimitObserver", null);
        E(this, "mainCamera");
        E(this, "cgCamera");
        E(this, "saveCameraPose");
        E(this, "_cameraPose");
        E(this, "scene");
        E(this, "canvas");
        E(this, "yuvInfo");
        E(this, "forceKeepVertical", !1);
        E(this, "initCamera", e=>{
            const {maxZ: t=1e4, minZ: r=.1, angularSensibility: n=2e3} = e;
            this.mainCamera = new FreeCamera("camera_main",new Vector3(0,1e3,0),this.scene),
            this.mainCamera.mode = Camera$1.PERSPECTIVE_CAMERA,
            this.mainCamera.speed = .1,
            this.mainCamera.angularSensibility = n,
            this.mainCamera.setTarget(new Vector3(0,1010,0)),
            this.mainCamera.minZ = r,
            this.mainCamera.fov = Math.PI * this.yuvInfo.fov / 180,
            this.mainCamera.maxZ = t,
            this.mainCamera.fovMode = Camera$1.FOVMODE_HORIZONTAL_FIXED,
            this.cgCamera = new FreeCamera("camera_temp",new Vector3(0,1e3,0),this.scene),
            this.cgCamera.mode = Camera$1.PERSPECTIVE_CAMERA,
            this.cgCamera.speed = .1,
            this.cgCamera.setTarget(new Vector3(0,1010,0)),
            this.cgCamera.maxZ = t,
            this.cgCamera.minZ = r,
            this.cgCamera.fovMode = Camera$1.FOVMODE_HORIZONTAL_FIXED,
            this.cameraFovChange(this.yuvInfo)
        }
        );
        E(this, "cameraFovChange", e=>{
            this.yuvInfo = e;
            const t = e.width
              , r = e.height
              , n = this.canvas.width
              , o = this.canvas.height
              , a = e.fov;
            if (this.forceKeepVertical == !0) {
                const s = t / (2 * Math.tan(Math.PI * a / 360))
                  , l = 2 * Math.atan(r / (2 * s));
                this.mainCamera.fov = l,
                this.cgCamera.fov = l,
                this.mainCamera.fovMode = Camera$1.FOVMODE_VERTICAL_FIXED,
                this.cgCamera.fovMode = Camera$1.FOVMODE_VERTICAL_FIXED
            } else if (this.mainCamera.fovMode = Camera$1.FOVMODE_HORIZONTAL_FIXED,
            this.cgCamera.fovMode = Camera$1.FOVMODE_HORIZONTAL_FIXED,
            n / o < t / r && this.mainCamera.fov) {
                const s = o
                  , l = n
                  , u = s * t / r / (2 * Math.tan(a * Math.PI / 360))
                  , c = 2 * Math.atan(l / (2 * u));
                this.mainCamera.fov = c,
                this.cgCamera.fov = c
            } else
                this.mainCamera.fov = Math.PI * a / 180,
                this.cgCamera.fov = Math.PI * a / 180
        }
        );
        E(this, "setCameraPose", e=>{
            var n;
            const t = ue4Position2Xverse(e.position);
            let r = null;
            e.rotation != null && (r = ue4Rotation2Xverse(e.rotation)),
            this._cameraPose = {
                position: t
            },
            r != null && (this._cameraPose.rotation = r),
            this.scene.activeCamera === this.mainCamera && !((n = this.mainCamera) != null && n.isDisposed()) && this._setCamPositionRotation(this.mainCamera, this._cameraPose)
        }
        );
        E(this, "_setCamPositionRotation", (e,t)=>{
            var r, n;
            t.position && (e.position = (r = t.position) == null ? void 0 : r.clone()),
            t.rotation && (e.rotation = (n = t.rotation) == null ? void 0 : n.clone())
        }
        );
        E(this, "switchCamera", e=>{
            var t;
            (t = this.scene.activeCamera) == null || t.detachControl(this.canvas),
            this.scene.activeCamera = e
        }
        );
        E(this, "reCalXYZRot", (e,t)=>(e = e % (2 * Math.PI),
        Math.abs(t - e) >= Math.PI && (e = e - 2 * Math.PI),
        e));
        E(this, "_moveCam", (e,t,r,n,o,a,s,l)=>{
            const u = (v,y,b)=>(v.x = this.reCalXYZRot(v.x, y.x),
            v.y = this.reCalXYZRot(v.y, y.y),
            v.z = this.reCalXYZRot(v.z, y.z),
            new Vector3((y.x - v.x) * b + v.x,(y.y - v.y) * b + v.y,(y.z - v.z) * b + v.z))
              , c = function(v, y, b) {
                return new Vector3((y.x - v.x) * b + v.x,(y.y - v.y) * b + v.y,(y.z - v.z) * b + v.z)
            }
              , h = new Animation("myAnimation1","position",s,Animation.ANIMATIONTYPE_VECTOR3,Animation.ANIMATIONLOOPMODE_CONSTANT);
            let f = []
              , d = t
              , _ = r;
            for (let v = 0; v < a; ++v)
                f.push({
                    frame: v,
                    value: c(d, _, v / a)
                });
            f.push({
                frame: f.length,
                value: c(d, _, 1)
            }),
            h.setKeys(f);
            const g = new Animation("myAnimation2","rotation",s,Animation.ANIMATIONTYPE_VECTOR3,Animation.ANIMATIONLOOPMODE_CONSTANT);
            f = [],
            d = n,
            _ = o;
            for (let v = 0; v < a; ++v)
                f.push({
                    frame: v,
                    value: u(d, _, v / a)
                });
            f.push({
                frame: f.length,
                value: u(d, _, 1)
            }),
            g.setKeys(f),
            e.animations.push(g),
            e.animations.push(h);
            const m = this.scene.beginAnimation(e, 0, a, !1);
            m.onAnimationEnd = ()=>{
                l(),
                m.stop(),
                m.animationStarted = !1
            }
        }
        );
        this.scene = t,
        this.canvas = e,
        this.yuvInfo = r.yuvInfo,
        r.forceKeepVertical != null && (this.forceKeepVertical = r.forceKeepVertical),
        this.initCamera(r.cameraParam)
    }
    get MainCamera() {
        return this.mainCamera
    }
    get CgCamera() {
        return this.cgCamera
    }
    getCameraHorizonFov() {
        return this.mainCamera.fovMode == Camera$1.FOVMODE_HORIZONTAL_FIXED ? this.mainCamera.fov : Math.PI * this.yuvInfo.fov / 180
    }
    changeMainCameraRotationDamping(e=2e3) {
        this.mainCamera.angularSensibility = e
    }
    removeMainCameraRotationLimit() {
        this.maincameraRotLimitObserver != null && this.mainCamera.onAfterCheckInputsObservable.remove(this.maincameraRotLimitObserver)
    }
    setMainCameraInfo(e) {
        const {maxZ: t=1e4, minZ: r=.1, angularSensibility: n=2e3} = e;
        this.mainCamera.maxZ = t,
        this.mainCamera.minZ = r,
        this.mainCamera.angularSensibility = n
    }
    getMainCameraInfo() {
        return {
            maxZ: this.mainCamera.maxZ,
            minZ: this.mainCamera.minZ,
            angularSensibility: this.mainCamera.angularSensibility
        }
    }
    _limitAngle(e, t) {
        return Math.abs(Math.abs(t[0] - t[1]) - 360) < 1e-6 || (e = (e % 360 + 360) % 360,
        t[0] = (t[0] % 360 + 360) % 360,
        t[1] = (t[1] % 360 + 360) % 360,
        t[0] > t[1] ? e > t[1] && e < t[0] && (Math.abs(e - t[0]) < Math.abs(e - t[1]) ? e = t[0] : e = t[1]) : e < t[0] ? e = t[0] : e > t[1] && (e = t[1])),
        e
    }
    setMainCameraRotationLimit(e, t) {
        this.maincameraRotLimitObserver != null && this.removeMainCameraRotationLimit();
        const r = this.mainCamera
          , {yaw: n, pitch: o, roll: a} = e
          , {yaw: s, pitch: l, roll: u} = t;
        if (s < 0 || l < 0 || u < 0)
            throw new Error("\u76F8\u673A\u65CB\u8F6C\u9650\u5236\u53EA\u80FD\u8BBE\u7F6E\u4E3A\u5927\u4E8E0");
        const c = [o - l, o + l]
          , h = [n - s, n + s]
          , f = [a - u, a + u];
        this.maincameraRotLimitObserver = r.onAfterCheckInputsObservable.add(()=>{
            let {pitch: d, yaw: _, roll: g} = xverseRotation2Ue4(r.rotation);
            d = this._limitAngle(d, c),
            _ = this._limitAngle(_, h),
            g = this._limitAngle(g, f),
            r.rotation = ue4Rotation2Xverse({
                pitch: d,
                yaw: _,
                roll: g
            })
        }
        )
    }
    setMainCameraRotationLimitByAnchor(e, t, r) {
        this.maincameraRotLimitObserver != null && this.removeMainCameraRotationLimit();
        const n = this.mainCamera
          , o = ue4Rotation2Xverse_mesh(t)
          , a = ue4Rotation2Xverse_mesh(r);
        a != null && o != null && e.mesh != null && (this.maincameraRotLimitObserver = n.onAfterCheckInputsObservable.add(()=>{
            const s = e.mesh.rotation;
            r.yaw > 0 && (n.rotation.y <= s.y - a.y + o.y ? n.rotation.y = s.y - a.y + o.y : n.rotation.y >= s.y + a.y + o.y && (n.rotation.y = s.y + a.y + o.y)),
            r.pitch > 0 && (n.rotation.x <= s.x - a.x + o.x ? n.rotation.x = s.x - a.x + o.x : n.rotation.x >= s.x + a.x + o.x && (n.rotation.x = s.x + a.x + o.x)),
            r.roll > 0 && (n.rotation.z <= s.z - a.z + o.z ? n.rotation.z = s.z - a.z + o.z : n.rotation.z >= s.z + a.z + o.z && (n.rotation.z = s.z + a.z + o.z))
        }
        ))
    }
    getCameraPose() {
        const e = xversePosition2Ue4({
            x: this.mainCamera.position.x,
            y: this.mainCamera.position.y,
            z: this.mainCamera.position.z
        })
          , t = xverseRotation2Ue4({
            x: this.mainCamera.rotation.x,
            y: this.mainCamera.rotation.y,
            z: this.mainCamera.rotation.z
        });
        return {
            position: e,
            rotation: t
        }
    }
    changeCameraFov(e, t) {
        this.mainCamera.fov = e,
        t != null && (this.mainCamera.fovMode = t == 0 ? Camera$1.FOVMODE_HORIZONTAL_FIXED : Camera$1.FOVMODE_VERTICAL_FIXED)
    }
    controlCameraRotation(e, t, r=.5, n=.5) {
        const o = {
            pitch: n * t * 180,
            yaw: r * e * 180,
            roll: 0
        };
        this.addRot(o)
    }
    addRot(e) {
        const t = this.mainCamera
          , r = ue4Rotation2Xverse_mesh(e);
        r != null && t.rotation.addInPlace(r)
    }
    getCameraFov() {
        return this.mainCamera.fov
    }
    allowMainCameraController() {
        this.mainCamera.attachControl(this.canvas, !0)
    }
    detachMainCameraController() {
        this.mainCamera.detachControl(this.canvas)
    }
    forceChangeSavedCameraPose(e) {
        this.saveCameraPose != null && (e.position != null && (this.saveCameraPose.position = ue4Position2Xverse(e.position)),
        e.rotation != null && (this.saveCameraPose.rotation = ue4Rotation2Xverse(e.rotation)))
    }
    changeToFirstPersonView(e) {
        this.saveCameraPose = {
            position: this.mainCamera.position.clone(),
            rotation: this.mainCamera.rotation.clone()
        },
        this.mainCamera.attachControl(this.canvas, !0),
        e.position != null && (this.mainCamera.position = ue4Position2Xverse(e.position)),
        e.rotation != null && (this.mainCamera.rotation = ue4Rotation2Xverse(e.rotation))
    }
    changeToThirdPersonView() {
        this.saveCameraPose != null && this.mainCamera != null && (this.mainCamera.position = this.saveCameraPose.position.clone(),
        this.mainCamera.rotation = this.saveCameraPose.rotation.clone(),
        this.mainCamera.detachControl(this.canvas))
    }
    switchToMainCamera() {
        this.switchCamera(this.mainCamera)
    }
    switchToCgCamera() {
        this.switchCamera(this.cgCamera)
    }
    moveMainCamera(e, t, r, n, o) {
        this._moveCam(this.mainCamera, this.mainCamera.position, e, this.mainCamera.rotation, t, r, n, o)
    }
}
function uuid$2() {
    return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, i=>{
        const e = Math.random() * 16 | 0;
        return (i === "x" ? e : e & 3 | 8).toString(16)
    }
    )
}
function hashCode(i) {
    let e = 0, t, r;
    if (i == null || i.length === 0)
        return e;
    for (t = 0; t < i.length; t++)
        r = i.charCodeAt(t),
        e = (e << 5) - e + r,
        e |= 0;
    return e
}
const log$u = new Logger$1("XStaticMeshComponent")
  , Te = class {
    constructor(e) {
        E(this, "scene");
        E(this, "_staticmeshes");
        E(this, "_lowModel_group");
        E(this, "_CgPlane");
        E(this, "_rootDir");
        E(this, "_abosoluteUrl");
        E(this, "_partMeshSkinInfo");
        E(this, "_meshInfoJson");
        E(this, "_orijson");
        E(this, "_notUsedRegionLists");
        E(this, "_meshInfoKeys");
        E(this, "_currentUpdateRegionCount");
        E(this, "_currentMeshUsedLod");
        E(this, "_currentPartGroup");
        E(this, "_allowRegionUpdate");
        E(this, "_allowRegionForceLod");
        E(this, "_forceLod");
        E(this, "_scenemanager");
        E(this, "regionIdInCamera");
        E(this, "regionIdInCameraConst");
        E(this, "_cameraInRegionId");
        E(this, "_meshVis");
        E(this, "_doMeshVisChangeNumber");
        E(this, "_meshVisTypeName");
        E(this, "_visCheckDurationFrameNumber");
        E(this, "_regionLodRule");
        E(this, "reg_staticmesh_partupdate", ()=>{
            if (this._allowRegionUpdate && (this.scene.getFrameId(),
            this._meshUpdateFrame()),
            this._allowRegionForceLod) {
                this.scene.getFrameId() % 2 == 0 && this.setOneRegionLod(this._meshInfoKeys[this._currentUpdateRegionCount % this._meshInfoKeys.length].toString(), this._forceLod);
                let t = !0;
                const r = Array.from(this._currentMeshUsedLod.keys());
                if (r.length > 0) {
                    for (let n = 0; n < r.length; ++n)
                        this._currentMeshUsedLod.get(r[n]) != this._forceLod && (t = !1);
                    t && (this._allowRegionForceLod = !1)
                }
            }
        }
        );
        E(this, "setMeshInfo", (e,t="")=>{
            this._abosoluteUrl != e && (this._abosoluteUrl.length > 0 && this.deleteLastRegionMesh(),
            this._partMeshSkinInfo = t,
            this._abosoluteUrl = e,
            this._rootDir = this._abosoluteUrl.slice(0, -4) + "/",
            this.parseJson(this._rootDir + "meshInfo.json").then(()=>{
                this.startMeshUpdate()
            }
            ))
        }
        );
        E(this, "_meshUpdateFrame", ()=>{
            {
                let e = this._meshInfoKeys[this._currentUpdateRegionCount % this._meshInfoKeys.length];
                const t = !0;
                let r = 3;
                if (this._scenemanager != null && this._scenemanager.cameraComponent != null) {
                    const n = this._getMainPlayerPosition();
                    if (n != null) {
                        if (this._cameraInRegionId >= 0) {
                            const a = this.getRegionIdWhichIncludeCamera(n);
                            (this._cameraInRegionId != a || this.regionIdInCamera.length == 0) && (this._cameraInRegionId = a,
                            this.regionIdInCamera = this._getNeighborId(this._cameraInRegionId.toString()),
                            this.regionIdInCameraConst = this.regionIdInCamera.slice());
                            let s = this.regionIdInCamera.pop();
                            for (; s != null; )
                                if (this._notUsedRegionLists.indexOf(s) >= 0)
                                    s = this.regionIdInCamera.pop();
                                else
                                    break;
                            s != null && (e = s.toString())
                        } else
                            this._cameraInRegionId = this.getRegionIdWhichIncludeCamera(n);
                        if (this._currentMeshUsedLod.size == 0 || this._notUsedRegionLists.indexOf(parseInt(e)) >= 0) {
                            e = this._cameraInRegionId.toString();
                            const a = this._getNeighborId(e);
                            for (; a.length == 0 && (e = this.getNearestRegionIdWithCamera(n).toString()),
                            this._notUsedRegionLists.indexOf(parseInt(e)) >= 0; )
                                e = a.pop().toString()
                        }
                        const o = this._meshInfoJson[this._cameraInRegionId.toString()].lod;
                        r = 3,
                        this._cameraInRegionId.toString() == e ? r = this._regionLodRule[0] : o[0].indexOf(parseInt(e)) >= 0 ? r = this._regionLodRule[1] : o[1].indexOf(parseInt(e)) >= 0 ? r = this._regionLodRule[2] : o[2].indexOf(parseInt(e)) >= 0 ? r = this._regionLodRule[3] : r = this._regionLodRule[4]
                    }
                }
                this.setOneRegionLod(e, r, t),
                this.updateRegionNotInLocalNeighbor(),
                this.cleanRootNodes()
            }
        }
        );
        E(this, "updateRegionNotInLocalNeighbor", ()=>{
            Array.from(this._currentMeshUsedLod.keys()).forEach(t=>{
                this.regionIdInCameraConst.indexOf(parseInt(t)) < 0 && this.setOneRegionLod(t, -1)
            }
            )
        }
        );
        E(this, "cleanRootNodes", ()=>{
            if (this.scene.getFrameId() % 3 == 0) {
                const e = [];
                this.scene.rootNodes.forEach(t=>{
                    (t.getClassName() == "TransformNode" && t.getChildren().length == 0 || t.getClassName() == "Mesh" && t.name == "__root__" && t.getChildren().length == 0) && e.push(t)
                }
                ),
                e.forEach(t=>{
                    t.dispose()
                }
                )
            }
        }
        );
        E(this, "setOneRegionLod", (e,t,r=!0)=>{
            this._currentUpdateRegionCount++;
            const n = this._calHashCode(this._rootDir)
              , o = "region_" + n + "_" + e;
            if (t < 0) {
                this._currentMeshUsedLod.has(e) && (this._currentMeshUsedLod.delete(e),
                this._currentPartGroup.delete(o),
                this.deleteMeshesByCustomProperty("group", "region_" + n + "_" + e));
                return
            }
            const a = this._rootDir + e + "_lod" + t + "_xverse.glb"
              , s = this._currentMeshUsedLod.get(e);
            this._currentPartGroup.add(o),
            s != null ? s != t && (this._currentMeshUsedLod.set(e, t),
            this._scenemanager.addNewLowPolyMesh({
                url: a,
                group: "region_" + n + "_" + e,
                pick: !0,
                lod: t,
                skinInfo: this._partMeshSkinInfo
            }, [{
                group: "region_" + n + "_" + e,
                mode: 0
            }])) : (this._currentMeshUsedLod.set(e, t),
            this._scenemanager.addNewLowPolyMesh({
                url: a,
                group: "region_" + n + "_" + e,
                pick: !0,
                lod: t,
                skinInfo: this._partMeshSkinInfo
            }))
        }
        );
        E(this, "checkPointInView", ({x: e, y: t, z: r})=>{
            const n = ue4Position2Xverse({
                x: e,
                y: t,
                z: r
            });
            if (!n)
                return !1;
            for (let o = 0; o < 6; o++)
                if (this.scene.frustumPlanes[o].dotCoordinate(n) < 0)
                    return !1;
            return !0
        }
        );
        E(this, "addNewLowPolyMesh", (e,t,r)=>{
            if (!e.url.endsWith("glb") && !e.url.startsWith("blob:"))
                return e.url.endsWith("zip") ? (this.setMeshInfo(e.url, e.skinInfo),
                Promise.resolve(!0)) : (log$u.error("[Engine] input model path is error! ", e.url),
                Promise.reject(new XLowpolyModelError("[Engine] input model path is error! " + e.url)));
            {
                const n = e.url;
                return new Promise((o,a)=>this._scenemanager.urlTransformer(e.url).then(s=>{
                    e.url = s;
                    const l = new XStaticMeshFromOneGltf(this.scene,e)
                      , u = Date.now();
                    return new Promise((c,h)=>{
                        l.loadMesh(r, !0).then(f=>{
                            const d = Date.now();
                            if (this._scenemanager.engineRunTimeStats.timeArray_loadStaticMesh.add(d - u),
                            f == !0) {
                                const _ = this.getLowModelType(e);
                                let g = 0;
                                if (this._lowModel_group.has(_) && (g = this._lowModel_group.get(_).length),
                                r != null && this._scenemanager.currentShader != null && this._scenemanager.currentShader.name != r.name && l.setMaterial(this._scenemanager.currentShader),
                                this._allowRegionUpdate == !1 && _.startsWith("region_"))
                                    l.dispose();
                                else if (this._staticmeshes.push(l),
                                this.lowmodelGroupMapAddValue(_, l),
                                t != null && t.length > 0) {
                                    const m = [];
                                    for (let v = 0; v < t.length; ++v)
                                        m.push(t[v].group),
                                        this.updateLowModelGroup(t[v], _, g)
                                }
                                this._scenemanager.engineRunTimeStats.timeArray_updateStaticMesh.add(Date.now() - d),
                                c(!0)
                            } else
                                h(new XLowpolyModelError("[Engine] after lowmodel error!"))
                        }
                        ).catch(f=>{
                            log$u.error("[Engine] load Mesh [" + n + "] error! " + f),
                            h(new XLowpolyModelError(`[Engine] load Mesh [${n}] error! ${f}`))
                        }
                        )
                    }
                    )
                }
                ).then(s=>{
                    s == !0 ? (log$u.info(`[Engine] load Mesh [${n}] successfully.`),
                    o(!0)) : a(!1)
                }
                ).catch(s=>{
                    log$u.error("[Engine] addNewLowPolyMesh [" + n + "] error! " + s),
                    a(new XLowpolyModelError(`[Engine] addNewLowPolyMesh [${n}] error! ${s}`))
                }
                ))
            }
        }
        );
        E(this, "toggleLowModelVisibility", e=>{
            const {vis: t, groupName: r="", skinInfo: n=""} = e;
            this._meshVis = t,
            this._meshVisTypeName = {
                groupName: r,
                skinInfo: n
            },
            this._doMeshVisChangeNumber = 0,
            r == Te.ALL_MESHES || this._currentPartGroup.has(r) == !0 || this._partMeshSkinInfo == n ? t == !1 ? (this._visCheckDurationFrameNumber = 100,
            this.stopMeshUpdate()) : (this._visCheckDurationFrameNumber = 1,
            this.startMeshUpdate()) : this._visCheckDurationFrameNumber = 1
        }
        );
        E(this, "reg_staticmesh_visibility", ()=>{
            if (this._doMeshVisChangeNumber >= 0)
                if (this._doMeshVisChangeNumber < this._visCheckDurationFrameNumber)
                    if (this._doMeshVisChangeNumber = this._doMeshVisChangeNumber + 1,
                    this._meshVisTypeName.groupName == Te.ALL_MESHES)
                        this._lowModel_group.forEach((e,t)=>{
                            for (let r = 0, n = e.length; r < n; ++r)
                                e[r].toggleVisibility(this._meshVis)
                        }
                        );
                    else {
                        if (this._lowModel_group.has(this._meshVisTypeName.groupName))
                            for (let e = 0; e < this._lowModel_group.get(this._meshVisTypeName.groupName).length; ++e)
                                this._lowModel_group.get(this._meshVisTypeName.groupName)[e].toggleVisibility(this._meshVis);
                        if (this._meshVisTypeName.skinInfo != "")
                            for (let e = 0; e < this._staticmeshes.length; ++e)
                                this._staticmeshes[e].skinInfo == this._meshVisTypeName.skinInfo && this._staticmeshes[e].toggleVisibility(this._meshVis)
                    }
                else
                    this._meshVis = !0,
                    this._meshVisTypeName = {
                        groupName: "",
                        skinInfo: ""
                    },
                    this._doMeshVisChangeNumber = -1
        }
        );
        E(this, "_getMeshesByCustomProperty", (e,t)=>{
            let r = [];
            return this._staticmeshes.forEach(n=>{
                n[e] != null && n[e] == t && (r = r.concat(n.meshes))
            }
            ),
            r
        }
        );
        this._lowModel_group = new Map,
        this._staticmeshes = [],
        this._meshInfoJson = null,
        this._meshInfoKeys = [],
        this._currentUpdateRegionCount = 0,
        this._abosoluteUrl = "",
        this._partMeshSkinInfo = "",
        this._forceLod = 3,
        this._allowRegionUpdate = !1,
        this._allowRegionForceLod = !1,
        this._currentMeshUsedLod = new Map,
        this._currentPartGroup = new Set,
        this._scenemanager = e,
        this.scene = e.Scene,
        this.regionIdInCamera = [],
        this.regionIdInCameraConst = [],
        this._cameraInRegionId = -1,
        this._rootDir = "",
        this._meshVis = !0,
        this._meshVisTypeName = {
            groupName: "",
            skinInfo: ""
        },
        this._doMeshVisChangeNumber = -1,
        this._visCheckDurationFrameNumber = -1,
        this._regionLodRule = [0, 1, 3, 3, -1],
        this.initCgLowModel(),
        this._regionPartLoop()
    }
    get cameraInRegionId() {
        return this._cameraInRegionId
    }
    setRegionLodRule(e) {
        return e.length != 5 ? !1 : (e.forEach(t=>{}
        ),
        this._regionLodRule = e,
        !0)
    }
    get lowModel_group() {
        return this._lowModel_group
    }
    _regionPartLoop() {
        this.scene.registerBeforeRender(this.reg_staticmesh_partupdate),
        this.scene.registerAfterRender(this.reg_staticmesh_visibility)
    }
    _globalSearchCameraInWhichRegion(e, t) {
        let r = -1;
        for (let n = 0; n < t.length; ++n) {
            const o = this._meshInfoJson[t[n].toString()].boundingbox
              , a = o[0]
              , s = o[1];
            if (e.x >= a[0] && e.x <= s[0] && e.y >= a[1] && e.y <= s[1] && e.z >= a[2] && e.z <= s[2] || e.x >= s[0] && e.x <= a[0] && e.y >= s[1] && e.y <= a[1] && e.z >= s[2] && e.z <= a[2]) {
                r = parseInt(t[n].toString());
                break
            }
        }
        return r
    }
    getRegionIdByPosition(e) {
        return this.getRegionIdWhichIncludeCamera(e)
    }
    getRegionIdWhichIncludeCamera(e) {
        let t = -1;
        if (this._allowRegionUpdate == !1)
            return t;
        if (this._cameraInRegionId == -1 ? t = this._globalSearchCameraInWhichRegion(e, this._meshInfoKeys) : (t = this._globalSearchCameraInWhichRegion(e, this.regionIdInCameraConst),
        t == -1 && (t = this._globalSearchCameraInWhichRegion(e, this._meshInfoKeys))),
        t == -1) {
            let r = 1e7;
            for (let n = 0; n < this._meshInfoKeys.length; ++n) {
                const o = this._meshInfoJson[this._meshInfoKeys[n]].center
                  , a = Math.abs(e.x - o[0]) + Math.abs(e.y - o[1]);
                r > a && (r = a,
                t = parseInt(this._meshInfoKeys[n]))
            }
        }
        return t
    }
    getNearestRegionIdWithCamera(e) {
        let t = 1
          , r = 1e7;
        for (let n = 0; n < this._meshInfoKeys.length; ++n) {
            if (this._notUsedRegionLists.indexOf(parseInt(this._meshInfoKeys[n])) >= 0)
                continue;
            const o = this._meshInfoJson[this._meshInfoKeys[n]].center
              , a = Math.abs(e.x - o[0]) + Math.abs(e.y - o[1]);
            r > a && (r = a,
            t = parseInt(this._meshInfoKeys[n]))
        }
        return t
    }
    _getNeighborId(e) {
        const t = this._meshInfoJson[e].lod;
        let r = [];
        const n = Object.keys(t);
        for (let o = n.length - 1; o >= 0; --o)
            r = r.concat(t[n[o]]);
        return r.push(parseInt(e)),
        r
    }
    _getMainPlayerPosition() {
        const e = this._scenemanager.cameraComponent.getCameraPose().position
          , t = this._scenemanager.avatarComponent.getMainAvatar();
        if (t != null && t != null) {
            const r = t.position;
            if (r != null)
                return r
        }
        return e
    }
    _calHashCode(e) {
        return hashCode(e) + "_" + this._partMeshSkinInfo
    }
    forceAllRegionLod(e=3) {
        e < 0 && (e = 0),
        e > 3 && (e = 3),
        this.stopMeshUpdate(),
        this._allowRegionForceLod = !0,
        this._forceLod = e
    }
    deleteLastRegionMesh() {
        if (this._rootDir != "") {
            const e = this._calHashCode(this._rootDir);
            this._currentMeshUsedLod.clear(),
            this._currentPartGroup.clear(),
            this._meshInfoJson = null,
            this._meshInfoKeys = [],
            this._currentUpdateRegionCount = 0,
            this._orijson = null,
            this._notUsedRegionLists = [],
            this._partMeshSkinInfo = "",
            this._abosoluteUrl = "",
            this.stopMeshUpdate(),
            this.deleteMeshesByCustomProperty("group", "region_" + e, !0)
        }
    }
    startMeshUpdate() {
        this._allowRegionUpdate == !1 && this._meshInfoJson != null && this._abosoluteUrl != "" && this._meshInfoKeys.length > 0 && (this._allowRegionUpdate = !0)
    }
    stopMeshUpdate() {
        this._allowRegionUpdate = !1
    }
    parseJson(e) {
        return new Promise((t,r)=>this._scenemanager.urlTransformer(e).then(n=>{
            const o = new XMLHttpRequest;
            o.open("get", n),
            o.send(null),
            o.onload = ()=>{
                if (o.status == 200) {
                    const a = JSON.parse(o.responseText);
                    this._orijson = a,
                    this._meshInfoJson = this._orijson.usedRegion,
                    this._notUsedRegionLists = this._orijson.notUsedRegion,
                    this._meshInfoKeys = Object.keys(this._meshInfoJson),
                    log$u.info("[Engine] parse zip mesh info successful"),
                    t()
                }
            }
            ,
            o.onerror = ()=>{
                log$u.error(`[Engine] load zip mesh info json error, (provided by blob): ${n}`),
                r(new XLowpolyJsonError(`[Engine] load zip mesh info json error, (provided by blob): ${n}`))
            }
        }
        ).catch(n=>{
            log$u.error(`[Engine] load zip mesh info json error: ${n}, link:${e}`),
            r(new XLowpolyJsonError(`[Engine] load zip mesh info json error: ${n}, link: ${e}`))
        }
        ))
    }
    initCgLowModel() {
        const e = MeshBuilder.CreatePlane("CgPlane", {
            size: 400
        });
        e.position = new Vector3(0,1010,0),
        e.rotation = new Vector3(3 * Math.PI / 2,0,0),
        this._CgPlane = new XStaticMesh({
            id: "CgPlane",
            mesh: e,
            xtype: EMeshType.Cgplane
        }),
        this._CgPlane.hide()
    }
    getLowModelType(e) {
        let t = "";
        return e.group != null ? t = e.group : t = "default",
        t
    }
    lowmodelGroupMapAddValue(e, t) {
        const r = this._lowModel_group.get(e);
        r != null ? (r.push(t),
        this._lowModel_group.set(e, r)) : this._lowModel_group.set(e, [t])
    }
    updateLowModelGroup(e, t, r) {
        let n = r;
        e.group == t || (n = -1),
        e.mode == 0 ? this.deleteLowModelGroup(e.group, n) : e.mode == 1 ? this.toggleVisibleLowModelGroup(!1, e.group, n) : e.mode == 2 && this.toggleVisibleLowModelGroup(!0, e.group, n)
    }
    toggleVisibleLowModelGroup(e, t, r=-1) {
        if (this._lowModel_group.has(t)) {
            const n = this._lowModel_group.get(t);
            let o = n.length;
            r >= 0 && o >= r && (o = r);
            for (let a = 0; a < o; ++a)
                n[a].toggleVisibility(e)
        }
    }
    deleteLowModelGroup(e, t=-1) {
        if (this._lowModel_group.has(e)) {
            const o = this._lowModel_group.get(e);
            let a = o.length;
            t >= 0 && a >= t && (a = t);
            for (let s = 0; s < a; ++s)
                o[s].dispose();
            t >= 0 ? this._lowModel_group.set(e, this._lowModel_group.get(e).slice(a)) : this._lowModel_group.delete(e)
        }
        const r = this._lowModel_group.get(e)
          , n = [];
        r != null && r.length > 0 ? this._staticmeshes.forEach(o=>{
            if (o.group != e)
                n.push(o);
            else
                for (let a = 0; a < r.length; ++a)
                    o.groupUuid == r[a].groupUuid && n.push(o)
        }
        ) : this._staticmeshes.forEach(o=>{
            o.group != e && n.push(o)
        }
        ),
        this._staticmeshes = n
    }
    deleteMeshesByGroup(e) {
        this.deleteLowModelGroup(e)
    }
    deleteMeshesById(e) {
        this.deleteMeshesByCustomProperty("id", e)
    }
    deleteMeshesByLoD(e) {
        this.deleteMeshesByCustomProperty("lod", e)
    }
    deleteMeshesBySkinInfo(e) {
        this.deleteMeshesByCustomProperty("skinInfo", e)
    }
    removeMeshesFromSceneByGroup(e) {
        this.removeMeshesFromSceneByCustomProperty("group", e)
    }
    removeMeshesFromSceneById(e) {
        this.removeMeshesFromSceneByCustomProperty("id", e)
    }
    addMeshesToSceneByGroup(e) {
        this.addMeshesToSceneByCustomProperty("group", e)
    }
    addMeshesToSceneById(e) {
        this.addMeshesToSceneByCustomProperty("id", e)
    }
    removeMeshesFromSceneByCustomProperty(e, t, r=!1) {
        this._staticmeshes.forEach(n=>{
            n.isinscene && n[e] != null && (r ? n[e].indexOf(t) < 0 || n.removeFromScene() : n[e] != t || n.removeFromScene())
        }
        )
    }
    addMeshesToSceneByCustomProperty(e, t, r=!1) {
        this._staticmeshes.forEach(n=>{
            n.isinscene == !1 && n[e] != null && (r ? n[e].indexOf(t) < 0 || n.addToScene() : n[e] != t || n.addToScene())
        }
        )
    }
    deleteMeshesByCustomProperty(e, t, r=!1) {
        const n = [];
        this._staticmeshes.forEach(a=>{
            a[e] != null && (r ? a[e].indexOf(t) < 0 ? n.push(a) : a.dispose() : a[e] != t ? n.push(a) : a.dispose())
        }
        ),
        this._staticmeshes = n;
        const o = Array.from(this._lowModel_group.keys());
        for (let a = 0; a < o.length; ++a) {
            const s = o[a]
              , l = this._lowModel_group.get(s);
            if (l != null) {
                const u = [];
                for (let c = 0; c < l.length; ++c)
                    l[c][e] != null && (r ? l[c][e].indexOf(t) < 0 && u.push(l[c]) : l[c][e] != t && u.push(l[c]));
                u.length > 0 ? this._lowModel_group.set(s, u) : this._lowModel_group.delete(s)
            }
        }
    }
    getMeshes() {
        let e = [];
        for (let t = 0; t < this._staticmeshes.length; ++t)
            e = e.concat(this._staticmeshes[t].meshes);
        return e
    }
    getCgMesh() {
        return this._CgPlane
    }
    getMeshesByGroup(e="default") {
        const t = this._lowModel_group.get(e);
        if (t != null) {
            let r = [];
            for (let n = 0; n < t.length; ++n)
                r = r.concat(t[n].meshes);
            return r
        } else
            return null
    }
    getMeshesByGroup2(e="default") {
        return this._getMeshesByCustomProperty("group", e)
    }
}
;
let XStaticMeshComponent = Te;
E(XStaticMeshComponent, "ALL_MESHES", "ALL_MESHES");
class XStaticMeshFromOneGltf {
    constructor(e, t) {
        E(this, "_scene");
        E(this, "_url");
        E(this, "_group");
        E(this, "_pickable");
        E(this, "_meshes");
        E(this, "_id");
        E(this, "_lod");
        E(this, "_groupUuid");
        E(this, "_isInScene");
        E(this, "_skinInfo");
        E(this, "loadMesh", (e,t)=>{
            const r = this._meshes.length
              , n = t ? 1 : 0
              , o = this._url;
            return SceneLoader.LoadAssetContainerAsync("", o, this._scene, ()=>{
                this._scene.blockMaterialDirtyMechanism = !0
            }
            , ".glb").then(a=>{
                for (let s = a.materials.length - 1; s >= 0; --s)
                    a.materials[s].dispose();
                this._scene.blockMaterialDirtyMechanism = !0;
                for (let s = 0; s < a.meshes.length; ++s) {
                    const l = a.meshes[s];
                    if ("instances"in l) {
                        "visibility"in l && (l.visibility = 0),
                        "isPickable"in l && (l.isPickable = this._pickable),
                        e != null && (l.material = e),
                        "hasVertexAlpha"in l && (l.hasVertexAlpha = !1);
                        const u = new XStaticMesh({
                            id: this._groupUuid + "-" + Math.random().toString(36).substr(2, 5),
                            mesh: l,
                            lod: this._lod,
                            group: this._group,
                            url: this._url,
                            xtype: EMeshType.XStaticMesh,
                            skinInfo: this._skinInfo
                        });
                        this._meshes.push(u)
                    }
                    this._scene.addMesh(l)
                }
                return !0
            }
            ).then(()=>{
                this._isInScene = !0;
                for (let a = r; a < this._meshes.length; ++a)
                    this._meshes[a].mesh.visibility = n;
                return Promise.resolve(!0)
            }
            ).catch(a=>{
                log$u.error("[Engine] input gltf mesh uri error! " + a),
                Promise.reject(new XLowpolyModelError("[Engine] input gltf mesh uri error! " + a))
            }
            )
        }
        );
        this._meshes = [],
        this._scene = e,
        this._url = t.url,
        t.group != null ? this._group = t.group : this._group = "default",
        t.pick != null ? this._pickable = t.pick : this._pickable = !1,
        t.id != null ? this._id = t.id : this._id = "default",
        t.lod != null ? this._lod = t.lod : this._lod = -1,
        t.skinInfo != null ? this._skinInfo = t.skinInfo : this._skinInfo = "default",
        this._groupUuid = uuid$2(),
        this._isInScene = !1
    }
    get isinscene() {
        return this._isInScene
    }
    get groupUuid() {
        return this._groupUuid
    }
    get skinInfo() {
        return this._skinInfo
    }
    get group() {
        return this._group
    }
    get meshes() {
        return this._meshes
    }
    get url() {
        return this._url
    }
    get id() {
        return this._id
    }
    get lod() {
        return this._lod
    }
    removeFromScene() {
        if (this._isInScene) {
            this._isInScene = !1;
            for (let e = 0, t = this._meshes.length; e < t; ++e)
                this._meshes[e].mesh != null && this._scene.removeMesh(this._meshes[e].mesh)
        }
    }
    addToScene() {
        if (this._isInScene == !1) {
            this._isInScene = !0;
            for (let e = 0, t = this._meshes.length; e < t; ++e)
                this._meshes[e].mesh != null && this._scene.addMesh(this._meshes[e].mesh)
        }
    }
    toggleVisibility(e) {
        const t = e ? 1 : 0;
        for (let r = 0, n = this._meshes.length; r < n; ++r)
            "visibility"in this._meshes[r].mesh && (this._meshes[r].mesh.visibility = t)
    }
    togglePickable(e) {
        for (let t = 0, r = this._meshes.length; t < r; ++t)
            "isPickable"in this._meshes[t].mesh && (this._meshes[t].mesh.isPickable = e)
    }
    setMaterial(e) {
        for (let t = 0, r = this._meshes.length; t < r; ++t)
            "material"in this._meshes[t].mesh && (this._meshes[t].mesh.material = e)
    }
    dispose() {
        for (let e = 0, t = this._meshes.length; e < t; ++e)
            this._meshes[e].mesh.dispose(!1, !1)
    }
}
const log$t = new Logger$1("XSceneManager");
var ECurrentShaderMode = (i=>(i[i.default = 0] = "default",
i[i.video = 1] = "video",
i[i.pano = 2] = "pano",
i))(ECurrentShaderMode || {})
  , EImageQuality = (i=>(i[i.low = 0] = "low",
i[i.mid = 1] = "mid",
i[i.high = 2] = "high",
i))(EImageQuality || {});
class XSceneManager {
    constructor(e, t) {
        E(this, "scene");
        E(this, "engine");
        E(this, "canvas");
        E(this, "gl");
        E(this, "_yuvInfo");
        E(this, "cameraParam");
        E(this, "shaderMode");
        E(this, "panoInfo");
        E(this, "_initEngineScaleNumber");
        E(this, "_forceKeepVertical", !1);
        E(this, "_currentShader");
        E(this, "_currentPanoId");
        E(this, "_renderStatusCheckCount", 0);
        E(this, "_renderStatusNotChecktCount", 0);
        E(this, "_nonlinearCanvasResize", !1);
        E(this, "_bChangeEngineSize", !0);
        E(this, "_cameraManager");
        E(this, "_lowpolyManager");
        E(this, "_materialManager");
        E(this, "_statisticManager");
        E(this, "_breathPointManager");
        E(this, "_skytv");
        E(this, "_mv", []);
        E(this, "_decalManager");
        E(this, "_lightManager");
        E(this, "_avatarManager");
        E(this, "urlTransformer");
        E(this, "_billboardManager");
        E(this, "_backgroundImg");
        E(this, "engineRunTimeStats");
        E(this, "uploadHardwareSystemInfo", ()=>{
            const e = this.statisticComponent.getHardwareRenderInfo()
              , t = this.statisticComponent.getSystemInfo()
              , r = {
                driver: t.driver,
                vender: t.vender,
                webgl: t.version,
                os: t.os
            };
            log$t.warn(JSON.stringify(e)),
            log$t.warn(JSON.stringify(r))
        }
        );
        E(this, "addNewLowPolyMesh", async(e,t)=>(this._currentShader == null && await this.initSceneManager(),
        this._lowpolyManager.addNewLowPolyMesh(e, t, this._currentShader)));
        E(this, "initSceneManager", async()=>(await this._materialManager.initMaterial(),
        this.applyShader()));
        E(this, "registerAfterRender", ()=>{
            var e;
            if (this._forceKeepVertical) {
                const t = this.canvas.width
                  , r = this.canvas.height;
                let n = 0
                  , o = [[0, 0, 0, 0], [0, 0, 0, 0]];
                if (((e = this._cameraManager.MainCamera) == null ? void 0 : e.fovMode) === Camera$1.FOVMODE_HORIZONTAL_FIXED ? (n = Math.ceil((r - this._yuvInfo.height * t / this._yuvInfo.width) / 2),
                o = [[0, 0, t, n], [0, r - n, t, n]]) : (n = Math.ceil((t - this._yuvInfo.width * r / this._yuvInfo.height) / 2),
                o = [[0, 0, n, r], [t - n, 0, n, r]]),
                n > 0) {
                    this.gl.enable(this.gl.SCISSOR_TEST);
                    for (let a = 0; a < o.length; ++a)
                        this.gl.scissor(o[a][0], o[a][1], o[a][2], o[a][3]),
                        this.gl.clearColor(0, 0, 0, 1),
                        this.gl.clear(this.gl.COLOR_BUFFER_BIT);
                    this.gl.disable(this.gl.SCISSOR_TEST)
                }
            }
        }
        );
        E(this, "resetRender", ()=>{
            this.scene.environmentTexture && (this.scene.environmentTexture._texture ? this.lightComponent.setIBL(this.scene.environmentTexture._texture.url) : this.scene.environmentTexture.url && this.lightComponent.setIBL(this.scene.environmentTexture.url))
        }
        );
        const r = /iphone|ipad/gi.test(window.navigator.userAgent) || t.disableWebGL2
          , n = new Engine(e,!0,{
            preserveDrawingBuffer: !0,
            stencil: !0,
            disableWebGL2Support: r
        },!0)
          , o = new Scene(n);
        this.scene = o,
        this.engine = n,
        this.canvas = e,
        this.scene.clearColor = new Color4(.7,.7,.7,1),
        this.engine.getCaps().parallelShaderCompile = void 0,
        this._initEngineScaleNumber = this.engine.getHardwareScalingLevel(),
        this.engine.enableOfflineSupport = !1,
        this.engine.doNotHandleContextLost = !0,
        this.scene.clearCachedVertexData(),
        this.scene.cleanCachedTextureBuffer(),
        this.urlTransformer = t.urlTransformer || (s=>Promise.resolve(s)),
        t.logger && Logger$1.setLogger(t.logger),
        this.gl = e.getContext("webgl2", {
            preserveDrawingBuffer: !0
        }) || e.getContext("webgl", {
            preserveDrawingBuffer: !0
        }) || e.getContext("experimental-webgl", {
            preserveDrawingBuffer: !0
        }),
        this.gl.pixelStorei(this.gl.UNPACK_ALIGNMENT, 1),
        this._currentPanoId = 0,
        t.forceKeepVertical != null && (this._forceKeepVertical = t.forceKeepVertical),
        t.panoInfo != null && (this.panoInfo = t.panoInfo),
        t.shaderMode != null && (this.shaderMode = t.shaderMode),
        t.yuvInfo != null ? this._yuvInfo = t.yuvInfo : this._yuvInfo = {
            width: t.videoResOriArray[0].width,
            height: t.videoResOriArray[0].height,
            fov: 50
        },
        t.cameraParam != null && (this.cameraParam = t.cameraParam),
        t.nonlinearCanvasResize != null && (this._nonlinearCanvasResize = t.nonlinearCanvasResize),
        this._cameraManager = new XCameraComponent(this.canvas,this.scene,{
            cameraParam: this.cameraParam,
            yuvInfo: this._yuvInfo,
            forceKeepVertical: this._forceKeepVertical
        }),
        this._lowpolyManager = new XStaticMeshComponent(this),
        this._materialManager = new XMaterialComponent(this,{
            videoResOriArray: t.videoResOriArray,
            yuvInfo: this._yuvInfo,
            panoInfo: this.panoInfo,
            shaderMode: this.shaderMode
        }),
        this._statisticManager = new XStats(this),
        this._breathPointManager = new XBreathPointManager(this),
        this._decalManager = new XDecalManager(this),
        this._avatarManager = new XAvatarManager(this),
        this._billboardManager = new XBillboardManager(this),
        this.billboardComponent.loadBackGroundTexToIDB(),
        this._lightManager = new XLightManager(this),
        this.postprocessing(),
        this.initSceneManager(),
        this.engineRunTimeStats = new XEngineRunTimeStats,
        /iphone/gi.test(window.navigator.userAgent) && window.devicePixelRatio && window.devicePixelRatio === 3 && window.screen.width === 375 && window.screen.height === 812 ? this.engine.setHardwareScalingLevel(this._initEngineScaleNumber * 2) : this.engine.setHardwareScalingLevel(this._initEngineScaleNumber * 1.8),
        this.scene.registerBeforeRender(()=>{
            this._nonlinearCanvasResize && this._bChangeEngineSize && (this.setEngineSize(this._yuvInfo),
            this._bChangeEngineSize = !1)
        }
        ),
        this.scene.registerAfterRender(()=>{
            this._nonlinearCanvasResize || this.registerAfterRender()
        }
        ),
        window.addEventListener("resize", ()=>{
            this._nonlinearCanvasResize ? this._bChangeEngineSize = !0 : this.engine.resize()
        }
        ),
        XBillboardManager.alphaWidthMap = getAlphaWidthMap("Arial", this.scene),
        this.uploadHardwareSystemInfo()
    }
    get yuvInfo() {
        return this.getCurrentShaderMode() == 1 ? this._yuvInfo : {
            width: -1,
            height: -1,
            fov: -1
        }
    }
    set yuvInfo(e) {
        this.getCurrentShaderMode() == 1 && (this._yuvInfo = e,
        this._cameraManager.cameraFovChange(e))
    }
    get mainScene() {
        return this.scene
    }
    get cameraComponent() {
        return this._cameraManager
    }
    get staticmeshComponent() {
        return this._lowpolyManager
    }
    get materialComponent() {
        return this._materialManager
    }
    get statisticComponent() {
        return this._statisticManager
    }
    get avatarComponent() {
        return this._avatarManager
    }
    get lightComponent() {
        return this._lightManager
    }
    get Engine() {
        return this.engine
    }
    get Scene() {
        return this.scene
    }
    get billboardComponent() {
        return this._billboardManager
    }
    get breathPointComponent() {
        return this._breathPointManager
    }
    get skytvComponent() {
        return this._skytv
    }
    get mvComponent() {
        return this._mv
    }
    get decalComponent() {
        return this._decalManager
    }
    get currentShader() {
        return this._currentShader
    }
    get initEngineScaleNumber() {
        return this._initEngineScaleNumber
    }
    setImageQuality(e) {
        e == 0 ? (this.engine.setHardwareScalingLevel(this._initEngineScaleNumber * 1.8),
        log$t.info("[Engine] change image quality to low, [" + this._initEngineScaleNumber * 1.8 + "]")) : e == 1 ? (this.engine.setHardwareScalingLevel(this._initEngineScaleNumber * 1.5),
        log$t.info("[Engine] change image quality to mid, [" + this._initEngineScaleNumber * 1.5 + "]")) : e == 2 && (this.engine.setHardwareScalingLevel(this._initEngineScaleNumber * 1),
        log$t.info("[Engine] change image quality to high, [" + this._initEngineScaleNumber * 1 + "]"))
    }
    setNonlinearCanvasResize(e) {
        this._nonlinearCanvasResize = e,
        this._bChangeEngineSize = e,
        e || this.engine.resize()
    }
    setBackgroundColor(e) {
        this.scene.clearColor = new Color4(e.r,e.g,e.b,e.a)
    }
    setBackgroundImg(e) {
        return this._backgroundImg != null && this._backgroundImg.url == e ? Promise.resolve(!0) : new Promise((t,r)=>{
            this.urlTransformer(e).then(n=>{
                this._backgroundImg == null ? this._backgroundImg = {
                    layer: new Layer("tex_background_" + Date.now(),n,this.Scene,!0),
                    url: e
                } : this._backgroundImg.url != e && this._backgroundImg.layer != null && this._backgroundImg.layer.texture != null && (this._backgroundImg.layer.texture.updateURL(n),
                this._backgroundImg.layer.name = "tex_background_" + Date.now(),
                this._backgroundImg.url = e),
                t(!0)
            }
            ).catch(n=>{
                log$t.error(`[Engine] set background image Error: ${n}`),
                r(`[Engine] set background image Error: ${n}`)
            }
            )
        }
        )
    }
    cleanTheWholeScene() {
        const e = this.scene.getFrameId();
        this.scene.onBeforeRenderObservable.clear(),
        this.scene.onAfterRenderObservable.clear(),
        this.scene.clearCachedVertexData(),
        this.scene.cleanCachedTextureBuffer(),
        this.scene.registerBeforeRender(()=>{
            this.scene.getFrameId() - e > 5 && this.scene.dispose()
        }
        )
    }
    getAreaAvatar(e, t) {
        const r = [];
        return this._avatarManager.getAvatarList().forEach(n=>{
            const o = e
              , a = n.position;
            a && o && calcDistance3D(o, a) < t && r.push(n.id)
        }
        ),
        r
    }
    setEngineSize(e) {
        const t = e.width
          , r = e.height
          , n = this.canvas.width;
        this.canvas.height,
        this.engine.setSize(Math.round(n), Math.round(n * (r / t)))
    }
    getCurrentShaderMode() {
        return this._currentShader === this._materialManager.getDefaultShader() ? 0 : this._currentShader === this._materialManager.getPureVideoShader() ? 1 : 2
    }
    addSkyTV(e, t) {
        return this._skytv = new XTelevision(this.scene,e,this,t),
        this._skytv
    }
    addMv(e, t) {
        this._mv.push(new XTelevision(this.scene,e,this,t))
    }
    addMeshInfo(e) {
        this._lowpolyManager.setMeshInfo(e)
    }
    applyShader() {
        return new Promise((e,t)=>{
            this.shaderMode == EShaderMode.videoAndPano || this.shaderMode == EShaderMode.video ? this.changeVideoShaderForLowModel() : this.shaderMode == EShaderMode.default && this.changeDefaultShaderForLowModel(),
            e(!0)
        }
        )
    }
    changeHardwareScaling(e) {
        e < 1 ? e = 1 : e > 2.5 && (e = 2.5),
        this._bChangeEngineSize = !0,
        this.engine.setHardwareScalingLevel(this._initEngineScaleNumber * e)
    }
    getCurrentUsedPanoId() {
        return this._currentPanoId
    }
    render() {
        try {
            this.scene.render()
        } catch (e) {
            throw log$t.error(`[Engine] Render Error: ${e}`),
            e
        }
    }
    isReadyToRender(e) {
        const {checkMesh: t=!0, checkEffect: r=!1, checkPostProgress: n=!1, checkParticle: o=!1, checkAnimation: a=!1, materialNameWhiteLists: s=[]} = e;
        if (this.scene._isDisposed)
            return log$t.error("[Engine] this.scene._isDisposed== false "),
            !1;
        let l;
        const u = this.scene.getEngine();
        if (r && !u.areAllEffectsReady())
            return log$t.error("[Engine] engine.areAllEffectsReady == false"),
            !1;
        if (a && this.scene._pendingData.length > 0)
            return log$t.error("[Engine] scene._pendingData.length > 0 && animation error"),
            !1;
        if (t) {
            for (l = 0; l < this.scene.meshes.length; l++) {
                const c = this.scene.meshes[l];
                if (!c.isEnabled() || !c.subMeshes || c.subMeshes.length === 0 || c != null && c.material != null && !(c.material.name.startsWith("Pure") || c.material.name.startsWith("Pano")))
                    continue;
                if (!c.isReady(!0))
                    return log$t.error(`[Engine] scene. mesh isReady == false, mesh name:${c.name}, mesh xtype: ${c == null ? void 0 : c.xtype}, mesh xgroup: ${c == null ? void 0 : c.xgroup}, mesh xskinInfo: ${c == null ? void 0 : c.xskinInfo}`),
                    !1;
                const h = c.hasThinInstances || c.getClassName() === "InstancedMesh" || c.getClassName() === "InstancedLinesMesh" || u.getCaps().instancedArrays && c.instances.length > 0;
                for (const f of this.scene._isReadyForMeshStage)
                    if (!f.action(c, h))
                        return log$t.error(`[Engine] scene._isReadyForMeshStage == false, mesh name:${c.name}, mesh xtype: ${c == null ? void 0 : c.xtype}, mesh xgroup: ${c == null ? void 0 : c.xgroup}, mesh xskinInfo: ${c == null ? void 0 : c.xskinInfo}`),
                        !1
            }
            for (l = 0; l < this.scene.geometries.length; l++)
                if (this.scene.geometries[l].delayLoadState === 2)
                    return log$t.error("[Engine] geometry.delayLoadState === 2"),
                    !1
        }
        if (n) {
            if (this.scene.activeCameras && this.scene.activeCameras.length > 0) {
                for (const c of this.scene.activeCameras)
                    if (!c.isReady(!0))
                        return log$t.error("[Engine] camera not ready === false, ", c.name),
                        !1
            } else if (this.scene.activeCamera && !this.scene.activeCamera.isReady(!0))
                return log$t.error("[Engine] activeCamera ready === false, ", this.scene.activeCamera.name),
                !1
        }
        if (o) {
            for (const c of this.scene.particleSystems)
                if (!c.isReady())
                    return log$t.error("[Engine] particleSystem ready === false, ", c.name),
                    !1
        }
        return !0
    }
    changePanoShaderForLowModel(e) {
        return log$t.info(`[Engine] changePanoShaderForLowModel: ${e}`),
        this._materialManager.allowYUVUpdate(),
        new Promise((t,r)=>{
            this._materialManager._isInDynamicRange(e) == !1 && r(!1),
            this._currentPanoId = e,
            this._currentShader = this._materialManager.getDynamicShader(e),
            this.changeShaderForLowModel().then(()=>{
                t(!0)
            }
            )
        }
        )
    }
    changeVideoShaderForLowModel() {
        return log$t.info("[Engine] changeVideoShaderForLowModel"),
        this._currentShader = this._materialManager.getPureVideoShader(),
        this._materialManager.allowYUVUpdate(),
        this.changeShaderForLowModel()
    }
    changeDefaultShaderForLowModel() {
        return log$t.info("[Engine] changeDefaultShaderForLowModel"),
        this._currentShader = this._materialManager.getDefaultShader(),
        this._materialManager.stopYUVUpdate(),
        this.changeShaderForLowModel()
    }
    changeShaderForLowModel() {
        return new Promise((e,t)=>{
            this._lowpolyManager.getMeshes().forEach(r=>{
                r.setMaterial(this._currentShader)
            }
            ),
            this._lowpolyManager.getCgMesh().mesh.material = this._currentShader,
            e(!0)
        }
        )
    }
    setIBL(e) {
        this._lightManager.setIBL(e)
    }
    postprocessing() {
        const e = new DefaultRenderingPipeline("default",!0,this.scene);
        e.imageProcessingEnabled = !1,
        e.bloomEnabled = !0,
        e.bloomThreshold = 1,
        e.bloomWeight = 1,
        e.bloomKernel = 64,
        e.bloomScale = .1
    }
    getGround(e) {
        const t = this._lowpolyManager.getMeshes()
          , r = [];
        return t.forEach(n=>{
            n.mesh.name.indexOf("SM_Stage") >= 0 && r.push(n.mesh)
        }
        ),
        this.Scene.meshes.forEach(n=>{
            n.name.split("_")[0] === "ground" && r.push(n)
        }
        ),
        r
    }
}
new Logger$1("XVolume");
const log$s = new Logger$1("ScreenShot");
function CreateScreenshot(i, e, t, r, n="image/png", o=!1) {
    const {height: a, width: s} = _getScreenshotSize(i, e, t);
    if (log$s.info("[Engine]CreateScreenshot!"),
    !(a && s)) {
        log$s.error("[Engine]CreateScreenshot Invalid 'size' parameter !");
        return
    }
    Tools._ScreenshotCanvas || (Tools._ScreenshotCanvas = document.createElement("canvas")),
    Tools._ScreenshotCanvas.width = s,
    Tools._ScreenshotCanvas.height = a;
    const l = Tools._ScreenshotCanvas.getContext("2d")
      , u = i.getRenderWidth() / i.getRenderHeight();
    let c = s
      , h = c / u;
    h > a && (h = a,
    c = h * u);
    const f = Math.max(0, s - c) / 2
      , d = Math.max(0, a - h) / 2;
    e.getScene().onAfterRenderObservable.addOnce(function() {
        const g = i.getRenderingCanvas();
        l && g ? l.drawImage(g, f, d, c, h) : log$s.error("[Engine]CreateScreenshot Invalid renderContext and renderingCanvas!"),
        o ? (Tools.EncodeScreenshotCanvasData(void 0, n),
        r && r("")) : Tools.EncodeScreenshotCanvasData(r, n)
    })
}
function CreateScreenshotAsync(i, e, t, r="image/png") {
    return new Promise((n,o)=>{
        CreateScreenshot(i, e, t, a=>{
            typeof a != "undefined" ? n(a) : o(new Error("Data is undefined"))
        }
        , r)
    }
    )
}
function CreateScreenshotUsingRenderTarget(i, e, t, r, n="image/png", o=1, a=!1, s, l=!1, u=!1) {
    const {height: c, width: h} = _getScreenshotSize(i, e, t)
      , f = {
        width: h,
        height: c
    };
    if (!(c && h)) {
        log$s.error("Invalid 'size' parameter !");
        return
    }
    const d = e.getScene();
    let _ = null;
    const g = d.activeCameras;
    d.activeCameras = null,
    d.activeCamera !== e && (_ = d.activeCamera,
    d.activeCamera = e),
    d.render();
    const m = new RenderTargetTexture("screenShot",f,d,!1,!1,Constants.TEXTURETYPE_UNSIGNED_INT,!1,Texture.NEAREST_SAMPLINGMODE,void 0,u,void 0,void 0,void 0,o);
    m.renderList = null,
    m.samples = o,
    m.renderSprites = l,
    d.onAfterRenderTargetsRenderObservable.addOnce(function() {
        m.readPixels(void 0, void 0, void 0, !1).then(y=>{
            Tools.DumpData(h, c, y, r, n, s, !0),
            m.dispose()
        }
        )
    });
    const v = ()=>{
        d.incrementRenderId(),
        d.resetCachedMaterial(),
        m.render(!0),
        d.incrementRenderId(),
        d.resetCachedMaterial(),
        _ && (d.activeCamera = _),
        d.activeCameras = g,
        e.getProjectionMatrix(!0),
        d.render()
    }
    ;
    if (a) {
        const y = new FxaaPostProcess("antialiasing",1,d.activeCamera);
        m.addPostProcess(y),
        y.getEffect().isReady() ? v() : y.getEffect().onCompiled = ()=>{
            v()
        }
    } else
        v()
}
function CreateScreenshotUsingRenderTargetAsync(i, e, t, r="image/png", n=1, o=!1, a, s=!1) {
    return new Promise((l,u)=>{
        CreateScreenshotUsingRenderTarget(i, e, t, c=>{
            typeof c != "undefined" ? l(c) : u(new Error("Data is undefined"))
        }
        , r, n, o, a, s)
    }
    )
}
function _getScreenshotSize(i, e, t) {
    let r = 0
      , n = 0;
    if (typeof t == "object") {
        const o = t.precision ? Math.abs(t.precision) : 1;
        t.width && t.height ? (r = t.height * o,
        n = t.width * o) : t.width && !t.height ? (n = t.width * o,
        r = Math.round(n / i.getAspectRatio(e))) : t.height && !t.width ? (r = t.height * o,
        n = Math.round(r * i.getAspectRatio(e))) : (n = Math.round(i.getRenderWidth() * o),
        r = Math.round(n / i.getAspectRatio(e)))
    } else
        isNaN(t) || (r = t,
        n = t);
    return n && (n = Math.floor(n)),
    r && (r = Math.floor(r)),
    {
        height: r | 0,
        width: n | 0
    }
}
const initSideEffects = ()=>{
    Tools.CreateScreenshot = CreateScreenshot,
    Tools.CreateScreenshotAsync = CreateScreenshotAsync,
    Tools.CreateScreenshotUsingRenderTarget = CreateScreenshotUsingRenderTarget,
    Tools.CreateScreenshotUsingRenderTargetAsync = CreateScreenshotUsingRenderTargetAsync
}
;
initSideEffects();
ParticleSystem.prototype.isReady = function() {
    if (!this.emitter || this._imageProcessingConfiguration && !this._imageProcessingConfiguration.isReady())
        return !1;
    if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) {
        if (!this._getWrapper(this.blendMode).effect.isReady())
            return !1
    } else if (!this._getWrapper(ParticleSystem.BLENDMODE_MULTIPLY).effect.isReady() || !this._getWrapper(ParticleSystem.BLENDMODE_ADD).effect.isReady())
        return !1;
    return !0
}
;
const animationMap = new Map;
animationMap.set("Falling", new AnimationRange("Falling1",0,15));
animationMap.set("Click", new AnimationRange("Click",16,39));
animationMap.set("Disappear", new AnimationRange("Disappear",40,47));
class XRain extends XSubSequence {
    constructor(e, t, r) {
        super(e, t, r);
        this.onLoadedObserverable.addOnce(()=>{
            this._particleGroups.forEach(n=>{
                const o = n.systems[0];
                o.getClassName() == "ParticleSystem" && (o.startPositionFunction = function(a, s) {
                    const u = 2 * Math.random() * Math.PI
                      , c = Math.random() * 15 * Math.sin(u)
                      , h = this.minEmitBox.y
                      , f = Math.random() * 15 * Math.cos(u);
                    Vector3.TransformCoordinatesFromFloatsToRef(c, h, f, a, s)
                }
                )
            }
            )
        }
        )
    }
}
var AvatarGroup = (i=>(i.Npc = "npc",
i.User = "user",
i))(AvatarGroup || {})
  , ChangeComponentsMode = (i=>(i[i.Preview = 0] = "Preview",
i[i.Confirm = 1] = "Confirm",
i[i.Cancel = 2] = "Cancel",
i))(ChangeComponentsMode || {})
  , MotionType = (i=>(i.Walk = "walk",
i.Run = "run",
i.Fly = "fly",
i))(MotionType || {});
class XverseError extends Error {
    constructor(e, t) {
        super(t);
        E(this, "code");
        this.code = e
    }
    toJSON() {
        return {
            code: this.code,
            message: this.message
        }
    }
    toString() {
        if (Object(this) !== this)
            throw new TypeError;
        let t = this.name;
        t = t === void 0 ? "Error" : String(t);
        let r = this.message;
        r = r === void 0 ? "" : String(r);
        const n = this.code;
        return r = n === void 0 ? r : n + "," + r,
        t === "" ? r : r === "" ? t : t + ": " + r
    }
}
class ParamError extends XverseError {
    constructor(e) {
        super(1001, e || "\u53C2\u6570\u9519\u8BEF")
    }
}
class InternalError extends XverseError {
    constructor(e) {
        super(1002, e || "\u5185\u90E8\u9519\u8BEF")
    }
}
class TimeoutError extends XverseError {
    constructor(e) {
        super(1003, e || "\u8D85\u65F6")
    }
}
class AuthenticationError extends XverseError {
    constructor(e) {
        super(1004, e || "\u9274\u6743\u5931\u8D25")
    }
}
class TokenExpiredError extends XverseError {
    constructor(e) {
        super(1005, e || "Token \u5DF2\u8FC7\u671F")
    }
}
class UnsupportedError extends XverseError {
    constructor(e) {
        super(1006, e || "\u624B\u673A\u7CFB\u7EDF\u4E0D\u652F\u6301XVerse")
    }
}
class InitNetworkTimeoutError extends XverseError {
    constructor(e) {
        super(1007, e || "\u7F51\u7EDC\u521D\u59CB\u5316\u8D85\u65F6")
    }
}
class InitDecoderTimeoutError extends XverseError {
    constructor(e) {
        super(1008, e || "Decoder \u521D\u59CB\u5316\u8D85\u65F6")
    }
}
class InitConfigTimeoutError extends XverseError {
    constructor(e) {
        super(1009, e || "\u914D\u7F6E\u521D\u59CB\u5316\u8D85\u65F6")
    }
}
class InitEngineTimeoutError extends XverseError {
    constructor(e) {
        super(1010, e || "\u5F15\u64CE\u521D\u59CB\u5316\u8D85\u65F6")
    }
}
class InitEngineError extends XverseError {
    constructor(e) {
        super(1011, e || "\u5F15\u64CE\u521D\u59CB\u5316\u9519\u8BEF")
    }
}
class ActionBlockedError extends XverseError {
    constructor(e) {
        super(1012, e || "\u52A8\u4F5C\u88AB\u5C4F\u853D")
    }
}
class PreloadCanceledError extends XverseError {
    constructor(e) {
        super(1013, e || "\u9884\u52A0\u8F7D\u88AB\u53D6\u6D88")
    }
}
class FrequencyLimitError extends XverseError {
    constructor(e) {
        super(1014, e || "\u9891\u7387\u9650\u5236")
    }
}
class UsersUpperLimitError extends XverseError {
    constructor(e) {
        super(2e3, e || "\u76F4\u64AD\u95F4\u4EBA\u6570\u5DF2\u6EE1")
    }
}
class RoomsUpperLimitError extends XverseError {
    constructor(e) {
        super(2001, e || "\u623F\u95F4\u5230\u8FBE\u4E0A\u9650")
    }
}
class ServerParamError extends XverseError {
    constructor(e) {
        super(2002, e || "\u670D\u52A1\u5668\u53C2\u6570\u9519\u8BEF")
    }
}
class LackOfTokenError extends XverseError {
    constructor(e) {
        super(2003, e || "\u7F3A\u5C11 Token")
    }
}
class LoginFailedError extends XverseError {
    constructor(e) {
        super(2004, e || "\u8FDB\u5165\u623F\u95F4\u5931\u8D25")
    }
}
class VerifyServiceDownError extends XverseError {
    constructor(e) {
        super(2005, e || "\u9274\u6743\u670D\u52A1\u5F02\u5E38")
    }
}
class CreateSessionFailedError extends XverseError {
    constructor(e) {
        super(2006, e || "\u521B\u5EFA session \u5931\u8D25")
    }
}
class RtcConnectionError extends XverseError {
    constructor(e) {
        super(2008, e || "RTC\u5EFA\u8054\u5931\u8D25")
    }
}
class DoActionFailedError extends XverseError {
    constructor(e) {
        super(2009, e || "\u52A8\u4F5C\u6267\u884C\u5931\u8D25")
    }
}
class StateSyncFailedError extends XverseError {
    constructor(e) {
        super(2010, e || "\u72B6\u6001\u540C\u6B65\u5931\u8D25")
    }
}
class BroadcastFailedError extends XverseError {
    constructor(e) {
        super(2011, e || "\u5E7F\u64AD\u63A5\u53E3\u63A5\u53E3\u5F02\u5E38")
    }
}
class DataAbnormalError extends XverseError {
    constructor(e) {
        super(2012, e || "\u6570\u636E\u5F02\u5E38")
    }
}
class GetOnVehicleError extends XverseError {
    constructor(e) {
        super(2015, e || "\u4E0A\u8F7D\u5177\u5931\u8D25\u9700\u8981\u9884\u7EA6")
    }
}
class RepeatLoginError extends XverseError {
    constructor(e) {
        super(2017, e || "\u5F02\u5730\u767B\u5F55")
    }
}
class RoomDoseNotExistError extends XverseError {
    constructor(e) {
        super(2018, e || "\u6307\u5B9A\u623F\u95F4\u4E0D\u5B58\u5728")
    }
}
class TicketExpireError extends XverseError {
    constructor(e) {
        super(2019, e || "\u7968\u636E\u8FC7\u671F")
    }
}
class ServerRateLimitError extends XverseError {
    constructor(e) {
        super(2020, e || "\u670D\u52A1\u7AEF\u9891\u7387\u9650\u5236")
    }
}
class DoActionBlockedError extends XverseError {
    constructor(e) {
        super(2333, e || "\u52A8\u4F5C\u88AB\u5C4F\u853D")
    }
}
class ActionMaybeDelayError extends XverseError {
    constructor(e) {
        super(2334, e || "\u52A8\u4F5C\u53EF\u80FD\u5EF6\u8FDF\u6267\u884C")
    }
}
class ActionResponseTimeoutError extends XverseError {
    constructor(e) {
        super(2999, e || "action\u56DE\u5305\u8D85\u65F6")
    }
}
var Codes$1 = (i=>(i[i.Success = 0] = "Success",
i[i.Param = 1001] = "Param",
i[i.Internal = 1002] = "Internal",
i[i.Timeout = 1003] = "Timeout",
i[i.Authentication = 1004] = "Authentication",
i[i.TokenExpired = 1005] = "TokenExpired",
i[i.Unsupported = 1006] = "Unsupported",
i[i.InitNetworkTimeout = 1007] = "InitNetworkTimeout",
i[i.InitDecoderTimeout = 1008] = "InitDecoderTimeout",
i[i.InitConfigTimeout = 1009] = "InitConfigTimeout",
i[i.InitEngineTimeout = 1010] = "InitEngineTimeout",
i[i.InitEngine = 1011] = "InitEngine",
i[i.ActionBlocked = 1012] = "ActionBlocked",
i[i.PreloadCanceled = 1013] = "PreloadCanceled",
i[i.FrequencyLimit = 1014] = "FrequencyLimit",
i[i.UsersUpperLimit = 2e3] = "UsersUpperLimit",
i[i.RoomsUpperLimit = 2001] = "RoomsUpperLimit",
i[i.ServerParam = 2002] = "ServerParam",
i[i.LackOfToken = 2003] = "LackOfToken",
i[i.LoginFailed = 2004] = "LoginFailed",
i[i.VerifyServiceDown = 2005] = "VerifyServiceDown",
i[i.CreateSessionFailed = 2006] = "CreateSessionFailed",
i[i.RtcConnection = 2008] = "RtcConnection",
i[i.DoActionFailed = 2009] = "DoActionFailed",
i[i.StateSyncFailed = 2010] = "StateSyncFailed",
i[i.BroadcastFailed = 2011] = "BroadcastFailed",
i[i.DataAbnormal = 2012] = "DataAbnormal",
i[i.GetOnVehicle = 2015] = "GetOnVehicle",
i[i.RepeatLogin = 2017] = "RepeatLogin",
i[i.RoomDoseNotExist = 2018] = "RoomDoseNotExist",
i[i.TicketExpire = 2019] = "TicketExpire",
i[i.ServerRateLimit = 2020] = "ServerRateLimit",
i[i.DoActionBlocked = 2333] = "DoActionBlocked",
i[i.ActionMaybeDelay = 2334] = "ActionMaybeDelay",
i[i.ActionResponseTimeout = 2999] = "ActionResponseTimeout",
i))(Codes$1 || {});
const CodeErrorMap = {
    1001: ParamError,
    1002: InternalError,
    1003: TimeoutError,
    1004: AuthenticationError,
    1005: TokenExpiredError,
    1006: UnsupportedError,
    1007: InitNetworkTimeoutError,
    1008: InitDecoderTimeoutError,
    1009: InitConfigTimeoutError,
    1010: InitEngineTimeoutError,
    1011: InitEngineError,
    1012: ActionBlockedError,
    1013: PreloadCanceledError,
    1014: FrequencyLimitError,
    2e3: UsersUpperLimitError,
    2001: RoomsUpperLimitError,
    2002: ServerParamError,
    2003: LackOfTokenError,
    2004: LoginFailedError,
    2005: VerifyServiceDownError,
    2006: CreateSessionFailedError,
    2008: RtcConnectionError,
    2009: DoActionFailedError,
    2010: StateSyncFailedError,
    2011: BroadcastFailedError,
    2012: DataAbnormalError,
    2015: GetOnVehicleError,
    2017: RepeatLoginError,
    2018: RoomDoseNotExistError,
    2019: TicketExpireError,
    2020: ServerRateLimitError,
    2333: DoActionBlockedError,
    2334: ActionMaybeDelayError,
    2999: ActionResponseTimeoutError
};
class EventEmitter {
    constructor() {
        E(this, "topics", {});
        E(this, "on", (e,t,r)=>this.register(!1, e, t, r));
        E(this, "once", (e,t,r)=>this.register(!0, e, t, r));
        E(this, "register", (e,t,r,n)=>{
            this.topics[t] || (this.topics[t] = {
                once: e,
                listeners: [],
                excuted: !1
            });
            const o = {
                order: n || 0,
                listener: r,
                once: e
            };
            return this.topics[t].listeners.push(o),
            this.topics[t].listeners.sort((a,s)=>a.order - s.order),
            {
                unsub: ()=>{
                    this.off(t, r)
                }
            }
        }
        );
        E(this, "off", (e,t)=>{
            const r = this.topics[e];
            if (!r)
                return;
            const n = r.listeners.findIndex(o=>o.listener === t);
            this.topics[e].listeners.splice(n, 1),
            this.topics[e].listeners.length === 0 && delete this.topics[e]
        }
        );
        E(this, "removeAllListener", ()=>{
            this.topics = {}
        }
        );
        E(this, "emit", (e,t)=>{
            !this.topics[e] || !this.topics[e].listeners || this.topics[e].listeners.length < 1 || this.topics[e].excuted || (this.topics[e].listeners.forEach(r=>{
                try {
                    r.listener(t !== void 0 ? t : {})
                } catch (n) {
                    console.error(n)
                }
            }
            ),
            this.topics[e] && this.topics[e].once && (this.topics[e].excuted = !0))
        }
        )
    }
}
const safeDecodeURIComponent = i=>{
    let e = "";
    try {
        e = decodeURIComponent(i)
    } catch {
        e = i
    }
    return e
}
  , safelyJsonParse = i=>{
    let e = {};
    try {
        e = JSON.parse(i)
    } catch {}
    return e
}
  , getRandomItem = i=>i.length === 0 ? null : i[Math.floor(Math.random() * i.length)]
  , ENV = "production";
function getFormattedDate(i) {
    const e = i.getMonth() + 1
      , t = i.getDate()
      , r = i.getHours()
      , n = i.getMinutes()
      , o = i.getSeconds()
      , a = i.getMilliseconds()
      , s = (e < 10 ? "0" : "") + e
      , l = (t < 10 ? "0" : "") + t
      , u = (r < 10 ? "0" : "") + r
      , c = (n < 10 ? "0" : "") + n
      , h = (o < 10 ? "0" : "") + o;
    return i.getFullYear() + "-" + s + "-" + l + " " + u + ":" + c + ":" + h + "." + a
}
const SERVER_URLS = {
    DEV: "wss://sit-eks.xverse.cn/ws",
    PROD: "wss://eks.xverse.cn/ws"
}
  , REPORT_URL = {
    DEV: "https://xa.xverse.cn:6680/collect",
    PROD: "https://xa.xverse.cn/collect"
}
  , MAX_RECONNECT_COUNT = 3
  , DEFAULT_JOINROOM_TIMEOUT = 15e3
  , DEFAULT_MAIN_CAMERA_FOV = 50
  , DEFAULT_AVATAR_SCALE = 1
  , REPORT_NUM_PER_REQUEST = 20
  , DEFAULT_OPEN_TIMEOUT_MS = 6e3
  , WS_CLOSE_NORMAL = 1e3
  , WS_CLOSE_RECONNECT = 3008
  , PING_INTERVAL_MS = 1e3
  , TEXTURE_URL = "https://static.xverse.cn/qqktv/texture.png"
  , REPORT_MODULE_TYPE = "xverse-js"
  , authenticationErrorCodes = [3001, 3002, 3003, 3005]
  , RTT_MAX_VALUE = 200
  , HB_MAX_VALUE = 500
  , DURATION = 10
  , NET_INTERVAL = 1;
class Reporter extends EventEmitter {
    constructor() {
        super();
        E(this, "_header", {});
        E(this, "_body", {});
        E(this, "_queue", []);
        E(this, "_disabled", !1);
        E(this, "_interval", null);
        E(this, "_reportUrl");
        E(this, "isDocumentLoaded", ()=>document.readyState === "complete");
        this._header.logModuleId = REPORT_MODULE_TYPE,
        this._header.url = location.href,
        this._header.enviroment = ENV,
        this._header.networkType = window.navigator.connection ? window.navigator.connection.type : "unknown",
        this._interval = window.setInterval(()=>{
            this._flushReport()
        }
        , 10 * 1e3)
    }
    disable() {
        this._disabled = !0,
        this._interval && window.clearInterval(this._interval)
    }
    updateHeader(e) {
        Object.assign(this._header, e)
    }
    updateBody(e) {
        Object.assign(this._body, e)
    }
    updateReportUrl(e) {
        this._reportUrl = e
    }
    report(e, t, r) {
        if (this._disabled)
            return;
        r || (r = {});
        const {immediate: n, sampleRate: o} = r;
        if (o && o > Math.random())
            return;
        this.updateBody({
            logTime: getFormattedDate(new Date),
            logTimestamp: Date.now()
        });
        const a = s=>{
            const l = oe(le(oe({}, this._body), {
                type: e
            }), s);
            this._queue.push(l),
            e === "measurement" && this.emit("report", s)
        }
        ;
        Array.isArray(t) ? t.forEach(s=>a(s)) : a(t),
        (n || this._queue.length >= REPORT_NUM_PER_REQUEST) && this._flushReport()
    }
    _flushReport() {
        if (this._disabled || !this._queue.length || !this.isDocumentLoaded())
            return;
        const e = {
            header: this._header,
            body: this._queue.splice(0, REPORT_NUM_PER_REQUEST)
        };
        this._post(e)
    }
    _post(e) {
        const t = this._reportUrl || REPORT_URL.DEV;
        return new Promise((r,n)=>{
            const o = new XMLHttpRequest;
            o.open("POST", t),
            o.setRequestHeader("Content-Type", "application/json");
            try {
                o.send(JSON.stringify(e))
            } catch (a) {
                console.error(a)
            }
            o.addEventListener("readystatechange", ()=>{
                if (o.readyState == 4)
                    return o.status == 200 ? r(o) : n("Unable to send log")
            }
            )
        }
        )
    }
}
const reporter = new Reporter;
var LoggerLevels = (i=>(i[i.Debug = 1] = "Debug",
i[i.Info = 2] = "Info",
i[i.Warn = 3] = "Warn",
i[i.Error = 4] = "Error",
i[i.Off = 5] = "Off",
i))(LoggerLevels || {});
const Ce = class {
    constructor(e) {
        E(this, "module", "log");
        E(this, "level", 3);
        this.module = e
    }
    static setLevel(e) {
        this.level = e
    }
    setLevel(e) {
        this.level = e
    }
    atleast(e) {
        return e >= this.level && e >= Ce.level
    }
    print(e, t, ...r) {
        if (this.atleast(t)) {
            const n = e == "debug" ? "info" : e
              , o = this.prefix(e);
            console[n].call(null, o, ...r)
        }
        if (e !== "debug" && e !== "info") {
            const n = r.map(o=>{
                if (o instanceof Object)
                    try {
                        return JSON.stringify(o)
                    } catch {
                        return o
                    }
                else
                    return o
            }
            ).join(",");
            reporter.report("log", {
                message: n,
                level: e,
                module: this.module
            })
        }
    }
    debug(...e) {
        return this.print("debug", 1, ...e)
    }
    info(...e) {
        return this.print("info", 2, ...e)
    }
    infoAndReportLog(e, ...t) {
        const {reportOptions: r} = e;
        delete e.reportOptions,
        reporter.report("log", e, r),
        t.length || (t = [e.message]),
        this.debug(...t)
    }
    infoAndReportMeasurement(e, ...t) {
        var n;
        const {reportOptions: r} = e;
        if (e.startTime) {
            const o = Date.now();
            e.value === void 0 && (e.endTime = o),
            e.value === void 0 && (e.value = o - e.startTime)
        }
        if (e.error ? e.code = ((n = e.error) == null ? void 0 : n.code) || Codes$1.Internal : e.code = Codes$1.Success,
        reporter.report("measurement", e, r),
        t.length || (t = [e]),
        e.level === 4 || e.error) {
            this.error(...t);
            return
        }
        this.warn(...t)
    }
    warn(...e) {
        return this.print("warn", 3, ...e)
    }
    error(...e) {
        return this.print("error", 4, ...e)
    }
    prefix(e) {
        return `[${this.module}][${e}] ${getFormattedDate(new Date)}:`
    }
}
;
let Logger = Ce;
E(Logger, "level", 3);
function getDistance(i, e) {
    const {x: t, y: r, z: n} = i
      , {x: o, y: a, z: s} = e;
    return Math.sqrt(Math.abs(t - o) ** 2 + Math.abs(r - a) ** 2 + Math.abs(n - s) ** 2)
}
function uuid$1() {
    return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, i=>{
        const e = Math.random() * 16 | 0;
        return (i === "x" ? e : e & 3 | 8).toString(16)
    }
    )
}
function getErrorByCode(i) {
    if (i === Codes$1.Success)
        return InternalError;
    const e = CodeErrorMap[i];
    return e || console.warn("unkown code", i),
    e || InternalError
}
const log$r = new Logger("events");
class EventsManager extends EventEmitter {
    constructor() {
        super(...arguments);
        E(this, "events", new Map);
        E(this, "specialEvents", new Map)
    }
    remove(e, t, r, n) {
        if (this.specialEvents.has(e) && !n && t === Codes$1.Success)
            return;
        this.events.get(e) && (this.emit(e, {
            code: t,
            data: r
        }),
        this.events.delete(e),
        this.specialEvents.delete(e))
    }
    async track(e, t) {
        const r = e.traceId;
        this.emitTraceIdToDecoder(e);
        const {sampleRate: n, noReport: o=!1, special: a} = t || {};
        if (n && Math.random() > n)
            return Promise.resolve();
        const s = Actions[e.event] + "Action"
          , l = e.tag;
        this.events.set(r, !0),
        a && this.specialEvents.set(r, !0);
        const u = Date.now();
        let c = null;
        return new Promise((h,f)=>{
            if (o)
                return this.off(r),
                this.events.delete(r),
                h(void 0);
            this.on(r, ({code: _, data: g, msg: m})=>{
                if (_ === Codes$1.Success)
                    h(g),
                    this.off(r),
                    log$r.infoAndReportMeasurement({
                        metric: s,
                        tag: l,
                        extra: e.extra,
                        startTime: u,
                        traceId: r
                    });
                else {
                    if (_ === Codes$1.ActionMaybeDelay)
                        return;
                    if (_ === Codes$1.DoActionBlocked && e.event === Actions.Rotation) {
                        log$r.debug(s + " response code: " + _);
                        return
                    }
                    const v = getErrorByCode(_)
                      , y = new v(m);
                    this.off(r),
                    f(y),
                    this.emit("actionResponseError", {
                        error: y,
                        event: e,
                        tag: l
                    }),
                    log$r.infoAndReportMeasurement({
                        metric: s,
                        tag: l,
                        extra: e.extra,
                        error: y,
                        startTime: u,
                        traceId: r
                    })
                }
            }
            );
            const d = e.timeout || 2e3;
            c = window.setTimeout(()=>{
                if (c && clearTimeout(c),
                !this.events.get(r))
                    return;
                const _ = new ActionResponseTimeoutError(`${s} timeout in ${d}ms`);
                this.emit("actionResponseTimeout", {
                    error: _,
                    event: e,
                    tag: l
                }),
                f(_),
                this.events.delete(r),
                this.off(r),
                log$r.infoAndReportMeasurement({
                    metric: s,
                    tag: l,
                    extra: e.extra,
                    error: _,
                    startTime: u,
                    traceId: r
                })
            }
            , d)
        }
        )
    }
    emitTraceIdToDecoder(e) {
        if (e.event === Actions.Rotation || e.event === Actions.Clicking || e.event === Actions.GetOnVehicle || e.event === Actions.GetOffVehicle) {
            const t = {
                [Actions.Rotation]: "Rotation",
                [Actions.GetOnVehicle]: "GetOnVehicle",
                [Actions.GetOffVehicle]: "GetOffVehicle",
                [Actions.Clicking]: "MoveTo"
            };
            this.emit("traceId", {
                traceId: e.traceId,
                timestamp: Date.now(),
                event: t[e.event]
            })
        }
    }
}
const eventsManager = new EventsManager;
var Actions = (i=>(i[i.Clicking = 1] = "Clicking",
i[i.PlayCG = 6] = "PlayCG",
i[i.Back = 7] = "Back",
i[i.ChangeRoom = 8] = "ChangeRoom",
i[i.ChangeSkin = 13] = "ChangeSkin",
i[i.Joystick = 15] = "Joystick",
i[i.Transfer = 18] = "Transfer",
i[i.GetOnVehicle = 22] = "GetOnVehicle",
i[i.GetOffVehicle = 23] = "GetOffVehicle",
i[i.StopMoving = 34] = "StopMoving",
i[i.UnaryActionLine = 1e3] = "UnaryActionLine",
i[i.Init = 1001] = "Init",
i[i.Exit = 1002] = "Exit",
i[i.SetIFrameInfo = 1003] = "SetIFrameInfo",
i[i.GetNeighborPoints = 1004] = "GetNeighborPoints",
i[i.ReserveSeat = 1005] = "ReserveSeat",
i[i.GetReserveStatus = 1006] = "GetReserveStatus",
i[i.ChangeNickname = 1007] = "ChangeNickname",
i[i.ChangeBitRateInfo = 1008] = "ChangeBitRateInfo",
i[i.Echo = 1009] = "Echo",
i[i.SetPlayerState = 1010] = "SetPlayerState",
i[i.TurnTo = 1011] = "TurnTo",
i[i.TurnToFace = 1012] = "TurnToFace",
i[i.RotateTo = 1013] = "RotateTo",
i[i.Rotation = 1014] = "Rotation",
i[i.CameraTurnTo = 1015] = "CameraTurnTo",
i[i.ConfirmEvent = 1016] = "ConfirmEvent",
i[i.Broadcast = 1017] = "Broadcast",
i[i.NotifyActionLine = 2e4] = "NotifyActionLine",
i[i.AudienceChangeToVisitor = 1020] = "AudienceChangeToVisitor",
i[i.VisitorChangeToAudience = 1021] = "VisitorChangeToAudience",
i[i.RemoveVisitor = 1022] = "RemoveVisitor",
i[i.GetUserWithAvatar = 1023] = "GetUserWithAvatar",
i))(Actions || {})
  , RemoveVisitorType = (i=>(i[i.RVT_ChangeToObserver = 1] = "RVT_ChangeToObserver",
i[i.RVT_MoveOutOfTheRoom = 2] = "RVT_MoveOutOfTheRoom",
i))(RemoveVisitorType || {})
  , CoreBroadcastType = (i=>(i.PlayAnimation = "PlayAnimation",
i))(CoreBroadcastType || {})
  , MessageHandleType = (i=>(i[i.MHT_Undefined = 0] = "MHT_Undefined",
i[i.MHT_RoomMulticast = 1] = "MHT_RoomMulticast",
i[i.MHT_FollowListMulticast = 2] = "MHT_FollowListMulticast",
i[i.MHT_CustomTargetSync = 3] = "MHT_CustomTargetSync",
i))(MessageHandleType || {});
const log$q = new Logger("xverse-broadcast")
  , Ee = class {
    constructor(e, t) {
        this.room = e,
        Ee.handlers.push(t)
    }
    async handleBroadcast(e) {
        let t = null;
        try {
            t = JSON.parse(e.broadcastAction.data)
        } catch (r) {
            log$q.error(r);
            return
        }
    }
    broadcast(e) {
        const {data: t, msgType: r=MessageHandleType.MHT_FollowListMulticast, targetUserIds: n} = e;
        return this.room.actionsHandler.broadcast({
            data: t,
            msgType: r,
            targetUserIds: n
        })
    }
}
;
let Broadcast = Ee;
E(Broadcast, "handlers", []);
const log$p = new Logger("actions-handler")
  , QueueActions = [Actions.Transfer, Actions.ChangeSkin, Actions.GetOnVehicle, Actions.GetOffVehicle];
class ActionsHandler {
    constructor(e) {
        E(this, "room");
        E(this, "currentActiveAction");
        E(this, "avatarComponentsSync", e=>{
            const t = {
                action_type: Actions.SetPlayerState,
                set_player_state_action: {
                    player_state: {
                        avatar_components: JSON.stringify(e)
                    }
                }
            };
            this.sendData({
                data: t
            })
        }
        );
        this.room = e
    }
    async sendData(e) {
        await this.beforeSend(e);
        const t = uuid$1();
        if (this.room.networkController.sendRtcData(le(oe({}, e.data), {
            trace_id: t,
            user_id: this.room.options.userId
        })),
        e.track === !1)
            return Promise.resolve(null);
        const {sampleRate: r=1, timeout: n=2e3, tag: o, data: a, special: s} = e;
        return eventsManager.track({
            timeout: n,
            traceId: t,
            event: a.action_type,
            tag: o,
            extra: a
        }, {
            special: s,
            sampleRate: r,
            noReport: this.room.viewMode === "serverless" || this.room.options.viewMode === "serverless"
        }).finally(()=>{
            QueueActions.includes(e.data.action_type) && (this.currentActiveAction = void 0)
        }
        )
    }
    async beforeSend(e) {
        var o;
        const t = (o = this.room._userAvatar) == null ? void 0 : o.isMoving
          , r = e.data.action_type;
        if (QueueActions.includes(r)) {
            if (this.currentActiveAction)
                return log$p.error(`${Actions[this.currentActiveAction]} still pending, reject ${Actions[r]}`),
                Promise.reject(new FrequencyLimitError(`${Actions[r]} action request frequency limit`));
            this.currentActiveAction = r
        }
        if (t && QueueActions.includes(e.data.action_type))
            try {
                await this.stopMoving()
            } catch (a) {
                this.currentActiveAction = void 0,
                log$p.error("before action stopMoving failed", a)
            }
    }
    async moveTo(e) {
        const {point: t, extra: r="", motionType: n} = e
          , o = {
            action_type: Actions.Clicking,
            clicking_action: {
                clicking_point: t,
                clicking_type: ClickType.IgnoreView,
                extra: encodeURIComponent(r),
                attitude: n
            },
            clicking_state: this.room._currentClickingState
        };
        return this.sendData({
            data: o
        })
    }
    transfer(e) {
        const {renderType: t, player: r, camera: n, areaName: o, attitude: a, pathName: s, person: l, noMedia: u, timeout: c, tag: h, special: f} = e
          , d = {
            data: {
                action_type: Actions.Transfer,
                transfer_action: {
                    render_type: t,
                    player: r,
                    camera: n,
                    areaName: o,
                    attitude: a,
                    pathName: s,
                    person: {
                        type: l
                    },
                    noMedia: u,
                    tiles: [0, 1, 2, 4]
                }
            },
            special: f,
            timeout: c || 4e3,
            tag: h
        };
        return this.sendData(d).then(_=>(typeof l != "undefined" && this.room.updateCurrentNetworkOptions({
            person: l,
            rotationRenderType: t
        }),
        _))
    }
    changeRotationRenderType(e) {
        const {renderType: t, player: r, camera: n, areaName: o, attitude: a, pathName: s} = e;
        return this.transfer({
            renderType: t,
            player: r,
            camera: n,
            areaName: o,
            attitude: a,
            pathName: s,
            tag: "changeToRotationVideo"
        })
    }
    requestPanorama(e, t, r) {
        const {camera: n, player: o, areaName: a, attitude: s, pathName: l, tag: u} = e;
        return this.transfer({
            renderType: RenderType.ClientRotationPano,
            player: o,
            camera: n,
            person: Person.First,
            areaName: a,
            attitude: s,
            pathName: l,
            noMedia: t,
            timeout: r,
            tag: u || "requestPanorama",
            special: !t
        })
    }
    setMotionType(e) {
        return this.transfer({
            attitude: e,
            tag: "setMotionType"
        })
    }
    setNickName(e) {
        const t = {
            action_type: Actions.ChangeNickname,
            change_nickname_action: {
                nickname: e
            }
        };
        return this.sendData({
            data: t
        })
    }
    getReserveSeat({routeId: e, name: t}) {
        const r = {
            action_type: Actions.ReserveSeat,
            reserve_seat_action: {
                route_id: e,
                name: t
            }
        };
        return this.sendData({
            data: r
        })
    }
    getReserveStatus({routeId: e, name: t, need_detail: r}) {
        const n = {
            action_type: Actions.GetReserveStatus,
            get_reserve_status_action: {
                route_id: e,
                name: t,
                need_detail: r
            }
        };
        return this.sendData({
            data: n,
            timeout: 2e3
        }).then(o=>o.reserveDetail)
    }
    stopMoving() {
        const e = {
            action_type: Actions.StopMoving,
            stop_move_action: {}
        };
        return this.sendData({
            data: e
        })
    }
    getOnVehicle({routeId: e, name: t, camera: r}) {
        const n = {
            action_type: Actions.GetOnVehicle,
            get_on_vehicle_action: {
                route_id: e,
                name: t,
                camera: r
            }
        };
        return this.sendData({
            data: n
        })
    }
    getOffVehicle({renderType: e, player: t, camera: r}) {
        const n = {
            action_type: Actions.GetOffVehicle,
            get_off_vehicle_action: {
                render_type: e,
                player: t,
                camera: r
            }
        };
        return this.sendData({
            data: n
        })
    }
    confirmEvent(e) {
        const t = {
            action_type: Actions.ConfirmEvent,
            confirm_event_action: {
                id: e
            }
        };
        return this.sendData({
            data: t,
            track: !1
        })
    }
    echo(e) {
        const t = {
            action_type: Actions.Echo,
            echo_msg: {
                echoMsg: e
            }
        };
        return this.sendData({
            data: t,
            track: !1
        })
    }
    async changeSkin(e) {
        const t = e.special === void 0 ? e.renderType === RenderType.ClientRotationPano : e.special
          , {skinId: r, mode: n, landingType: o=LandingType.Stay, landingPoint: a, landingCamera: s, renderType: l, areaName: u, attitude: c, pathName: h, person: f, noMedia: d, timeout: _, roomTypeId: g=""} = e
          , m = this.room.skinList.filter(y=>y.id === r)[0];
        if (!m) {
            const y = `skin ${r} is invalid`;
            return log$p.error(y),
            Promise.reject(new ParamError(y))
        }
        const v = {
            action_type: Actions.ChangeSkin,
            change_skin_action: {
                skinID: r,
                mode: n === ChangeMode.Preview ? ChangeMode.Preview : ChangeMode.Confirm,
                skin_data_version: r + m.versionId,
                landing_type: o,
                landing_point: a,
                landing_camera: s,
                render_wrapper: {
                    render_type: l
                },
                areaName: u,
                attitude: c,
                noMedia: d,
                person: f,
                pathName: h,
                roomTypeId: g
            }
        };
        return this.sendData({
            data: v,
            timeout: _ || 6e3,
            special: t
        }).then(async y=>{
            if (l === RenderType.ClientRotationPano && y) {
                const b = await this.room.modelManager.findRoute(r, h)
                  , {camera: T} = getRandomItem(b.birthPointList) || {};
                await this.room.panorama.handleReceivePanorama(y, T)
            }
            return this.handleChangeSkin(e)
        }
        ).catch(y=>d ? this.handleChangeSkin(e) : Promise.reject(y))
    }
    handleChangeSkin(e) {
        const {skinId: t, mode: r, renderType: n, areaName: o, attitude: a, pathName: s} = e;
        return this.room.sceneManager.staticmeshComponent.getCgMesh().show(),
        this.room.sceneManager.cameraComponent.switchToCgCamera(),
        this.room.engineProxy._updateSkinAssets(t).then(()=>{
            this.room.sceneManager.staticmeshComponent.getCgMesh().hide(),
            this.room.sceneManager.cameraComponent.switchToMainCamera(),
            this.room.pathManager.currentArea = o,
            log$p.info("changeSkin _updateSkinAssets susccss"),
            this.room.updateCurrentNetworkOptions({
                pathName: s,
                attitude: a,
                areaName: o
            }),
            this.room.skinChangedHook(),
            this.room.emit("skinChanged", {
                skin: {
                    id: t
                },
                mode: r
            }),
            n === RenderType.ClientRotationPano && this.room.sceneManager.cameraComponent.allowMainCameraController()
        }
        )
    }
    rotate({pitch: e, yaw: t}) {
        var n;
        if (this.room.disableRotate || this.room.isPano || ((n = this.room._userAvatar) == null ? void 0 : n._isChangingComponentsMode))
            return;
        const r = {
            action_type: Actions.Rotation,
            rotation_action: {
                vertical_move: e,
                horizontal_move: -t
            }
        };
        this.sendData({
            data: r,
            sampleRate: .02
        })
    }
    turnTo(e) {
        const {point: t, timeout: r=2e3, offset: n=8} = e || {}
          , o = {
            action_type: Actions.TurnTo,
            turn_to_action: {
                turn_to_point: t,
                offset: n
            }
        };
        return this.sendData({
            data: o,
            timeout: r
        })
    }
    rotateTo(e) {
        const {point: t, offset: r=0, speed: n=3} = e || {}
          , o = {
            action_type: Actions.RotateTo,
            rotate_to_action: {
                rotate_to_point: t,
                offset: r,
                speed: n
            }
        };
        return this.sendData({
            data: o
        })
    }
    broadcast(e) {
        const {data: t, msgType: r=MessageHandleType.MHT_FollowListMulticast, targetUserIds: n} = e;
        if (r === MessageHandleType.MHT_CustomTargetSync && !Array.isArray(n))
            return Promise.reject(new ParamError(`param targetUserIds is required  when msgType is ${MessageHandleType[r]}`));
        const o = {
            action_type: Actions.Broadcast,
            broadcast_action: {
                data: JSON.stringify(t),
                user_id: this.room.options.userId,
                msgType: r
            }
        };
        return Array.isArray(n) && r === MessageHandleType.MHT_CustomTargetSync && (o.broadcast_action.target_user_ids = n),
        this.room.actionsHandler.sendData({
            data: o,
            tag: t.broadcastType
        })
    }
    getNeighborPoints(e) {
        const {point: t, containSelf: r=!1, searchRange: n=500} = e
          , o = {
            action_type: Actions.GetNeighborPoints,
            get_neighbor_points_action: {
                point: t,
                level: 1,
                containSelf: r,
                searchRange: n
            }
        };
        return this.sendData({
            data: o
        }).then(a=>a.nps)
    }
    playCG(e) {
        const t = {
            action_type: Actions.PlayCG,
            play_cg_action: {
                cg_name: e
            }
        };
        return this.sendData({
            data: t
        })
    }
    audienceToVisitor(e) {
        const {avatarId: t, avatarComponents: r, player: n, camera: o} = e
          , a = {
            action_type: Actions.AudienceChangeToVisitor,
            audienceChangeToVisitorAction: {
                avatarID: t,
                avatarComponents: r,
                player: n,
                camera: o
            }
        };
        return log$p.debug("send data: audience to visitor"),
        this.sendData({
            data: a
        })
    }
    visitorToAudience(e) {
        const {renderType: t, player: r, camera: n, areaName: o, attitude: a, pathName: s, person: l, noMedia: u} = e
          , c = {
            action_type: Actions.VisitorChangeToAudience,
            visitorChangeToAudienceAction: {
                transferAction: {
                    render_type: t,
                    player: r,
                    camera: n,
                    areaName: o,
                    attitude: a,
                    pathName: s,
                    person: {
                        type: l
                    },
                    noMedia: u,
                    tiles: [0, 1, 2, 4]
                }
            }
        };
        return log$p.debug("send data: visitor to audience"),
        this.sendData({
            data: c
        })
    }
    removeVisitor(e) {
        const {removeType: t, userIDList: r, extraInfo: n=""} = e
          , o = {
            action_type: Actions.RemoveVisitor,
            removeVisitorAction: {
                removeVisitorEvent: t,
                userIDList: r,
                extraInfo: encodeURIComponent(n)
            }
        };
        return log$p.debug("send data: remove visitor"),
        this.sendData({
            data: o
        })
    }
    getUserWithAvatar(e, t) {
        const r = {
            action_type: Actions.GetUserWithAvatar,
            getUserWithAvatarAction: {
                userType: e,
                roomID: t
            }
        };
        return log$p.debug("send data: get user with avatar"),
        this.sendData({
            data: r
        }).then(n=>n.userWithAvatarList)
    }
    joystick(e) {
        const {degree: t, level: r=1} = e
          , n = uuid$1();
        let o = -t + 90 + 360;
        o >= 360 && (o -= 360);
        const a = {
            action_type: Actions.Joystick,
            dir_action: {
                move_angle: o,
                speed_level: r
            },
            trace_id: n,
            user_id: this.room.options.userId,
            packet_id: n
        };
        return this.sendData({
            data: a,
            track: !1
        })
    }
}
const isWebAssemblySupported = ()=>{
    try {
        if (typeof WebAssembly == "object" && typeof WebAssembly.instantiate == "function") {
            const i = new WebAssembly.Module(Uint8Array.of(0, 97, 115, 109, 1, 0, 0, 0));
            if (i instanceof WebAssembly.Module)
                return new WebAssembly.Instance(i)instanceof WebAssembly.Instance
        }
    } catch {}
    return console.log("wasm is not supported"),
    !1
}
;
function isSupported() {
    return typeof RTCPeerConnection == "function" && isWebAssemblySupported()
}
var workerSourceCode = `onmessage = function (event) {
  const data = event.data
  if (!data) return

  if (data.type === 'start') {
    const startTime = Date.now()
    const request = new XMLHttpRequest()
    request.open('GET', data.url)
    try {
      request.send()
    } catch (error) {
      console.error(error)
    }
    request.addEventListener('readystatechange', () => {
      if (request.readyState == 4) {
        if (request.status == 200) {
          postMessage(Date.now() - startTime)
        }
      }
    })
  }
}
`;
const log$o = new Logger("detect");
let worker = null;
function checkNetworkQuality(i) {
    if (!i)
        return;
    const e = Date.now();
    if (pingOthers("https://www.baidu.com", function(t, r) {
        log$o.infoAndReportMeasurement({
            metric: "baiduRtt",
            group: "http",
            value: r,
            startTime: e
        })
    }),
    !worker) {
        const t = new Blob([workerSourceCode],{
            type: "application/javascript"
        });
        worker = new Worker(URL.createObjectURL(t)),
        worker.onmessage = function(r) {
            log$o.infoAndReportMeasurement({
                metric: "workerRtt",
                group: "http",
                startTime: e,
                value: r.data
            })
        }
    }
}
function pingOthers(i, e) {
    let t = !1;
    const r = new Image;
    r.onload = o,
    r.onerror = a;
    const n = Date.now();
    function o(l) {
        t = !0,
        s()
    }
    function a(l) {}
    function s() {
        const l = Date.now() - n;
        if (typeof e == "function")
            return t ? e(null, l) : (console.error("error loading resource"),
            e("error", l))
    }
    r.src = i + "/favicon.ico?" + +new Date
}
const log$n = new Logger("heartbeat");
class Heartbeat {
    constructor(e) {
        E(this, "_interval", null);
        E(this, "ping", ()=>{
            const e = Date.now().toString();
            this.handler.ping(e)
        }
        );
        this.handler = e
    }
    start() {
        this.stop(),
        log$n.debug(`Setting ping interval to ${PING_INTERVAL_MS}ms`),
        this._interval = window.setInterval(this.ping, PING_INTERVAL_MS)
    }
    stop() {
        log$n.debug("stop heartbeat"),
        this._interval && window.clearInterval(this._interval)
    }
    pong(e, t) {
        !e || typeof e == "string" && this.handler.pong(Date.now() - Number(e), t)
    }
}
class NetworkMonitor {
    constructor(e) {
        E(this, "_listener");
        this._listener = e
    }
    get isOnline() {
        const e = window.navigator;
        return typeof e.onLine == "boolean" ? e.onLine : !0
    }
    start() {
        window.addEventListener("online", this._listener),
        window.addEventListener("offline", this._listener)
    }
    stop() {
        window.removeEventListener("online", this._listener),
        window.removeEventListener("offline", this._listener)
    }
}
function VisibilityChangeHandler() {
    this.subscribers = [],
    this.bindFunc = void 0,
    this.id = 1,
    this.addListener()
}
VisibilityChangeHandler.prototype = {
    subscribe(i) {
        if (!i)
            return;
        const e = ++this.id
          , t = {
            id: e,
            handler: i
        };
        return this.subscribers.push(t),
        ()=>{
            this.subscribers = this.subscribers.filter(n=>n.id == e)
        }
    },
    destroy() {
        !this.bindFunc || (document.hidden !== void 0 ? document.removeEventListener("visibilitychange", this.bindFunc, !1) : document.webkitHidden && document.removeEventListener("webkitvisibilitychange", this.bindFunc, !1))
    },
    broadcast(i) {
        this.subscribers.forEach(e=>e.handler(i))
    },
    addListener() {
        document.hidden !== void 0 ? (this.bindFunc = ()=>this.broadcast(document.hidden),
        document.addEventListener("visibilitychange", this.bindFunc, !1)) : document.webkitHidden && (this.bindFunc = ()=>this.broadcast(document.webkitHidden),
        document.addEventListener("webkitvisibilitychange", this.bindFunc, !1))
    }
};
const WASM_Version = "h264"
  , DECODER_VERSION = "v0.9.3"
  , WASM_URLS = {
    h264: "https://static.xverse.cn/wasm/v15/lib_ff264dec_no_idb_with_wasm_tbundle.js?tbundle=tmeland_base",
    xv265: "https://static.xverse.cn/wasm/codec-release/h265-dec-sw-wasm/v-0-9-1/libxv265dec.js",
    h265: ""
}
  , STUCK_STAGE_GOOD = 45
  , STUCK_STAGE_WELL = 85
  , STUCK_STAGE_FAIR = 125
  , STUCK_STAGE_BAD = 165
  , DECODER_PASSIVE_JITTER = 0;
function add(i, e) {
    return e == -1 && (e = 0),
    i + e
}
function count_valid(i, e) {
    let t = 0;
    return e != -1 && (t = 1),
    i + t
}
function count_less(i, e) {
    function t(r, n) {
        let o = 0;
        return n != -1 && n < e && (o = 1),
        r + o
    }
    return i.reduce(t, 0)
}
function count_sd(i, e) {
    function t(r, n) {
        let o = 0;
        return n == -1 ? o = 0 : o = (n - e) * (n - e),
        r + o
    }
    return Math.sqrt(i.reduce(t, 0) / i.reduce(count_valid, 0)) || 0
}
function max(i, e) {
    return Math.max(i, e)
}
class CircularArray {
    constructor(e, t, r) {
        this.sum = 0,
        this.incomingSum = 0,
        this.count = 0,
        this.incomingCount = 0,
        this.max = 0,
        this.incomingMax = 0,
        this.goodLess = 0,
        this.wellLess = 0,
        this.fairLess = 0,
        this.badLess = 0,
        this.countLess = !1,
        this.lessThreshes = [],
        this.incomingData = [],
        this.circularData = Array(e).fill(-1),
        this.circularPtr = 0,
        this.circularLength = e,
        t && (this.countLess = !0,
        this.lessThreshes = r)
    }
    add(e) {
        this.circularData[this.circularPtr] != -1 ? (this.sum -= this.circularData[this.circularPtr],
        Math.abs(this.circularData[this.circularPtr] - this.max) < .01 && (this.circularData[this.circularPtr] = -1,
        this.max = this.getMax(!1))) : this.count += 1,
        this.sum += e,
        this.incomingSum += e,
        this.incomingCount += 1,
        this.max < e && (this.max = e),
        this.incomingMax < e && (this.incomingMax = e),
        this.circularData[this.circularPtr] = e,
        this.circularPtr = (this.circularPtr + 1) % this.circularLength,
        this.incomingData.push(e),
        this.incomingData.length > this.circularLength && (this.clearIncoming(),
        this.incomingCount = 0,
        this.incomingSum = 0)
    }
    computeAvg(e) {
        return e.reduce(add, 0) / e.reduce(count_valid, 0) || 0
    }
    computeMax(e) {
        return e.reduce(max, 0) || 0
    }
    computeThreshPercent(e) {
        if (this.countLess) {
            const t = count_less(e, this.lessThreshes[0]) || 0
              , r = count_less(e, this.lessThreshes[1]) || 0
              , n = count_less(e, this.lessThreshes[2]) || 0
              , o = count_less(e, this.lessThreshes[3]) || 0
              , a = e.reduce(count_valid, 0);
            return [t, r, n, o, a]
        } else
            return [0, 0, 0, 0, 0]
    }
    getAvg() {
        const e = this.sum / this.count || 0
          , t = this.computeAvg(this.circularData) || 0;
        return Math.abs(e - t) > .01 && console.error("avg value mismatch: ", e, t),
        this.computeAvg(this.circularData) || 0
    }
    getMax(e=!0) {
        const t = this.computeMax(this.circularData) || 0;
        return e && Math.abs(t - this.max) > .01 && console.error("max value mismatch: ", this.max, t),
        this.computeMax(this.circularData) || 0
    }
    getStandardDeviation() {
        return count_sd(this.circularData, this.getAvg())
    }
    getThreshPercent() {
        return this.computeThreshPercent(this.circularData)
    }
    getIncomingMax() {
        return this.computeMax(this.incomingData) || 0
    }
    getIncomingAvg() {
        return this.computeAvg(this.incomingData) || 0
    }
    getIncomingStandardDeviation() {
        return count_sd(this.incomingData, this.getIncomingAvg())
    }
    getIncomingThreshPercent() {
        return this.computeThreshPercent(this.incomingData)
    }
    clearFastComputeItem() {
        this.sum = 0,
        this.incomingSum = 0,
        this.count = 0,
        this.incomingCount = 0,
        this.max = 0,
        this.incomingMax = 0,
        this.goodLess = 0,
        this.wellLess = 0,
        this.fairLess = 0,
        this.badLess = 0
    }
    clearIncoming() {
        for (; this.incomingData.length > 0; )
            this.incomingData.pop()
    }
    clear() {
        this.circularData.fill(-1),
        this.circularPtr = 0,
        this.clearFastComputeItem(),
        this.clearIncoming()
    }
}
var decoder = `/* eslint-disable no-inner-declarations */
/* eslint-disable default-case */
/* eslint-disable no-restricted-globals */

// import { arrayBuffer } from "stream/consumers"
// import { addSyntheticLeadingComment, textChangeRangeIsUnchanged } from "typescript"

/* eslint-disable no-undef */
const CACHE_BUF_LENGTH = 16
const YUV_BUF_LENGTH = 16
if ('function' === typeof importScripts) {
  const startTime = Date.now()
  // self.importScripts('https://static.xverse.cn/wasm/zx_test_exclusive/v2/libxv265dec.js')
  // printConsole.log('Decoder update time is 2021/10/14 12:13 ')
  const YUVArray = []
  const mediaArray = []
  let IframesReceived = 0
  let IframesDecoded = 0
  let lastReceivePts = 0
  let lastProcessPts = 0
  let framesReturned = 0
  let send_out_buffer = 0
  let lastPoc = 0
  let cachedFirstFrame = undefined
  let cachedPanoramaFirstFrame = undefined

  const printConsole = {
    log: (msg) => self.postMessage({ t: MessageEvent.ConsoleLog, printMsg: msg }),
    error: (msg, code) => self.postMessage({ t: MessageEvent.ConsoleError, printMsg: msg, code: code }),
  }

  const MessageEvent = {
    DecodeMessage: 0,
    UpdateStats: 1,
    WASMReady: 2,
    CacheFrame: 3,
    RecordVideo: 4,
    OnlyEmitSignal: 5,
    WASMReadyCost: 6,
    PanoramaMessage: 7,
    RequestIFrame: 8,
    ConsoleLog: 9,
    ConsoleError: 10,
  }

  let lastReceiveContentPts = 0

  let saveMediaBytes = 0 // Just for test use
  const IFrameCacheBuffer = {}

  for (var i = 0; i < CACHE_BUF_LENGTH; ++i) {
    mediaArray.push({
      pts: -1,
      receive_ts: 0,
      decode_ts: 0,
      yuv_ts: 0,
      render_ts: 0,
      media: null,
      meta: null,
      isIDR: false,
    })
  }

  let downloadBlob = (data, fileName, mimeType) => {
    const blob = new Blob([data], {
      type: mimeType,
    })
    const url = URL.createObjectURL(blob)
    self.postMessage({ t: MessageEvent.RecordVideo, fileObj: blob, link: url })
    //downloadURL(url, fileName)
    setTimeout(function () {
      return URL.revokeObjectURL(url)
    }, 3000)
  }

  function Decoder() {
    this.expected_frameCnt = 1
    this.inited = false
    this.wasminited = false
    this.cacheMap = new Map()

    this.receivedMedia = 0
    this.receivedFrame = 0
    this.receivedYUV = 0
    this.receivedEmit = 0
    this.lastReceivedEmit = 0
    this.mediaBytesReceived = 0
    this.metaBytesReceived = 0
    this.prevSeq = 0
    this.packetsLost = 0
    this.packetsDrop = 0
    this.dtpf = 0
    this.dtmf = 0

    this.getFrameInterval = 10
    this.jumpI = false
    this.startEmit = false

    this.JankTimes = 0
    this.bigJankTimes = 0

    this.mediaCacheBuffer = new Uint8Array(1024 * 1024 * 10) // 10MB for video recording
    this.errorCacheBuffer = new Uint8Array(1024 * 1024 * 10) // 10MB for error stream recording
    this.mediaCacheSize = 0
    this.errorCacheSize = 0

    this.startRecord = false
    this.saveRecord = false

    this.requestingIFrame = false

    this.decoderId = 0 // 0 for 720p, 1 for 480p.

    this.DecodablePts = 0
    this.BlockedFrames = []

    this.decodeTimeCircular = Array(120).fill(-1)
    this.dtcPtr = 0

    this.readPtr = 1
    this.writePtr = 1
    this.cntBufInc = 0
    this.prevBufNum = 0
    this.MAX_TRY_TO_DEC_BUFNUM = 3
    this.skipFrameUntilI = true
    this.enable_logging = false

    this.framesReceivedBetweenTimerInterval = 0
    this.maxFramesReceivedBetweenTimerInterval = 0

    this.isFirstFrame = 1
    this.consumerPrevPts = -1
    this.consumerCurrPts = -1
    this.consumerWaitingIDR = false
    this.lastObj = null

    this.bufferIFrame = 0
    this.passiveJitterLength = 0
  }

  //refactor:
  Decoder.prototype.isBufEmpty = function () {
    return this.readPtr == this.writePtr
  }

  Decoder.prototype.isBufFull = function () {
    return (this.writePtr + 1) % CACHE_BUF_LENGTH == this.readPtr
  }

  Decoder.prototype.getNumOfPktToBeDec = function () {
    return (this.writePtr + CACHE_BUF_LENGTH - this.readPtr) % CACHE_BUF_LENGTH
  }

  Decoder.prototype.getNumOfEmptySlot = function () {
    return CACHE_BUF_LENGTH - this.getNumOfPktToBeDec() - 1
  }

  Decoder.prototype.aheadof = function (a, b) {
    return (a - b + 65536) % 65536 > 65536 / 2
  }

  Decoder.prototype.distance = function (a, b) {
    var res
    if (this.aheadof(a, b)) {
      res = this.seqDiff(b, a, 65536)
    } else {
      res = this.seqDiff(a, b, 65536)
    }
    return res
  }

  Decoder.prototype.isSeqJump = function (a, b) {
    return this.distance(a, b) >= CACHE_BUF_LENGTH - 1
  }

  Decoder.prototype.seqDiff = function (a, b, mod) {
    return (a + mod - b) % mod
  }

  //notice: n could be nagative
  Decoder.prototype.seqAdd = function (seq, n, mod) {
    return (seq + mod + n) % mod
  }
  //end refactor

  Decoder.prototype.resetDecoder = function () {
    this.isFirstFrame = 1
    this.expected_frameCnt = 1

    this.receivedMedia = 0
    this.receivedYUV = 0
    this.receivedEmit = 0
    this.lastReceivedEmit = 0
    this.mediaBytesReceived = 0
    this.metaBytesReceived = 0
    this.prevSeq = 0

    this.packetsLost = 0
    this.packetsDrop = 0
    this.dtpf = 0
    this.dtmf = 0

    this.JankTimes = 0
    this.bigJankTimes = 0

    this.getFrameInterval = 10
    this.jumpI = false
    IframesReceived = 0
    IframesDecoded = 0
    lastReceivePts = 0
    lastProcessPts = 0
    lastReceiveContentPts = 0

    this.requestingIFrame = false
    this.DecodablePts = 0
    this.BlockedFrames = []

    this.decodeTimeCircular.fill(-1)
    this.dtcPtr = 0

    for (var i = 0; i < CACHE_BUF_LENGTH; ++i) {
      mediaArray[i].media = null
      mediaArray[i].meta = null
      mediaArray[i] = {
        pts: -1,
        receive_ts: 0,
        decode_ts: 0,
        yuv_ts: 0,
        render_ts: 0,
        media: null,
        meta: null,
        isIDR: false,
      }
    }
    //refactor:
    this.readPtr = this.writePtr = 1
    this.cntBufInc = 0
    this.prevBufNum = 0
    this.MAX_TRY_TO_DEC_BUFNUM = 3
    this.skipFrameUntilI = true

    this.consumerPrevPts = -1
    this.consumerCurrPts = -1

    this.consumerWaitingIDR = false
    this.lastObj = null
    this.bufferIFrame = 0
    //end refactor
  }

  //refactor:

  Decoder.prototype.changeLogSwitch = function (status) {
    this.enable_logging = status
  }

  const MAX_LOG_NUM = 128
  logBufQueue = []

  Decoder.prototype.dumpLogBuf = function () {
    while (logBufQueue.length > 0) {
      console.log(logBufQueue.shift())
    }
  }

  Decoder.prototype.dumpJitterBufInfo = function (label, pts = -1) {
    // if (!this.enable_logging) {
    //   return
    // }

    logInfo =
      'WritePtr: ' +
      this.writePtr +
      ', ReadPtr: ' +
      this.readPtr +
      '\\n' +
      ', Producer Prev/Curr: ' +
      this.prevSeq +
      '/' +
      pts +
      '\\n' +
      ', Consumer Prev/Curr: ' +
      this.consumerPrevPts +
      '/' +
      this.consumerCurrPts +
      '\\n' +
      'awaitingBuf: ' +
      this.getNumOfPktToBeDec() +
      ', emptySlotNum: ' +
      this.getNumOfEmptySlot() +
      ', skipFrameUntilI: ' +
      this.skipFrameUntilI +
      '\\n' +
      ' framesReceivedBetweenTimerInterval: ' +
      this.framesReceivedBetweenTimerInterval +
      ', maxFramesReceivedBetweenTimerInterval: ' +
      this.maxFramesReceivedBetweenTimerInterval +
      '\\n' +
      ' label: ' +
      label +
      '\\n'

    if (pts != -1) {
      logInfo += ' this.notEnoughSlots(' + pts + '): ' + this.notEnoughSlots(pts) + '\\n'
    }

    if (this.enable_logging) {
      console.log(logInfo)
    } else {
      logBufQueue.push(logInfo)
      if (logBufQueue.length > MAX_LOG_NUM) {
        logBufQueue.shift()
      }
    }
  }

  Decoder.prototype.resetBufItem = function (index) {
    mediaArray[index].media = null
    mediaArray[index].meta = null
    if (mediaArray[index].isIDR == true) {
      this.bufferIFrame -= 1
    }
    mediaArray[index] = {
      pts: -1,
      receive_ts: 0,
      decode_ts: 0,
      yuv_ts: 0,
      render_ts: 0,
      media: null,
      meta: null,
      isIDR: false,
    }
    this.readPtr = this.seqAdd(this.readPtr, 1, CACHE_BUF_LENGTH)
  }

  Decoder.prototype.checkPktOrderInConsumer = function (index) {
    if (this.consumerPrevPts == -1) {
      if (!this.isSlotEmpty(index)) {
        this.consumerPrevPts = mediaArray[index].pts
      }
      return true
    }
    if (this.isSlotEmpty(index)) {
      //lost
      // debugger
      // console.log("[xmedia] return on SLOT EMPTY, prev: %s", prev)
      this.consumerWaitingIDR = true
      this.consumerPrevPts = this.seqAdd(this.consumerPrevPts, 1, 65536)
      return true
    }

    if (!this.slotHasMedia(index)) {
      // pure meta
      // debugger
      // console.log("[xmedia] return on meta, prev: %s, cur: %s", this., mediaArray[index].pts)
      this.consumerPrevPts = mediaArray[index].pts
      return true
    }

    this.consumerCurrPts = mediaArray[index].pts

    if (this.consumerWaitingIDR || this.seqDiff(this.consumerCurrPts, this.consumerPrevPts, 65536) != 1) {
      // if (!mediaArray[index].isIDR && mediaArray[index].media.byteLength!=0) {
      if (this.isPFrame(mediaArray[index].isIDR, mediaArray[index].media.byteLength)) {
        console.error('[INFO][XMEDIA] optimize to further reduce clutter chance. copy console log to developer')
        this.dumpLogBuf()
        this.dumpJitterBufInfo('go away.')
        // debugger
        this.consumerPrevPts = -1
        // this.resetDecoder()
        return false
      }
    }

    // console.log("[xmedia] return finally, prev: %s, cur: %s", prev, cur)
    this.consumerPrevPts = this.consumerCurrPts

    this.consumerWaitingIDR = false
    return true
  }

  Decoder.prototype.slotHasMedia = function (index) {
    return mediaArray[index].media != null && mediaArray[index].media.byteLength != 0
  }

  Decoder.prototype.slotHasContent = function (index) {
    return mediaArray[index].media != null && mediaArray[index].meta != null && mediaArray[index].pts != -1
  }

  Decoder.prototype.procBufItem = function (index) {
    this.dumpJitterBufInfo('Entering Decoder.prototype.procBufItem')
    // console.log('[][Core][WASM], pts: %s, isIDR: %s, length: %s', mediaArray[index].pts, mediaArray[index].isIDR, mediaArray[index].media.length)
    // var loginfo = 'pts: %s, isIDR: %s, length: %s', mediaArray[index].pts, mediaArray[index].isIDR, mediaArray[index].media.length

    needToSkip = this.skipFrameUntilI && !mediaArray[index].isIDR
    var loginfo =
      'pts: ' +
      mediaArray[index].pts +
      ', isidr: ' +
      mediaArray[index].isIDR +
      ', slotHasMedia: ' +
      this.slotHasMedia(index) +
      ', slotHasMeta: ' +
      (mediaArray[index].meta != null) +
      ', needToSkip: ' +
      needToSkip

    if (this.slotHasContent(index) && !needToSkip) {
      // console.log("[xmedia] %s ------------ 001", mediaArray[index].pts)
      let objData = {
        media: mediaArray[index].media,
        frameCnt: mediaArray[index].pts,
        meta: mediaArray[index].meta,
        metadata: mediaArray[index].metadata,
        isIDR: mediaArray[index].isIDR,
      }

      // -------------------
      if (this.checkPktOrderInConsumer(index)) {
        // console.log("[xmedia] %s ------------ 002", mediaArray[index].pts)
        this.decodeFrame(objData)
      }

      if (mediaArray[index].isIDR) {
        // console.log("[xmedia] %s ------------ 003", mediaArray[index].pts)
        // console.log("mediaArray[index].isIDR: this.skipFrameUntilI = false")
        this.skipFrameUntilI = false
      }
    } else {
      // console.log("[xmedia] %s ------------ 004", mediaArray[index].pts)
      if (this.slotHasMedia(index)) {
        // console.log("[xmedia] %s ------------ 005", mediaArray[index].pts)
        //need to skip, waiting I Frame
        //dropCache++
        this.dropPkt += 1
        // MARKER META1META2
        // self.postMessage({ t: MessageEvent.OnlyEmitSignal, meta_only: true, meta: mediaArray[index].meta, metadata: mediaArray[index].metadata })
      } else {
        // console.log("[xmedia] %s ------------ 006", mediaArray[index].pts)
        // no media
        if (mediaArray[index].meta != null) {
          this.checkPktOrderInConsumer(index)
          // console.log("[xmedia] %s ------------ 007", mediaArray[index].pts)
          // Still frame
          // console.log('[send signal]', mediaArray[index].pts)
          self.postMessage({
            t: MessageEvent.OnlyEmitSignal,
            meta_only: true,
            meta: mediaArray[index].meta,
            metadata: mediaArray[index].metadata,
          })
        } else {
          // console.log("[xmedia] %s ------------ 008", mediaArray[index].pts)
          // Lost_rcv++
          // console.log("lost_rcv++: this.skipFrameUntilI = true")
          // console.info('[xmedia] FFFFF This code should not be executed!!!!')
          console.info('[xmedia] null pkt sneaked into profBufItem without harm')
          this.skipFrameUntilI = true
        }
      }
    }
    this.dumpJitterBufInfo('Leaving Decoder.prototype.procBufItem, ' + loginfo)
    this.lastObj = mediaArray[index]
    this.resetBufItem(index)
  }

  Decoder.prototype.flushBuffer = function (untilIDR) {
    this.dumpJitterBufInfo('Entering Decoder.prototype.flushBuffer')
    this.skipFrameUntilI = true
    var breakWhenIDR = false
    while (this.getNumOfPktToBeDec() > 0) {
      index = this.readPtr
      if (this.slotHasMedia(index)) {
        // dropMedia until IDR // \u6765\u4E0D\u53CA\u89E3\u7801\u4E22\u5E27
        this.packetsDrop += 1
        if (untilIDR) {
          if (mediaArray[index].isIDR == true) {
            breakWhenIDR = true
            break
          }
        }
      } else if (mediaArray[index].meta != null) {
        self.postMessage({
          t: MessageEvent.OnlyEmitSignal,
          meta_only: true,
          meta: mediaArray[index].meta,
          metadata: mediaArray[index].metadata,
        })
      }
      this.resetBufItem(index)
    }
    if (!breakWhenIDR) {
      this.isFirstFrame = true
    }
    this.dumpJitterBufInfo('Leaving Decoder.prototype.flushBuffer')
    return this.isFirstFrame
  }
  // var cnt = 0
  Decoder.prototype.getFrameToDecode = function () {
    this.dumpJitterBufInfo('Entering Decoder.prototype.getFrameToDecode')

    if (this.getNumOfPktToBeDec() == 0) {
      return false
    }

    //bufNum awaiting increase counter
    // while (this.getNumOfPktToBeDec() > CACHE_BUF_LENGTH / 2) {
    //   needToCheck = true
    //   if (this.cntBufInc > this.MAX_TRY_TO_DEC_BUFNUM) {
    //     console.log('ringbuffer is deteriorating, flush until IDR')
    //     var untilIDR = true
    //     this.flushBuffer(untilIDR)
    //     this.cntBufInc = 0
    //     break
    //   }

    //   this.procBufItem(this.readPtr)
    // }

    // if (this.getNumOfPktToBeDec() == 0) {
    //   return false
    // }
    let IFrmInBuffer = 0
    let frmInBuffer = 0
    for (var i = 0; i < CACHE_BUF_LENGTH; ++i) {
      if (mediaArray[i].isIDR) {
        IFrmInBuffer += 1
      }
      if (this.slotHasMedia(i)) {
        frmInBuffer += 1
      }
    }
    if (!this.slotHasContent(this.readPtr) && IFrmInBuffer == 0) {
      if (frmInBuffer > 0) {
        // There is P frame in buffer but cannot be decoded.
        // Due to ordered data channel, this is packet loss.
        // So request for I frame here.
        printConsole.log('detect packet lost. Request for I frame.')
        self.postMessage({ t: MessageEvent.RequestIFrame })
      }
      return false
    }
    this.procBufItem(this.readPtr)

    // if (this.getNumOfPktToBeDec() > this.prevBufNum) {
    //   this.cntBufInc++
    // } else {
    //   if (this.cntBufInc > 2) {
    //     // aimd
    //     this.cntBufInc / 2
    //   }
    // }

    // this.prevBufNum = this.getNumOfPktToBeDec()

    this.dumpJitterBufInfo('Leaving Decoder.prototype.getFrameToDecode')
    return true
  }
  //refactor end:

  var cacheBuffer
  var resultBuffer

  Decoder.prototype.startDecoding = function () {
    function iterative_getFrameToDecode() {
      self.decoder.framesReceivedBetweenTimerInterval = 0
      self.decoder.dumpJitterBufInfo('Entering Decoder.prototype.iterative_getFrameToDecode')
      var start_ts = Date.now()
      let hasDecodeFrame = self.decoder.getFrameToDecode()
      var end_ts = Date.now()

      // refactor
      let expect_interval =
        1000 / (30 + Math.max(self.decoder.getNumOfPktToBeDec() - self.decoder.passiveJitterLength, 0))
      //let expect_interval = 1000 / (Decoder.prototype.getNumOfPktToBeDec() + 30)
      if (hasDecodeFrame) {
        let usedTime = end_ts - start_ts
        self.decoder.getFrameInterval = expect_interval - Math.max(usedTime, self.decoder.dtpf)
        if (self.decoder.getFrameInterval < 1) {
          self.decoder.getFrameInterval = 0
        }
      } else {
        self.decoder.getFrameInterval = 5
      }

      // let usedTime = end_ts - start_ts
      // FPS = 30
      // if (usedTime * FPS < 1000) {
      //   self.decoder.getFrameInterval = 1000 / (FPS + Decoder.prototype.getNumOfPktToBeDec())
      // } else {
      //   self.decoder.getFrameInterval = 1 //ms
      // }
      // if (Decoder.prototype.getNumOfPktToBeDec() == 0) {
      //   //Hinse: have to get buf to send asap.
      //   self.decoder.getFrameInterval = 5 //ms
      // }
      setTimeout(iterative_getFrameToDecode, self.decoder.getFrameInterval)
      self.decoder.dumpJitterBufInfo('Leaving Decoder.prototype.iterative_getFrameToDecode')
      // refactor end
    }
    function postStats() {
      function add(accumulator, a) {
        if (a == -1) {
          a = 0
        }
        return accumulator + a
      }
      function count_valid(accumulator, a) {
        let non_zero = 0
        if (a != -1) {
          non_zero = 1
        }
        return accumulator + non_zero
      }
      function max(maxer, a) {
        return Math.max(maxer, a)
      }
      const dtpf =
        self.decoder.decodeTimeCircular.reduce(add, 0) / self.decoder.decodeTimeCircular.reduce(count_valid, 0) || 0
      const dtmf = self.decoder.decodeTimeCircular.reduce(max, 0)
      let objData = {
        t: MessageEvent.UpdateStats,
        mediaBytesReceived: self.decoder.mediaBytesReceived,
        metaBytesReceived: self.decoder.metaBytesReceived,
        packetsLost: self.decoder.packetsLost, // \u7F51\u7EDC\u4E22\u5E27
        packetsDrop: self.decoder.packetsDrop, // \u6765\u4E0D\u53CA\u89E3\u7801\u4E22\u5E27
        framesReceived: self.decoder.receivedMedia,
        framesDecoded: self.decoder.receivedYUV,
        framesRendered: self.decoder.receivedEmit,
        framesReturned: framesReturned,
        // framesAwait: leastReceivePts - lastProcessPts,
        framesAwait: self.decoder.getNumOfPktToBeDec(), // \u7B49\u5F85\u89E3\u7801\u7684\u5E27
        decodeTimePerFrame: dtpf,
        decodeTimeMaxFrame: dtmf,
        sendOutBuffer: send_out_buffer,
        JankTimes: self.decoder.JankTimes,
        bigJankTimes: self.decoder.bigJankTimes,
        receivedIframe: self.decoder.IframesReceived,
        decodedIframe: self.decoder.IframesDecoded,
      }
      self.postMessage(objData)
      self.decoder.dtmf = 0
    }
    setTimeout(iterative_getFrameToDecode, this.getFrameInterval)
    setInterval(postStats, 1000)
  }

  Decoder.prototype.initAll = function (config) {
    if (typeof wasmSource != 'undefined') {
      if (wasmSource == 0) {
        // Load from indexedDB
        // console.log('Load WASM from indexedDB')
        printConsole.log('Load WASM from indexedDB')
        wasmSource = undefined
      } else if (wasmSource == 1) {
        // Load by fetch
        // console.log('Load WASM by fetch')
        printConsole.log('Load WASM by fetch')
        wasmSource = undefined
      } else {
        printConsole.log('WASM not ready now, wait for 200 ms.')
      }
    } else {
      printConsole.log('wasm variable is not defined. Probably libffmpeg.js file is not loaded properly.')
    }
    if (typeof wasmTable === 'undefined') {
      setTimeout(self.decoder.initAll, 200, config)
      return 0
    }

    cacheBuffer = Module._malloc(1024 * 1024)

    resultBuffer = Module._malloc(64)

    self.postMessage({
      t: MessageEvent.WASMReadyCost,
      type: 'report',
      data: {
        metric: 'wasmDownloadCost',
        value: Date.now() - startTime,
        group: 'costs',
      },
    })

    // WASM already initialized. Now  we open decoder.
    const LOG_LEVEL_WASM = 2
    const DECODER_H264 = 0
    const decoder_type = DECODER_H264
    for (var j = 0; j < YUV_BUF_LENGTH; ++j) {
      YUVArray.push({ status: 0, buffer: new Uint8Array((config.width * config.height * 3) / 2) })
    }
    printConsole.log('Going to open decoder ' + String(Date.now()))
    var ret0 = Module._openDecoder(0, decoder_type, LOG_LEVEL_WASM)
    if (ret0 == 0) {
      self.decoder.startDecoding()
      self.postMessage({ t: MessageEvent.WASMReady, wasm_ready: true, updateStats: false })
    } else {
      printConsole.error('openDecoder failed with error ' + String(ret0), '5001')
      return 1
    }

    return 0
  }

  Decoder.prototype.cacheFrame = function (data) {
    if (data.position != undefined) {
      var media = data.data.subarray(data.metaLen, data.metaLen + data.mediaLen)
      if (IFrameCacheBuffer[JSON.stringify(data.position)] == undefined) {
        for (var key in IFrameCacheBuffer) delete IFrameCacheBuffer[key] // Clear Frame Cache
        IFrameCacheBuffer[JSON.stringify(data.position)] = {}
      }
      IFrameCacheBuffer[JSON.stringify(data.position)][data.cachedKey] = media
      self.postMessage({
        t: MessageEvent.CacheFrame,
        cacheFrame: true,
        cachedKey: data.cachedKey,
        metadata: data.metadata,
      })
    }
  }

  Decoder.prototype.updateMediaMetaStats = function (data) {
    this.metaBytesReceived += data.metaLen
    this.mediaBytesReceived += data.mediaLen
    if (data.mediaLen != 0) {
      this.receivedMedia++
    }
  }

  Decoder.prototype.isIFrame = function (isIDR, mediaLen) {
    // return data.isIDR && media.byteLength !=0
    return isIDR && mediaLen != 0
  }

  Decoder.prototype.isPFrame = function (isIDR, mediaLen) {
    // return !data.isIDR && media.byteLength !=0
    return !isIDR && mediaLen != 0
  }

  Decoder.prototype.isPureMeta = function (metaLen, mediaLen) {
    // return media.byteLength == 0 && meta.byteLength !=0
    return mediaLen == 0 && metaLen != 0
  }

  Decoder.prototype.isInvalidPkt = function (isIDR, mediaLen, metaLen) {
    return !this.isIFrame(isIDR, mediaLen) && !this.isPFrame(isIDR, mediaLen) && !this.isPureMeta(metaLen, mediaLen)
  }

  Decoder.prototype.isSlotEmpty = function (index) {
    return !this.slotHasMedia(index) && mediaArray[index].meta == null
  }

  Decoder.prototype.handleNewPktOnFlush = function (isIDR, mediaLen) {
    var dropPkt = false

    // console.log("[xmedia] 000-1 isFirstFrame %s", this.isFirstFrame)
    if (this.isFirstFrame) {
      // let IDR/meta pass
      // console.log("[xmedia] 000-2 isIDR: %s, mediaLen: %s", isIDR, mediaLen)
      // console.log("[xmedia] 000-3 this.isPFrame(isIDR, mediaLen): %s", this.isPFrame(isIDR, mediaLen))
      if (this.isPFrame(isIDR, mediaLen)) {
        // console.log("[xmedia] 001: isPFrame TRUE")
        this.packetsDrop += 1
        // MARKER META1META2
        dropPkt = true
      }
      if (this.isIFrame(isIDR, mediaLen)) {
        // console.log("[xmedia] 002: isIFrame TRUE")
        this.isFirstFrame = false
      }
    }
    // console.log("[xmedia] 003: dropPkt: %s", dropPkt)
    return dropPkt
  }

  Decoder.prototype.notEnoughSlots = function (pts) {
    return this.isBufFull() || this.seqDiff(pts, this.prevSeq, CACHE_BUF_LENGTH) > this.getNumOfEmptySlot()
  }

  Decoder.prototype.receiveFrame = function (data) {
    var key = data.cachedKey
    var pts = data.frameCnt
    var meta = data.data.subarray(0, data.metaLen)
    var media

    if (data.cached) {
      media = IFrameCacheBuffer[JSON.stringify(data.position)][key]
    } else if (data.cacheRequest) {
      media = data.data.subarray(data.metaLen, data.metaLen + data.mediaLen)
      self.decoder.cacheFrame(data)
    } else {
      media = data.data.subarray(data.metaLen, data.metaLen + data.mediaLen)
    }

    this.updateMediaMetaStats(data)

    if (this.isFirstFrame) {
      // console.log('[xmedia] isFirstFrame = true. pts:%s', pts)
      if (this.isPFrame(data.isIDR, media.byteLength)) {
        // MARKER META1META2
        this.packetsDrop += 1
        return
      }
      this.prevSeq = this.seqDiff(pts, 1, 65536)
      this.readPtr = this.writePtr = pts % CACHE_BUF_LENGTH
      if (data.isIDR) {
        this.isFirstFrame = false
      }
    }
    if (pts !== this.seqAdd(this.prevSeq, 1, 65536) && pts !== this.prevSeq) {
      this.packetsLost += 1
    }

    const index = pts % CACHE_BUF_LENGTH
    if (this.startRecord) {
      this.mediaCacheBuffer.set(media, this.mediaCacheSize)
      this.mediaCacheSize += media.byteLength
    }
    if (this.saveRecord) {
      downloadBlob(this.mediaCacheBuffer.subarray(0, this.mediaCacheSize), 'test.264', 'application/octet-stream')
      this.mediaCacheSize = 0
      this.saveRecord = false
      this.startRecord = false
    }
    //refactor:
    // Step 1, big jump detected. we cannot handle it, flush all.
    var untilIDR, pktDrop
    if (this.isSeqJump(this.prevSeq, pts)) {
      // console.log('[resetdecoder] Fatal: decoder seq jump from ' + this.prevSeq + ' to ' + pts)
      untilIDR = false
      this.flushBuffer(untilIDR)
      pktDrop = this.handleNewPktOnFlush(data.isIDR, media.byteLength)
      if (pktDrop) return
    }
    this.dumpJitterBufInfo('Entering Decoder.prototype.receiveFrame', pts)
    // console.log("--->> this.notEnoughSlots(pts): %s", this.notEnoughSlots(pts))

    // Step 2,
    if (this.aheadof(pts, this.prevSeq)) {
      // pts before prevSeq
      // pkts in wrong order
      if (this.packetsLost > 0) {
        this.packetsLost -= 1
        // this.packetdisorder +=1
      }
      // console.log("[xmedia] disorder frame received. preSeq: %s, pts: %s", this.prevSeq, pts)
      if (this.seqDiff(this.prevSeq, pts, 65536) < this.getNumOfPktToBeDec()) {
        // slot for pts is not handled yet. just put it back:
        // console.log('put disorder frame to enc_queue, pkt:%s, prevPts: %s, numOfPktToBeDec: %s', pts, this.prevSeq, this.getNumOfPktToBeDec())
      } else {
        //dropDisorder++
        console.error(
          'drop disorder pkt:%s, prevPts: %s, numOfPktToBeDec: %s',
          pts,
          this.prevSeq,
          this.getNumOfPktToBeDec(),
        )
        this.packetsDrop += 1
        // ---------------------
        // Note:
        //
        // Three principles for meta data:
        //           step 1                        step 2
        // 1. backend -----> frontend (decoder.js) -----> frontend (worker.js), meta pkts must be kept in order in the whole pipeline
        // 2. if media presents and needs to be dropped, the meta companion needs to be dropped together.
        // 3. if media is absent (media.bytelength == 0), send meta anyway
        // ---------------------
        // According to rule 1, drop meta at this point is reasonable.
        return
      }
    } else {
      // pts after prevSeq
      // make sure the ringbuffer has empty slot for new pkt
      if (this.notEnoughSlots(pts)) {
        this.dumpJitterBufInfo('Fatal: decoder buf is full', pts)
        //dropIncoming
        untilIDR = true
        this.flushBuffer(untilIDR)

        if (this.notEnoughSlots(pts)) {
          untilIDR = false
          this.flushBuffer(untilIDR)
        }
        pktDrop = this.handleNewPktOnFlush(data.isIDR, media.byteLength)
        if (pktDrop) return
      }
    }

    mediaArray[index] = {
      pts: pts,
      receive_ts: Date.now(),
      decode_ts: 0,
      yuv_ts: 0,
      render_ts: 0,
      media: media,
      meta: meta,
      metadata: data.metadata,
      isIDR: data.isIDR,
    }

    if (data.isIDR == true) {
      this.bufferIFrame += 1
    }

    this.framesReceivedBetweenTimerInterval += 1
    if (this.framesReceivedBetweenTimerInterval > this.maxFramesReceivedBetweenTimerInterval) {
      this.maxFramesReceivedBetweenTimerInterval = this.framesReceivedBetweenTimerInterval
    }

    if (!this.aheadof(pts, this.prevSeq)) {
      // writePtr += (cur - prev)
      this.writePtr = this.seqAdd(this.writePtr, this.seqDiff(pts, this.prevSeq, CACHE_BUF_LENGTH), CACHE_BUF_LENGTH)

      if (this.seqAdd(index, 1, CACHE_BUF_LENGTH) != this.writePtr) {
        this.dumpJitterBufInfo('dec worker internal info: index (' + index + ') != write_ptr (' + this.writePtr + ')')
        // debugger
      }
      this.prevSeq = pts
    }

    this.dumpJitterBufInfo('Leaving Decoder.prototype.receiveFrame')
    //refactor end
  }

  Decoder.prototype.startEmiter = function () {
    self.decoder.startEmit = true
    if (cachedFirstFrame != undefined) {
      self.postMessage(cachedFirstFrame, [cachedFirstFrame.data.buffer])
      send_out_buffer += 1
      this.receivedEmit++
      cachedFirstFrame = undefined
    }
    if (cachedPanoramaFirstFrame != undefined) {
      self.postMessage(cachedPanoramaFirstFrame)
      send_out_buffer += 1
      this.receivedEmit++
      cachedPanoramaFirstFrame = undefined
    }
  }

  Decoder.prototype.decodePanorama = function (data) {
    console.log('upload pano data')
    var content = data.data.data
    var content_size = data.data.mediaLen
    // var cacheBuffer = Module._malloc(content_size)
    // var resultBuffer = Module._malloc(64)
    Module.HEAPU8.set(content, cacheBuffer)
    let ret = 0
    try {
      ret = Module._decodeData(0, 0, cacheBuffer, content_size, resultBuffer)
      // // console.log('[][Core][WASM] return value %s',ret)
      // if(ret!=0){
      //   // console.log('[][Core][WASM],-abcdefg-----> ', ret)

      //   var ret_close = Module._closeDecoder(0)
      //   // eslint-disable-next-line no-empty
      //   if (ret_close === 0) {
      //     // console.log('[][Core][WASM] decoder closed for restart')
      //   } else {
      //     printConsole.error('close decoder failed after decode pano.')
      //     return 1
      //   }
      //   var ret0 = Module._openDecoder(0, 0, 2)
      //   // console.log('[][Core][WASM] decoder restart success')
      //   // var ret1 = Module._openDecoder(1, decoder_type, LOG_LEVEL_WASM)
      //   if (ret0 === 0) {
      //     ret = Module._decodeData(0, 0, cacheBuffer, content_size, resultBuffer)
      //   } else {
      //     printConsole.error('openDecoder failed with error ' + String(ret0) , '5001')
      //     return 1
      //   }
      // }
    } catch (e) {
      console.log('catch error ', e)
      printConsole.error(e.message, '5002')
    }
    // let ret = Module._decodeData(0, 0, cacheBuffer, content_size, resultBuffer)
    var width = Module.getValue(resultBuffer, 'i32')
    var height = Module.getValue(resultBuffer + 4, 'i32')
    var stride_y = Module.getValue(resultBuffer + 20, 'i32')
    var stride_u = Module.getValue(resultBuffer + 24, 'i32')
    var stride_v = Module.getValue(resultBuffer + 28, 'i32')
    var addr_y = Module.getValue(resultBuffer + 8, 'i32')
    var addr_u = Module.getValue(resultBuffer + 12, 'i32')
    var addr_v = Module.getValue(resultBuffer + 16, 'i32')
    var poc = Module.getValue(resultBuffer + 32, 'i32')
    if (ret != 0) {
      printConsole.log(
        'Decode Data error for panorama, ret value is ' + String(ret) + ', frame content size: ' + String(content_size),
      )
      return
    }

    var yuv_data = new Uint8Array((width * height * 3) / 2)
    let pos = 0
    for (let i = 0; i < height; i++) {
      let src = addr_y + i * stride_y
      let tmp = HEAPU8.subarray(src, src + width)
      tmp = new Uint8Array(tmp)
      yuv_data.set(tmp, pos)
      pos += tmp.length
    }
    for (let i = 0; i < height / 2; i++) {
      let src = addr_u + i * stride_u
      let tmp = HEAPU8.subarray(src, src + width / 2)
      tmp = new Uint8Array(tmp)
      yuv_data.set(tmp, pos)
      pos += tmp.length

      let src2 = addr_v + i * stride_v
      let tmp2 = HEAPU8.subarray(src2, src2 + width / 2)
      tmp2 = new Uint8Array(tmp2)
      yuv_data.set(tmp2, pos)
      pos += tmp2.length
    }

    const objData = {
      t: MessageEvent.PanoramaMessage,
      tileId: data.data.tileId,
      uuid: data.data.uuid,
      data: yuv_data,
      x: data.data.x,
      y: data.data.y,
      z: data.data.z,
    }
    //TODO: remove debug
    if (this.startEmit) {
      self.postMessage(objData)
    } else {
      cachedPanoramaFirstFrame = objData
    }

    // console.log('upload pano data with dataLength:', len(yuv_data))
    var ret_close = Module._closeDecoder(0)
    // eslint-disable-next-line no-empty
    if (ret_close === 0) {
      // console.log('[][Core][WASM] decoder closed for restart')
    } else {
      printConsole.error('close decoder failed after decode pano.')
      return 1
    }
    var ret0 = Module._openDecoder(0, 0, 2)
    // var ret1 = Module._openDecoder(1, decoder_type, LOG_LEVEL_WASM)
    if (ret0 === 0) {
      // console.log('[][Core][WASM] decoder restart success')
      self.decoder.startDecoding()
      self.postMessage({ t: MessageEvent.WASMReady, wasm_ready: true, updateStats: false })
    } else {
      printConsole.error('openDecoder failed with error ' + String(ret0), '5001')
      return 1
    }
  }

  Decoder.prototype.decodeFrame = function (data) {
    var content = data.media
    if (typeof content == 'undefined') {
      printConsole.error('null content in decoder', '5999')
      return
    }
    var content_size = content.byteLength
    // var cacheBuffer = Module._malloc(content_size)
    // var resultBuffer = Module._malloc(64)
    Module.HEAPU8.set(content, cacheBuffer)
    const index = data.frameCnt % CACHE_BUF_LENGTH
    mediaArray[index].decode_ts = Date.now()
    var objData
    if (content_size != 0) {
      // var date = Date.now()
      // var curDate = Date.now()
      // while (curDate - date < 100) {
      //   curDate = Date.now()
      // }

      // TODO: Enable/Disable it by config
      if (data.isIDR) {
        this.errorCacheSize = 0
      }
      // Guarantee that stream start from I frame
      if (this.errorCacheSize != 0 || data.isIDR) {
        this.errorCacheBuffer.set(content, this.mediaCacheSize)
        this.errorCacheSize += content.byteLength
      }

      let start_ts = Date.now()
      let ret = 0
      try {
        ret = Module._decodeData(0, data.frameCnt, cacheBuffer, content_size, resultBuffer)
        // if(ret==8){
        //   // console.log('[][Core][WASM],-abcdefg-----> ', ret)

        //   var ret_close = Module._closeDecoder(0)
        //   // eslint-disable-next-line no-empty
        //   if (ret_close === 0) {
        //     // console.log('[][Core][WASM] decoder closed for restart')
        //   } else {
        //     printConsole.error('close decoder failed after decode pano.')
        //     return 1
        //   }
        //   var ret0 = Module._openDecoder(0, 0, 2)
        //   // console.log('[][Core][WASM] decoder restart success')
        //   // var ret1 = Module._openDecoder(1, decoder_type, LOG_LEVEL_WASM)
        //   if (ret0 === 0) {
        //     ret = Module._decodeData(0, data.frameCnt, cacheBuffer, content_size, resultBuffer)
        //   } else {
        //     printConsole.error('openDecoder failed with error ' + String(ret0) , '5001')
        //     return 1
        //   }
        // }
      } catch (e) {
        console.log('catch error ', e)
        if (this.errorCacheSize > 0) {
          downloadBlob(this.errorCacheBuffer.subarray(0, this.errorCacheSize), 'error.264', 'application/octet-stream')
          this.errorCacheSize = 0
        }
        printConsole.error(e.message, '5002')
      }
      var width = Module.getValue(resultBuffer, 'i32')
      var height = Module.getValue(resultBuffer + 4, 'i32')
      var stride_y = Module.getValue(resultBuffer + 20, 'i32')
      var stride_u = Module.getValue(resultBuffer + 24, 'i32')
      var stride_v = Module.getValue(resultBuffer + 28, 'i32')
      var addr_y = Module.getValue(resultBuffer + 8, 'i32')
      var addr_u = Module.getValue(resultBuffer + 12, 'i32')
      var addr_v = Module.getValue(resultBuffer + 16, 'i32')
      var poc = Module.getValue(resultBuffer + 32, 'i32')
      var pts = data.frameCnt
      if (ret != 0) {
        printConsole.log(
          'Decode Data error for video stream, ret value is ' +
            String(ret) +
            ', frame content size: ' +
            String(content_size),
        )
        if (this.errorCacheSize > 0) {
          downloadBlob(this.errorCacheBuffer.subarray(0, this.errorCacheSize), 'error.264', 'application/octet-stream')
          this.errorCacheSize = 0
        }
        printConsole.log('current poc is ' + String(poc) + ', last poc is ' + String(lastPoc))
        return
      }
      lastPoc = poc
      this.receivedYUV++
      let end_ts = Date.now()
      fdt = end_ts - start_ts
      if (fdt + self.decoder.getFrameInterval > 84) {
        this.JankTimes++
      }
      if (fdt + self.decoder.getFrameInterval > 125) {
        this.bigJankTimes++
      }
      self.decoder.dtpf = self.decoder.dtpf * 0.9 + fdt * 0.1
      // if (fdt > self.decoder.dtmf) {
      //   self.decoder.dtmf = fdt
      // }
      self.decoder.decodeTimeCircular[self.decoder.dtcPtr] = fdt
      self.decoder.dtcPtr = (self.decoder.dtcPtr + 1) % self.decoder.decodeTimeCircular.length

      if (YUVArray.length <= 0) {
        // printConsole.error('No buffer to save YUV after decoding, pts is ' + String(pts), '5002')
        return
      }
      var first_available_buffer = YUVArray.shift()
      var yuv_data = first_available_buffer.buffer

      let pos = 0
      for (let i = 0; i < height; i++) {
        let src = addr_y + i * stride_y
        let tmp = HEAPU8.subarray(src, src + width)
        tmp = new Uint8Array(tmp)
        yuv_data.set(tmp, pos)
        pos += tmp.length
      }
      for (let i = 0; i < height / 2; i++) {
        let src = addr_u + i * stride_u
        let tmp = HEAPU8.subarray(src, src + width / 2)
        tmp = new Uint8Array(tmp)
        yuv_data.set(tmp, pos)
        pos += tmp.length

        let src2 = addr_v + i * stride_v
        let tmp2 = HEAPU8.subarray(src2, src2 + width / 2)
        tmp2 = new Uint8Array(tmp2)
        yuv_data.set(tmp2, pos)
        pos += tmp2.length
      }
      objData = {
        t: MessageEvent.DecodeMessage,
        data: yuv_data,
        width: width,
        height: height,
        pts: data.frameCnt,
        yuv_ts: Date.now(),
        meta: data.meta,
        metadata: data.metadata,
      }
    } else {
      objData = {
        t: MessageEvent.DecodeMessage,
        data: null,
        width: 0,
        height: 0,
        pts: data.frameCnt,
        yuv_ts: Date.now(),
        meta: data.meta,
        metadata: data.metadata,
      }
    }
    if (this.startEmit) {
      if (objData.data != null) {
        self.postMessage(objData, [objData.data.buffer])
        send_out_buffer += 1
        this.receivedEmit++
      } else {
        self.postMessage(objData)
        this.receivedEmit++
      }
    } else {
      if (objData.data != null) {
        cachedFirstFrame = objData
      }
    }
    // if (cacheBuffer != null) {
    //   Module._free(cacheBuffer)
    //   cacheBuffer = null
    // }
    // if (resultBuffer != null) {
    //   Module._free(resultBuffer)
    //   resultBuffer = null
    // }

    return
  }

  Decoder.prototype.receiveBuffer = function (data) {
    framesReturned++
    send_out_buffer -= 1
    YUVArray.push({ status: 0, buffer: data.buffer })
  }

  Decoder.prototype.setPassiveJitter = function (len) {
    this.passiveJitterLength = len
  }

  Decoder.prototype.uninitDecoder = function () {
    printConsole.log('Going to uninit decoder.')
  }

  Decoder.prototype.StartRecord = function () {
    printConsole.log('Start Record')
    this.startRecord = true
  }

  Decoder.prototype.SaveRecord = function () {
    printConsole.log('Save Record')
    this.saveRecord = true
  }

  Decoder.prototype.ReceivePanorama = function (data) {
    self.decoder.resetDecoder()
    self.decoder.decodePanorama(data)
  }

  Decoder.prototype.LoadWASM = function (url) {
    printConsole.log('Load WASM from ' + String(url))
    try {
      self.importScripts(url)
    } catch (e) {
      console.log('catch error ', e)
      printConsole.error(e.message, '5003')
    }
  }

  // self.incoming_pkt_queue = new array()

  function getRandomInt(max) {
    return Math.floor(Math.random() * max)
  }

  // console.log(getRandomInt(30));

  self.decoder = new Decoder()

  netArray = []

  var gTmpIdx = 0
  var gLossCnt = 0
  self.onmessage = function (evt) {
    switch (evt.data.t) {
      case 1: // Init Message
        self.decoder.initAll(evt.data.config)
        break
      case 0: // Decode Message
        // console.log('[][Core][WASM],------> ', evt.data)
        gTmpIdx += 1

        randLen = 16
        // randLen = getRandomInt(30)

        // eslint-disable-next-line no-constant-condition
        if (gTmpIdx > 100 && false) {
          var test_jitter_buffer = true
          if (test_jitter_buffer == true) {
            if (netArray.length % 5 == 4) {
              // netArray.insert(netArray.length -1, evt.data)
              netArray.splice(netArray.length - 1, 0, evt.data)
            } else {
              netArray.push(evt.data)
            }
            if (netArray.length > randLen) {
              // 1. jitter
              while (netArray.length > 0) {
                // console.log("[xmedia] array len: %s", netArray.length)
                gLossCnt += 1

                var pkt = netArray.shift()
                // lose pkt
                var dropInterval = 50
                var dropContinousPkts = 3
                if (gLossCnt % dropInterval < dropContinousPkts) {
                  if (gLossCnt == dropInterval + dropContinousPkts - 1) {
                    gLossCnt = 0
                  }
                } else {
                  self.decoder.receiveFrame(pkt)
                }
              }
              // // 2. disorder
              // if (incoming_pkt_queue.length % 3) {
              //   in[0]
              //   in[2]
              //   in[1]
              // }
            }
          } else {
            self.decoder.receiveFrame(evt.data)
          }
        } else {
          self.decoder.receiveFrame(evt.data)
        }
        break
      case 2: // Receive used buffer
        self.decoder.receiveBuffer(evt.data)
        break
      case 3: // Unint Message
        self.decoder.uninitDecoder()
        break
      case 4: // Reset status
        self.decoder.resetDecoder()
        break
      case 5: // Start emit
        self.decoder.startEmiter()
        break
      case 6: // Start Record
        self.decoder.StartRecord()
        break
      case 7: // Save Record
        self.decoder.SaveRecord()
        break
      case 8: // Panorama Decode Message
        self.decoder.ReceivePanorama(evt.data)
        break
      case 9: // Select WASM Version
        self.decoder.setPassiveJitter(evt.data.jitterLength)
        self.decoder.LoadWASM(evt.data.url)
        break
      case 100: // change decoder worker status
        self.decoder.changeLogSwitch(evt.data.status)
        break
    }
  }
}
`;
const panorama_width = 4096
  , panorama_height = 2048
  , tile_width = 512
  , tile_height = 256;
function ToRadius(i) {
    return i / 180 * Math.PI
}
function ToAngle(i) {
    return i / Math.PI * 180
}
function getAngleInView(i, e) {
    const t = {}
      , r = e.x - i.width * .5
      , n = i.height * .5 - e.y
      , o = -1 * ToRadius(i.angle.pitch)
      , a = ToRadius(i.angle.yaw)
      , s = i.width / 2 / Math.tan(ToRadius(i.horz_fov / 2))
      , l = Math.sin(o)
      , u = Math.cos(o);
    for (t.yaw = Math.atan2(r, s * u + n * l),
    t.pitch = Math.atan2((n - s * Math.tan(o)) * Math.cos(t.yaw), s + n * Math.tan(o)),
    t.pitch = ToAngle(t.pitch),
    t.yaw = ToAngle(a + t.yaw); t.yaw > 359.9; )
        t.yaw -= 360;
    for (; t.yaw < 0; )
        t.yaw += 360;
    return t
}
function getRectangleInView(i) {
    const e = {}
      , t = Array(9)
      , r = i.height
      , n = i.width;
    for (let a = 0, s = 0; s <= r; s += r / 2)
        for (let l = 0; l <= n; l += n / 2,
        a++) {
            const u = {};
            u.x = l,
            u.y = s;
            let c = {};
            c = i,
            c.angle.pitch >= 90 && (c.angle.pitch = 89.999),
            c.angle.pitch <= -90 && (c.angle.pitch = -89.999),
            c.angle.yaw = 0,
            t[a] = getAngleInView(i, u),
            t[a].pitch < -90 ? t[a].pitch = 90 : t[a].pitch > 90 && (t[a].pitch = -90)
        }
    let o = t[0].yaw > t[3].yaw ? 3 : 0;
    return t[o].yaw > t[6].yaw && (o = 6),
    t[o].yaw > t[o + 2].yaw && (t[o + 2].yaw += 360),
    t[o + 2].yaw > t[o].yaw + 180 ? (e.x = 0,
    e.width = panorama_width) : (e.x = (t[o].yaw / 360 - .5) * panorama_width,
    e.width = (t[o + 2].yaw / 360 - .5) * panorama_width - e.x),
    e.y = (.5 - t[t[0].pitch > t[1].pitch ? 0 : 1].pitch / 180) * panorama_height,
    e.height = (.5 - t[t[6].pitch > t[7].pitch ? 7 : 6].pitch / 180) * panorama_height - e.y,
    e
}
function MaskSetToOne(i, e) {
    const t = i / 8
      , r = i % 8;
    e.setUint8(t, e.getUint8(t) | 1 << 7 - r)
}
function IsAll0(i) {
    return i.getUint32(0) == 0 && i.getUint32(4) == 0
}
function getMaskFromTiles(i, e) {
    const t = new DataView(e);
    i.forEach(function(r, n) {
        MaskSetToOne(r, t)
    })
}
function operateForDataView(i, e, t, r) {
    t.setUint32(0, r(i.getUint32(0), e.getUint32(0))),
    t.setUint32(4, r(i.getUint32(4), e.getUint32(4)))
}
function getTilesInView(i, e) {
    const t = getRectangleInView(i)
      , r = Math.floor(t.x / tile_width)
      , n = Math.floor((t.x + t.width - 1) / tile_width)
      , o = Math.floor(t.y / tile_height)
      , a = Math.floor((t.y + t.height - 1) / tile_height);
    console.log({
        left: r,
        right: n,
        top: o,
        bottom: a
    });
    const l = []
      , u = panorama_height / tile_height;
    for (let c = r; c <= n; c++)
        for (let h = o; h <= a; h++)
            l.push(c * u + h);
    return console.log(l),
    getMaskFromTiles(l, e),
    l
}
var md5$1 = {
    exports: {}
};
(function(module) {
    (function() {
        var ERROR = "input is invalid type"
          , WINDOW = typeof window == "object"
          , root = WINDOW ? window : {};
        root.JS_MD5_NO_WINDOW && (WINDOW = !1);
        var WEB_WORKER = !WINDOW && typeof self == "object"
          , NODE_JS = !root.JS_MD5_NO_NODE_JS && typeof process == "object" && process.versions && process.versions.node;
        NODE_JS ? root = commonjsGlobal : WEB_WORKER && (root = self);
        var COMMON_JS = !root.JS_MD5_NO_COMMON_JS && !0 && module.exports, ARRAY_BUFFER = !root.JS_MD5_NO_ARRAY_BUFFER && typeof ArrayBuffer != "undefined", HEX_CHARS = "0123456789abcdef".split(""), EXTRA = [128, 32768, 8388608, -2147483648], SHIFT = [0, 8, 16, 24], OUTPUT_TYPES = ["hex", "array", "digest", "buffer", "arrayBuffer", "base64"], BASE64_ENCODE_CHAR = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""), blocks = [], buffer8;
        if (ARRAY_BUFFER) {
            var buffer = new ArrayBuffer(68);
            buffer8 = new Uint8Array(buffer),
            blocks = new Uint32Array(buffer)
        }
        (root.JS_MD5_NO_NODE_JS || !Array.isArray) && (Array.isArray = function(i) {
            return Object.prototype.toString.call(i) === "[object Array]"
        }
        ),
        ARRAY_BUFFER && (root.JS_MD5_NO_ARRAY_BUFFER_IS_VIEW || !ArrayBuffer.isView) && (ArrayBuffer.isView = function(i) {
            return typeof i == "object" && i.buffer && i.buffer.constructor === ArrayBuffer
        }
        );
        var createOutputMethod = function(i) {
            return function(e, t) {
                return new Md5(!0).update(e, t)[i]()
            }
        }
          , createMethod = function() {
            var i = createOutputMethod("hex");
            NODE_JS && (i = nodeWrap(i)),
            i.getCtx = i.create = function() {
                return new Md5
            }
            ,
            i.update = function(r) {
                return i.create().update(r)
            }
            ;
            for (var e = 0; e < OUTPUT_TYPES.length; ++e) {
                var t = OUTPUT_TYPES[e];
                i[t] = createOutputMethod(t)
            }
            return i
        }
          , nodeWrap = function(method) {
            var crypto = eval("require('crypto')")
              , Buffer = eval("require('buffer').Buffer")
              , nodeMethod = function(i) {
                if (typeof i == "string")
                    return crypto.createHash("md5").update(i, "utf8").digest("hex");
                if (i == null)
                    throw ERROR;
                return i.constructor === ArrayBuffer && (i = new Uint8Array(i)),
                Array.isArray(i) || ArrayBuffer.isView(i) || i.constructor === Buffer ? crypto.createHash("md5").update(new Buffer(i)).digest("hex") : method(i)
            };
            return nodeMethod
        };
        function Md5(i) {
            if (i)
                blocks[0] = blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0,
                this.blocks = blocks,
                this.buffer8 = buffer8;
            else if (ARRAY_BUFFER) {
                var e = new ArrayBuffer(68);
                this.buffer8 = new Uint8Array(e),
                this.blocks = new Uint32Array(e)
            } else
                this.blocks = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
            this.h0 = this.h1 = this.h2 = this.h3 = this.start = this.bytes = this.hBytes = 0,
            this.finalized = this.hashed = !1,
            this.first = !0
        }
        Md5.prototype.update = function(i, e) {
            if (!this.finalized) {
                for (var t, r = 0, n, o = i.length, a = this.blocks, s = this.buffer8; r < o; ) {
                    if (this.hashed && (this.hashed = !1,
                    a[0] = a[16],
                    a[16] = a[1] = a[2] = a[3] = a[4] = a[5] = a[6] = a[7] = a[8] = a[9] = a[10] = a[11] = a[12] = a[13] = a[14] = a[15] = 0),
                    ARRAY_BUFFER)
                        for (n = this.start; r < o && n < 64; ++r)
                            t = i.charCodeAt(r),
                            e || t < 128 ? s[n++] = t : t < 2048 ? (s[n++] = 192 | t >> 6,
                            s[n++] = 128 | t & 63) : t < 55296 || t >= 57344 ? (s[n++] = 224 | t >> 12,
                            s[n++] = 128 | t >> 6 & 63,
                            s[n++] = 128 | t & 63) : (t = 65536 + ((t & 1023) << 10 | i.charCodeAt(++r) & 1023),
                            s[n++] = 240 | t >> 18,
                            s[n++] = 128 | t >> 12 & 63,
                            s[n++] = 128 | t >> 6 & 63,
                            s[n++] = 128 | t & 63);
                    else
                        for (n = this.start; r < o && n < 64; ++r)
                            t = i.charCodeAt(r),
                            e || t < 128 ? a[n >> 2] |= t << SHIFT[n++ & 3] : t < 2048 ? (a[n >> 2] |= (192 | t >> 6) << SHIFT[n++ & 3],
                            a[n >> 2] |= (128 | t & 63) << SHIFT[n++ & 3]) : t < 55296 || t >= 57344 ? (a[n >> 2] |= (224 | t >> 12) << SHIFT[n++ & 3],
                            a[n >> 2] |= (128 | t >> 6 & 63) << SHIFT[n++ & 3],
                            a[n >> 2] |= (128 | t & 63) << SHIFT[n++ & 3]) : (t = 65536 + ((t & 1023) << 10 | i.charCodeAt(++r) & 1023),
                            a[n >> 2] |= (240 | t >> 18) << SHIFT[n++ & 3],
                            a[n >> 2] |= (128 | t >> 12 & 63) << SHIFT[n++ & 3],
                            a[n >> 2] |= (128 | t >> 6 & 63) << SHIFT[n++ & 3],
                            a[n >> 2] |= (128 | t & 63) << SHIFT[n++ & 3]);
                    this.lastByteIndex = n,
                    this.bytes += n - this.start,
                    n >= 64 ? (this.start = n - 64,
                    this.hash(),
                    this.hashed = !0) : this.start = n
                }
                return this.bytes > 4294967295 && (this.hBytes += this.bytes / 4294967296 << 0,
                this.bytes = this.bytes % 4294967296),
                this
            }
        }
        ,
        Md5.prototype.finalize = function() {
            if (!this.finalized) {
                this.finalized = !0;
                var i = this.blocks
                  , e = this.lastByteIndex;
                i[e >> 2] |= EXTRA[e & 3],
                e >= 56 && (this.hashed || this.hash(),
                i[0] = i[16],
                i[16] = i[1] = i[2] = i[3] = i[4] = i[5] = i[6] = i[7] = i[8] = i[9] = i[10] = i[11] = i[12] = i[13] = i[14] = i[15] = 0),
                i[14] = this.bytes << 3,
                i[15] = this.hBytes << 3 | this.bytes >>> 29,
                this.hash()
            }
        }
        ,
        Md5.prototype.hash = function() {
            var i, e, t, r, n, o, a = this.blocks;
            this.first ? (i = a[0] - 680876937,
            i = (i << 7 | i >>> 25) - 271733879 << 0,
            r = (-1732584194 ^ i & 2004318071) + a[1] - 117830708,
            r = (r << 12 | r >>> 20) + i << 0,
            t = (-271733879 ^ r & (i ^ -271733879)) + a[2] - 1126478375,
            t = (t << 17 | t >>> 15) + r << 0,
            e = (i ^ t & (r ^ i)) + a[3] - 1316259209,
            e = (e << 22 | e >>> 10) + t << 0) : (i = this.h0,
            e = this.h1,
            t = this.h2,
            r = this.h3,
            i += (r ^ e & (t ^ r)) + a[0] - 680876936,
            i = (i << 7 | i >>> 25) + e << 0,
            r += (t ^ i & (e ^ t)) + a[1] - 389564586,
            r = (r << 12 | r >>> 20) + i << 0,
            t += (e ^ r & (i ^ e)) + a[2] + 606105819,
            t = (t << 17 | t >>> 15) + r << 0,
            e += (i ^ t & (r ^ i)) + a[3] - 1044525330,
            e = (e << 22 | e >>> 10) + t << 0),
            i += (r ^ e & (t ^ r)) + a[4] - 176418897,
            i = (i << 7 | i >>> 25) + e << 0,
            r += (t ^ i & (e ^ t)) + a[5] + 1200080426,
            r = (r << 12 | r >>> 20) + i << 0,
            t += (e ^ r & (i ^ e)) + a[6] - 1473231341,
            t = (t << 17 | t >>> 15) + r << 0,
            e += (i ^ t & (r ^ i)) + a[7] - 45705983,
            e = (e << 22 | e >>> 10) + t << 0,
            i += (r ^ e & (t ^ r)) + a[8] + 1770035416,
            i = (i << 7 | i >>> 25) + e << 0,
            r += (t ^ i & (e ^ t)) + a[9] - 1958414417,
            r = (r << 12 | r >>> 20) + i << 0,
            t += (e ^ r & (i ^ e)) + a[10] - 42063,
            t = (t << 17 | t >>> 15) + r << 0,
            e += (i ^ t & (r ^ i)) + a[11] - 1990404162,
            e = (e << 22 | e >>> 10) + t << 0,
            i += (r ^ e & (t ^ r)) + a[12] + 1804603682,
            i = (i << 7 | i >>> 25) + e << 0,
            r += (t ^ i & (e ^ t)) + a[13] - 40341101,
            r = (r << 12 | r >>> 20) + i << 0,
            t += (e ^ r & (i ^ e)) + a[14] - 1502002290,
            t = (t << 17 | t >>> 15) + r << 0,
            e += (i ^ t & (r ^ i)) + a[15] + 1236535329,
            e = (e << 22 | e >>> 10) + t << 0,
            i += (t ^ r & (e ^ t)) + a[1] - 165796510,
            i = (i << 5 | i >>> 27) + e << 0,
            r += (e ^ t & (i ^ e)) + a[6] - 1069501632,
            r = (r << 9 | r >>> 23) + i << 0,
            t += (i ^ e & (r ^ i)) + a[11] + 643717713,
            t = (t << 14 | t >>> 18) + r << 0,
            e += (r ^ i & (t ^ r)) + a[0] - 373897302,
            e = (e << 20 | e >>> 12) + t << 0,
            i += (t ^ r & (e ^ t)) + a[5] - 701558691,
            i = (i << 5 | i >>> 27) + e << 0,
            r += (e ^ t & (i ^ e)) + a[10] + 38016083,
            r = (r << 9 | r >>> 23) + i << 0,
            t += (i ^ e & (r ^ i)) + a[15] - 660478335,
            t = (t << 14 | t >>> 18) + r << 0,
            e += (r ^ i & (t ^ r)) + a[4] - 405537848,
            e = (e << 20 | e >>> 12) + t << 0,
            i += (t ^ r & (e ^ t)) + a[9] + 568446438,
            i = (i << 5 | i >>> 27) + e << 0,
            r += (e ^ t & (i ^ e)) + a[14] - 1019803690,
            r = (r << 9 | r >>> 23) + i << 0,
            t += (i ^ e & (r ^ i)) + a[3] - 187363961,
            t = (t << 14 | t >>> 18) + r << 0,
            e += (r ^ i & (t ^ r)) + a[8] + 1163531501,
            e = (e << 20 | e >>> 12) + t << 0,
            i += (t ^ r & (e ^ t)) + a[13] - 1444681467,
            i = (i << 5 | i >>> 27) + e << 0,
            r += (e ^ t & (i ^ e)) + a[2] - 51403784,
            r = (r << 9 | r >>> 23) + i << 0,
            t += (i ^ e & (r ^ i)) + a[7] + 1735328473,
            t = (t << 14 | t >>> 18) + r << 0,
            e += (r ^ i & (t ^ r)) + a[12] - 1926607734,
            e = (e << 20 | e >>> 12) + t << 0,
            n = e ^ t,
            i += (n ^ r) + a[5] - 378558,
            i = (i << 4 | i >>> 28) + e << 0,
            r += (n ^ i) + a[8] - 2022574463,
            r = (r << 11 | r >>> 21) + i << 0,
            o = r ^ i,
            t += (o ^ e) + a[11] + 1839030562,
            t = (t << 16 | t >>> 16) + r << 0,
            e += (o ^ t) + a[14] - 35309556,
            e = (e << 23 | e >>> 9) + t << 0,
            n = e ^ t,
            i += (n ^ r) + a[1] - 1530992060,
            i = (i << 4 | i >>> 28) + e << 0,
            r += (n ^ i) + a[4] + 1272893353,
            r = (r << 11 | r >>> 21) + i << 0,
            o = r ^ i,
            t += (o ^ e) + a[7] - 155497632,
            t = (t << 16 | t >>> 16) + r << 0,
            e += (o ^ t) + a[10] - 1094730640,
            e = (e << 23 | e >>> 9) + t << 0,
            n = e ^ t,
            i += (n ^ r) + a[13] + 681279174,
            i = (i << 4 | i >>> 28) + e << 0,
            r += (n ^ i) + a[0] - 358537222,
            r = (r << 11 | r >>> 21) + i << 0,
            o = r ^ i,
            t += (o ^ e) + a[3] - 722521979,
            t = (t << 16 | t >>> 16) + r << 0,
            e += (o ^ t) + a[6] + 76029189,
            e = (e << 23 | e >>> 9) + t << 0,
            n = e ^ t,
            i += (n ^ r) + a[9] - 640364487,
            i = (i << 4 | i >>> 28) + e << 0,
            r += (n ^ i) + a[12] - 421815835,
            r = (r << 11 | r >>> 21) + i << 0,
            o = r ^ i,
            t += (o ^ e) + a[15] + 530742520,
            t = (t << 16 | t >>> 16) + r << 0,
            e += (o ^ t) + a[2] - 995338651,
            e = (e << 23 | e >>> 9) + t << 0,
            i += (t ^ (e | ~r)) + a[0] - 198630844,
            i = (i << 6 | i >>> 26) + e << 0,
            r += (e ^ (i | ~t)) + a[7] + 1126891415,
            r = (r << 10 | r >>> 22) + i << 0,
            t += (i ^ (r | ~e)) + a[14] - 1416354905,
            t = (t << 15 | t >>> 17) + r << 0,
            e += (r ^ (t | ~i)) + a[5] - 57434055,
            e = (e << 21 | e >>> 11) + t << 0,
            i += (t ^ (e | ~r)) + a[12] + 1700485571,
            i = (i << 6 | i >>> 26) + e << 0,
            r += (e ^ (i | ~t)) + a[3] - 1894986606,
            r = (r << 10 | r >>> 22) + i << 0,
            t += (i ^ (r | ~e)) + a[10] - 1051523,
            t = (t << 15 | t >>> 17) + r << 0,
            e += (r ^ (t | ~i)) + a[1] - 2054922799,
            e = (e << 21 | e >>> 11) + t << 0,
            i += (t ^ (e | ~r)) + a[8] + 1873313359,
            i = (i << 6 | i >>> 26) + e << 0,
            r += (e ^ (i | ~t)) + a[15] - 30611744,
            r = (r << 10 | r >>> 22) + i << 0,
            t += (i ^ (r | ~e)) + a[6] - 1560198380,
            t = (t << 15 | t >>> 17) + r << 0,
            e += (r ^ (t | ~i)) + a[13] + 1309151649,
            e = (e << 21 | e >>> 11) + t << 0,
            i += (t ^ (e | ~r)) + a[4] - 145523070,
            i = (i << 6 | i >>> 26) + e << 0,
            r += (e ^ (i | ~t)) + a[11] - 1120210379,
            r = (r << 10 | r >>> 22) + i << 0,
            t += (i ^ (r | ~e)) + a[2] + 718787259,
            t = (t << 15 | t >>> 17) + r << 0,
            e += (r ^ (t | ~i)) + a[9] - 343485551,
            e = (e << 21 | e >>> 11) + t << 0,
            this.first ? (this.h0 = i + 1732584193 << 0,
            this.h1 = e - 271733879 << 0,
            this.h2 = t - 1732584194 << 0,
            this.h3 = r + 271733878 << 0,
            this.first = !1) : (this.h0 = this.h0 + i << 0,
            this.h1 = this.h1 + e << 0,
            this.h2 = this.h2 + t << 0,
            this.h3 = this.h3 + r << 0)
        }
        ,
        Md5.prototype.hex = function() {
            this.finalize();
            var i = this.h0
              , e = this.h1
              , t = this.h2
              , r = this.h3;
            return HEX_CHARS[i >> 4 & 15] + HEX_CHARS[i & 15] + HEX_CHARS[i >> 12 & 15] + HEX_CHARS[i >> 8 & 15] + HEX_CHARS[i >> 20 & 15] + HEX_CHARS[i >> 16 & 15] + HEX_CHARS[i >> 28 & 15] + HEX_CHARS[i >> 24 & 15] + HEX_CHARS[e >> 4 & 15] + HEX_CHARS[e & 15] + HEX_CHARS[e >> 12 & 15] + HEX_CHARS[e >> 8 & 15] + HEX_CHARS[e >> 20 & 15] + HEX_CHARS[e >> 16 & 15] + HEX_CHARS[e >> 28 & 15] + HEX_CHARS[e >> 24 & 15] + HEX_CHARS[t >> 4 & 15] + HEX_CHARS[t & 15] + HEX_CHARS[t >> 12 & 15] + HEX_CHARS[t >> 8 & 15] + HEX_CHARS[t >> 20 & 15] + HEX_CHARS[t >> 16 & 15] + HEX_CHARS[t >> 28 & 15] + HEX_CHARS[t >> 24 & 15] + HEX_CHARS[r >> 4 & 15] + HEX_CHARS[r & 15] + HEX_CHARS[r >> 12 & 15] + HEX_CHARS[r >> 8 & 15] + HEX_CHARS[r >> 20 & 15] + HEX_CHARS[r >> 16 & 15] + HEX_CHARS[r >> 28 & 15] + HEX_CHARS[r >> 24 & 15]
        }
        ,
        Md5.prototype.toString = Md5.prototype.hex,
        Md5.prototype.digest = function(i) {
            if (i === "hex")
                return this.hex();
            this.finalize();
            var e = this.h0
              , t = this.h1
              , r = this.h2
              , n = this.h3
              , o = [e & 255, e >> 8 & 255, e >> 16 & 255, e >> 24 & 255, t & 255, t >> 8 & 255, t >> 16 & 255, t >> 24 & 255, r & 255, r >> 8 & 255, r >> 16 & 255, r >> 24 & 255, n & 255, n >> 8 & 255, n >> 16 & 255, n >> 24 & 255];
            return o
        }
        ,
        Md5.prototype.array = Md5.prototype.digest,
        Md5.prototype.arrayBuffer = function() {
            this.finalize();
            var i = new ArrayBuffer(16)
              , e = new Uint32Array(i);
            return e[0] = this.h0,
            e[1] = this.h1,
            e[2] = this.h2,
            e[3] = this.h3,
            i
        }
        ,
        Md5.prototype.buffer = Md5.prototype.arrayBuffer,
        Md5.prototype.base64 = function() {
            for (var i, e, t, r = "", n = this.array(), o = 0; o < 15; )
                i = n[o++],
                e = n[o++],
                t = n[o++],
                r += BASE64_ENCODE_CHAR[i >>> 2] + BASE64_ENCODE_CHAR[(i << 4 | e >>> 4) & 63] + BASE64_ENCODE_CHAR[(e << 2 | t >>> 6) & 63] + BASE64_ENCODE_CHAR[t & 63];
            return i = n[o],
            r += BASE64_ENCODE_CHAR[i >>> 2] + BASE64_ENCODE_CHAR[i << 4 & 63] + "==",
            r
        }
        ;
        var exports = createMethod();
        COMMON_JS ? module.exports = exports : root.md5 = exports
    }
    )()
}
)(md5$1);
var crypto = {
    exports: {}
};
(function(i) {
    var e = e || function(t, r) {
        var n = {}
          , o = n.lib = {}
          , a = function() {}
          , s = o.Base = {
            extend: function(g) {
                a.prototype = this;
                var m = new a;
                return g && m.mixIn(g),
                m.hasOwnProperty("init") || (m.init = function() {
                    m.$super.init.apply(this, arguments)
                }
                ),
                m.init.prototype = m,
                m.$super = this,
                m
            },
            create: function() {
                var g = this.extend();
                return g.init.apply(g, arguments),
                g
            },
            init: function() {},
            mixIn: function(g) {
                for (var m in g)
                    g.hasOwnProperty(m) && (this[m] = g[m]);
                g.hasOwnProperty("toString") && (this.toString = g.toString)
            },
            clone: function() {
                return this.init.prototype.extend(this)
            }
        }
          , l = o.WordArray = s.extend({
            init: function(g, m) {
                g = this.words = g || [],
                this.sigBytes = m != r ? m : 4 * g.length
            },
            toString: function(g) {
                return (g || c).stringify(this)
            },
            concat: function(g) {
                var m = this.words
                  , v = g.words
                  , y = this.sigBytes;
                if (g = g.sigBytes,
                this.clamp(),
                y % 4)
                    for (var b = 0; b < g; b++)
                        m[y + b >>> 2] |= (v[b >>> 2] >>> 24 - 8 * (b % 4) & 255) << 24 - 8 * ((y + b) % 4);
                else if (65535 < v.length)
                    for (b = 0; b < g; b += 4)
                        m[y + b >>> 2] = v[b >>> 2];
                else
                    m.push.apply(m, v);
                return this.sigBytes += g,
                this
            },
            clamp: function() {
                var g = this.words
                  , m = this.sigBytes;
                g[m >>> 2] &= 4294967295 << 32 - 8 * (m % 4),
                g.length = t.ceil(m / 4)
            },
            clone: function() {
                var g = s.clone.call(this);
                return g.words = this.words.slice(0),
                g
            },
            random: function(g) {
                for (var m = [], v = 0; v < g; v += 4)
                    m.push(4294967296 * t.random() | 0);
                return new l.init(m,g)
            }
        })
          , u = n.enc = {}
          , c = u.Hex = {
            stringify: function(g) {
                var m = g.words;
                g = g.sigBytes;
                for (var v = [], y = 0; y < g; y++) {
                    var b = m[y >>> 2] >>> 24 - 8 * (y % 4) & 255;
                    v.push((b >>> 4).toString(16)),
                    v.push((b & 15).toString(16))
                }
                return v.join("")
            },
            parse: function(g) {
                for (var m = g.length, v = [], y = 0; y < m; y += 2)
                    v[y >>> 3] |= parseInt(g.substr(y, 2), 16) << 24 - 4 * (y % 8);
                return new l.init(v,m / 2)
            }
        }
          , h = u.Latin1 = {
            stringify: function(g) {
                var m = g.words;
                g = g.sigBytes;
                for (var v = [], y = 0; y < g; y++)
                    v.push(String.fromCharCode(m[y >>> 2] >>> 24 - 8 * (y % 4) & 255));
                return v.join("")
            },
            parse: function(g) {
                for (var m = g.length, v = [], y = 0; y < m; y++)
                    v[y >>> 2] |= (g.charCodeAt(y) & 255) << 24 - 8 * (y % 4);
                return new l.init(v,m)
            }
        }
          , f = u.Utf8 = {
            stringify: function(g) {
                try {
                    return decodeURIComponent(escape(h.stringify(g)))
                } catch {
                    throw Error("Malformed UTF-8 data")
                }
            },
            parse: function(g) {
                return h.parse(unescape(encodeURIComponent(g)))
            }
        }
          , d = o.BufferedBlockAlgorithm = s.extend({
            reset: function() {
                this._data = new l.init,
                this._nDataBytes = 0
            },
            _append: function(g) {
                typeof g == "string" && (g = f.parse(g)),
                this._data.concat(g),
                this._nDataBytes += g.sigBytes
            },
            _process: function(g) {
                var m = this._data
                  , v = m.words
                  , y = m.sigBytes
                  , b = this.blockSize
                  , T = y / (4 * b)
                  , T = g ? t.ceil(T) : t.max((T | 0) - this._minBufferSize, 0);
                if (g = T * b,
                y = t.min(4 * g, y),
                g) {
                    for (var C = 0; C < g; C += b)
                        this._doProcessBlock(v, C);
                    C = v.splice(0, g),
                    m.sigBytes -= y
                }
                return new l.init(C,y)
            },
            clone: function() {
                var g = s.clone.call(this);
                return g._data = this._data.clone(),
                g
            },
            _minBufferSize: 0
        });
        o.Hasher = d.extend({
            cfg: s.extend(),
            init: function(g) {
                this.cfg = this.cfg.extend(g),
                this.reset()
            },
            reset: function() {
                d.reset.call(this),
                this._doReset()
            },
            update: function(g) {
                return this._append(g),
                this._process(),
                this
            },
            finalize: function(g) {
                return g && this._append(g),
                this._doFinalize()
            },
            blockSize: 16,
            _createHelper: function(g) {
                return function(m, v) {
                    return new g.init(v).finalize(m)
                }
            },
            _createHmacHelper: function(g) {
                return function(m, v) {
                    return new _.HMAC.init(g,v).finalize(m)
                }
            }
        });
        var _ = n.algo = {};
        return n
    }(Math);
    (function() {
        var t = e
          , a = t.lib
          , r = a.WordArray
          , n = a.Hasher
          , o = []
          , a = t.algo.SHA1 = n.extend({
            _doReset: function() {
                this._hash = new r.init([1732584193, 4023233417, 2562383102, 271733878, 3285377520])
            },
            _doProcessBlock: function(s, l) {
                for (var u = this._hash.words, c = u[0], h = u[1], f = u[2], d = u[3], _ = u[4], g = 0; 80 > g; g++) {
                    if (16 > g)
                        o[g] = s[l + g] | 0;
                    else {
                        var m = o[g - 3] ^ o[g - 8] ^ o[g - 14] ^ o[g - 16];
                        o[g] = m << 1 | m >>> 31
                    }
                    m = (c << 5 | c >>> 27) + _ + o[g],
                    m = 20 > g ? m + ((h & f | ~h & d) + 1518500249) : 40 > g ? m + ((h ^ f ^ d) + 1859775393) : 60 > g ? m + ((h & f | h & d | f & d) - 1894007588) : m + ((h ^ f ^ d) - 899497514),
                    _ = d,
                    d = f,
                    f = h << 30 | h >>> 2,
                    h = c,
                    c = m
                }
                u[0] = u[0] + c | 0,
                u[1] = u[1] + h | 0,
                u[2] = u[2] + f | 0,
                u[3] = u[3] + d | 0,
                u[4] = u[4] + _ | 0
            },
            _doFinalize: function() {
                var s = this._data
                  , l = s.words
                  , u = 8 * this._nDataBytes
                  , c = 8 * s.sigBytes;
                return l[c >>> 5] |= 128 << 24 - c % 32,
                l[(c + 64 >>> 9 << 4) + 14] = Math.floor(u / 4294967296),
                l[(c + 64 >>> 9 << 4) + 15] = u,
                s.sigBytes = 4 * l.length,
                this._process(),
                this._hash
            },
            clone: function() {
                var s = n.clone.call(this);
                return s._hash = this._hash.clone(),
                s
            }
        });
        t.SHA1 = n._createHelper(a),
        t.HmacSHA1 = n._createHmacHelper(a)
    }
    )(),
    function() {
        var t = e
          , r = t.enc.Utf8;
        t.algo.HMAC = t.lib.Base.extend({
            init: function(n, o) {
                n = this._hasher = new n.init,
                typeof o == "string" && (o = r.parse(o));
                var a = n.blockSize
                  , s = 4 * a;
                o.sigBytes > s && (o = n.finalize(o)),
                o.clamp();
                for (var l = this._oKey = o.clone(), u = this._iKey = o.clone(), c = l.words, h = u.words, f = 0; f < a; f++)
                    c[f] ^= 1549556828,
                    h[f] ^= 909522486;
                l.sigBytes = u.sigBytes = s,
                this.reset()
            },
            reset: function() {
                var n = this._hasher;
                n.reset(),
                n.update(this._iKey)
            },
            update: function(n) {
                return this._hasher.update(n),
                this
            },
            finalize: function(n) {
                var o = this._hasher;
                return n = o.finalize(n),
                o.reset(),
                o.finalize(this._oKey.clone().concat(n))
            }
        })
    }(),
    function() {
        var t = e
          , r = t.lib
          , n = r.WordArray
          , o = t.enc;
        o.Base64 = {
            stringify: function(a) {
                var s = a.words
                  , l = a.sigBytes
                  , u = this._map;
                a.clamp();
                for (var c = [], h = 0; h < l; h += 3)
                    for (var f = s[h >>> 2] >>> 24 - h % 4 * 8 & 255, d = s[h + 1 >>> 2] >>> 24 - (h + 1) % 4 * 8 & 255, _ = s[h + 2 >>> 2] >>> 24 - (h + 2) % 4 * 8 & 255, g = f << 16 | d << 8 | _, m = 0; m < 4 && h + m * .75 < l; m++)
                        c.push(u.charAt(g >>> 6 * (3 - m) & 63));
                var v = u.charAt(64);
                if (v)
                    for (; c.length % 4; )
                        c.push(v);
                return c.join("")
            },
            parse: function(a) {
                var s = a.length
                  , l = this._map
                  , u = l.charAt(64);
                if (u) {
                    var c = a.indexOf(u);
                    c != -1 && (s = c)
                }
                for (var h = [], f = 0, d = 0; d < s; d++)
                    if (d % 4) {
                        var _ = l.indexOf(a.charAt(d - 1)) << d % 4 * 2
                          , g = l.indexOf(a.charAt(d)) >>> 6 - d % 4 * 2;
                        h[f >>> 2] |= (_ | g) << 24 - f % 4 * 8,
                        f++
                    }
                return n.create(h, f)
            },
            _map: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
        }
    }(),
    i.exports = e
}
)(crypto);
var domParser = {}
  , sax = {}
  , nameStartChar = /[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/
  , nameChar = new RegExp("[\\-\\.0-9" + nameStartChar.source.slice(1, -1) + "\\u00B7\\u0300-\\u036F\\u203F-\\u2040]")
  , tagNamePattern = new RegExp("^" + nameStartChar.source + nameChar.source + "*(?::" + nameStartChar.source + nameChar.source + "*)?$")
  , S_TAG = 0
  , S_ATTR = 1
  , S_ATTR_SPACE = 2
  , S_EQ = 3
  , S_ATTR_NOQUOT_VALUE = 4
  , S_ATTR_END = 5
  , S_TAG_SPACE = 6
  , S_TAG_CLOSE = 7;
function XMLReader$1() {}
XMLReader$1.prototype = {
    parse: function(i, e, t) {
        var r = this.domBuilder;
        r.startDocument(),
        _copy(e, e = {}),
        parse(i, e, t, r, this.errorHandler),
        r.endDocument()
    }
};
function parse(i, e, t, r, n) {
    function o(F) {
        if (F > 65535) {
            F -= 65536;
            var V = 55296 + (F >> 10)
              , N = 56320 + (F & 1023);
            return String.fromCharCode(V, N)
        } else
            return String.fromCharCode(F)
    }
    function a(F) {
        var V = F.slice(1, -1);
        return V in t ? t[V] : V.charAt(0) === "#" ? o(parseInt(V.substr(1).replace("x", "0x"))) : (n.error("entity not found:" + F),
        F)
    }
    function s(F) {
        if (F > g) {
            var V = i.substring(g, F).replace(/&#?\w+;/g, a);
            f && l(g),
            r.characters(V, 0, F - g),
            g = F
        }
    }
    function l(F, V) {
        for (; F >= c && (V = h.exec(i)); )
            u = V.index,
            c = u + V[0].length,
            f.lineNumber++;
        f.columnNumber = F - u + 1
    }
    for (var u = 0, c = 0, h = /.*(?:\r\n?|\n)|.*$/g, f = r.locator, d = [{
        currentNSMap: e
    }], _ = {}, g = 0; ; ) {
        try {
            var m = i.indexOf("<", g);
            if (m < 0) {
                if (!i.substr(g).match(/^\s*$/)) {
                    var v = r.doc
                      , y = v.createTextNode(i.substr(g));
                    v.appendChild(y),
                    r.currentElement = y
                }
                return
            }
            switch (m > g && s(m),
            i.charAt(m + 1)) {
            case "/":
                var x = i.indexOf(">", m + 3)
                  , b = i.substring(m + 2, x)
                  , T = d.pop();
                x < 0 ? (b = i.substring(m + 2).replace(/[\s<].*/, ""),
                n.error("end tag name: " + b + " is not complete:" + T.tagName),
                x = m + 1 + b.length) : b.match(/\s</) && (b = b.replace(/[\s<].*/, ""),
                n.error("end tag name: " + b + " maybe not complete"),
                x = m + 1 + b.length);
                var C = T.localNSMap
                  , A = T.tagName == b
                  , S = A || T.tagName && T.tagName.toLowerCase() == b.toLowerCase();
                if (S) {
                    if (r.endElement(T.uri, T.localName, b),
                    C)
                        for (var P in C)
                            r.endPrefixMapping(P);
                    A || n.fatalError("end tag name: " + b + " is not match the current start tagName:" + T.tagName)
                } else
                    d.push(T);
                x++;
                break;
            case "?":
                f && l(m),
                x = parseInstruction(i, m, r);
                break;
            case "!":
                f && l(m),
                x = parseDCC(i, m, r, n);
                break;
            default:
                f && l(m);
                var R = new ElementAttributes
                  , M = d[d.length - 1].currentNSMap
                  , x = parseElementStartPart(i, m, R, M, a, n)
                  , I = R.length;
                if (!R.closed && fixSelfClosed(i, x, R.tagName, _) && (R.closed = !0,
                t.nbsp || n.warning("unclosed xml attribute")),
                f && I) {
                    for (var w = copyLocator(f, {}), O = 0; O < I; O++) {
                        var D = R[O];
                        l(D.offset),
                        D.locator = copyLocator(f, {})
                    }
                    r.locator = w,
                    appendElement$1(R, r, M) && d.push(R),
                    r.locator = f
                } else
                    appendElement$1(R, r, M) && d.push(R);
                R.uri === "http://www.w3.org/1999/xhtml" && !R.closed ? x = parseHtmlSpecialContent(i, x, R.tagName, a, r) : x++
            }
        } catch (F) {
            n.error("element parse error: " + F),
            x = -1
        }
        x > g ? g = x : s(Math.max(m, g) + 1)
    }
}
function copyLocator(i, e) {
    return e.lineNumber = i.lineNumber,
    e.columnNumber = i.columnNumber,
    e
}
function parseElementStartPart(i, e, t, r, n, o) {
    for (var a, s, l = ++e, u = S_TAG; ; ) {
        var c = i.charAt(l);
        switch (c) {
        case "=":
            if (u === S_ATTR)
                a = i.slice(e, l),
                u = S_EQ;
            else if (u === S_ATTR_SPACE)
                u = S_EQ;
            else
                throw new Error("attribute equal must after attrName");
            break;
        case "'":
        case '"':
            if (u === S_EQ || u === S_ATTR)
                if (u === S_ATTR && (o.warning('attribute value must after "="'),
                a = i.slice(e, l)),
                e = l + 1,
                l = i.indexOf(c, e),
                l > 0)
                    s = i.slice(e, l).replace(/&#?\w+;/g, n),
                    t.add(a, s, e - 1),
                    u = S_ATTR_END;
                else
                    throw new Error("attribute value no end '" + c + "' match");
            else if (u == S_ATTR_NOQUOT_VALUE)
                s = i.slice(e, l).replace(/&#?\w+;/g, n),
                t.add(a, s, e),
                o.warning('attribute "' + a + '" missed start quot(' + c + ")!!"),
                e = l + 1,
                u = S_ATTR_END;
            else
                throw new Error('attribute value must after "="');
            break;
        case "/":
            switch (u) {
            case S_TAG:
                t.setTagName(i.slice(e, l));
            case S_ATTR_END:
            case S_TAG_SPACE:
            case S_TAG_CLOSE:
                u = S_TAG_CLOSE,
                t.closed = !0;
            case S_ATTR_NOQUOT_VALUE:
            case S_ATTR:
            case S_ATTR_SPACE:
                break;
            default:
                throw new Error("attribute invalid close char('/')")
            }
            break;
        case "":
            return o.error("unexpected end of input"),
            u == S_TAG && t.setTagName(i.slice(e, l)),
            l;
        case ">":
            switch (u) {
            case S_TAG:
                t.setTagName(i.slice(e, l));
            case S_ATTR_END:
            case S_TAG_SPACE:
            case S_TAG_CLOSE:
                break;
            case S_ATTR_NOQUOT_VALUE:
            case S_ATTR:
                s = i.slice(e, l),
                s.slice(-1) === "/" && (t.closed = !0,
                s = s.slice(0, -1));
            case S_ATTR_SPACE:
                u === S_ATTR_SPACE && (s = a),
                u == S_ATTR_NOQUOT_VALUE ? (o.warning('attribute "' + s + '" missed quot(")!!'),
                t.add(a, s.replace(/&#?\w+;/g, n), e)) : ((r[""] !== "http://www.w3.org/1999/xhtml" || !s.match(/^(?:disabled|checked|selected)$/i)) && o.warning('attribute "' + s + '" missed value!! "' + s + '" instead!!'),
                t.add(s, s, e));
                break;
            case S_EQ:
                throw new Error("attribute value missed!!")
            }
            return l;
        case "\x80":
            c = " ";
        default:
            if (c <= " ")
                switch (u) {
                case S_TAG:
                    t.setTagName(i.slice(e, l)),
                    u = S_TAG_SPACE;
                    break;
                case S_ATTR:
                    a = i.slice(e, l),
                    u = S_ATTR_SPACE;
                    break;
                case S_ATTR_NOQUOT_VALUE:
                    var s = i.slice(e, l).replace(/&#?\w+;/g, n);
                    o.warning('attribute "' + s + '" missed quot(")!!'),
                    t.add(a, s, e);
                case S_ATTR_END:
                    u = S_TAG_SPACE;
                    break
                }
            else
                switch (u) {
                case S_ATTR_SPACE:
                    t.tagName,
                    (r[""] !== "http://www.w3.org/1999/xhtml" || !a.match(/^(?:disabled|checked|selected)$/i)) && o.warning('attribute "' + a + '" missed value!! "' + a + '" instead2!!'),
                    t.add(a, a, e),
                    e = l,
                    u = S_ATTR;
                    break;
                case S_ATTR_END:
                    o.warning('attribute space is required"' + a + '"!!');
                case S_TAG_SPACE:
                    u = S_ATTR,
                    e = l;
                    break;
                case S_EQ:
                    u = S_ATTR_NOQUOT_VALUE,
                    e = l;
                    break;
                case S_TAG_CLOSE:
                    throw new Error("elements closed character '/' and '>' must be connected to")
                }
        }
        l++
    }
}
function appendElement$1(i, e, t) {
    for (var r = i.tagName, n = null, h = i.length; h--; ) {
        var o = i[h]
          , a = o.qName
          , s = o.value
          , f = a.indexOf(":");
        if (f > 0)
            var l = o.prefix = a.slice(0, f)
              , u = a.slice(f + 1)
              , c = l === "xmlns" && u;
        else
            u = a,
            l = null,
            c = a === "xmlns" && "";
        o.localName = u,
        c !== !1 && (n == null && (n = {},
        _copy(t, t = {})),
        t[c] = n[c] = s,
        o.uri = "http://www.w3.org/2000/xmlns/",
        e.startPrefixMapping(c, s))
    }
    for (var h = i.length; h--; ) {
        o = i[h];
        var l = o.prefix;
        l && (l === "xml" && (o.uri = "http://www.w3.org/XML/1998/namespace"),
        l !== "xmlns" && (o.uri = t[l || ""]))
    }
    var f = r.indexOf(":");
    f > 0 ? (l = i.prefix = r.slice(0, f),
    u = i.localName = r.slice(f + 1)) : (l = null,
    u = i.localName = r);
    var d = i.uri = t[l || ""];
    if (e.startElement(d, u, r, i),
    i.closed) {
        if (e.endElement(d, u, r),
        n)
            for (l in n)
                e.endPrefixMapping(l)
    } else
        return i.currentNSMap = t,
        i.localNSMap = n,
        !0
}
function parseHtmlSpecialContent(i, e, t, r, n) {
    if (/^(?:script|textarea)$/i.test(t)) {
        var o = i.indexOf("</" + t + ">", e)
          , a = i.substring(e + 1, o);
        if (/[&<]/.test(a))
            return /^script$/i.test(t) ? (n.characters(a, 0, a.length),
            o) : (a = a.replace(/&#?\w+;/g, r),
            n.characters(a, 0, a.length),
            o)
    }
    return e + 1
}
function fixSelfClosed(i, e, t, r) {
    var n = r[t];
    return n == null && (n = i.lastIndexOf("</" + t + ">"),
    n < e && (n = i.lastIndexOf("</" + t)),
    r[t] = n),
    n < e
}
function _copy(i, e) {
    for (var t in i)
        e[t] = i[t]
}
function parseDCC(i, e, t, r) {
    var n = i.charAt(e + 2);
    switch (n) {
    case "-":
        if (i.charAt(e + 3) === "-") {
            var o = i.indexOf("-->", e + 4);
            return o > e ? (t.comment(i, e + 4, o - e - 4),
            o + 3) : (r.error("Unclosed comment"),
            -1)
        } else
            return -1;
    default:
        if (i.substr(e + 3, 6) == "CDATA[") {
            var o = i.indexOf("]]>", e + 9);
            return t.startCDATA(),
            t.characters(i, e + 9, o - e - 9),
            t.endCDATA(),
            o + 3
        }
        var a = split(i, e)
          , s = a.length;
        if (s > 1 && /!doctype/i.test(a[0][0])) {
            var l = a[1][0]
              , u = s > 3 && /^public$/i.test(a[2][0]) && a[3][0]
              , c = s > 4 && a[4][0]
              , h = a[s - 1];
            return t.startDTD(l, u && u.replace(/^(['"])(.*?)\1$/, "$2"), c && c.replace(/^(['"])(.*?)\1$/, "$2")),
            t.endDTD(),
            h.index + h[0].length
        }
    }
    return -1
}
function parseInstruction(i, e, t) {
    var r = i.indexOf("?>", e);
    if (r) {
        var n = i.substring(e, r).match(/^<\?(\S*)\s*([\s\S]*?)\s*$/);
        return n ? (n[0].length,
        t.processingInstruction(n[1], n[2]),
        r + 2) : -1
    }
    return -1
}
function ElementAttributes(i) {}
ElementAttributes.prototype = {
    setTagName: function(i) {
        if (!tagNamePattern.test(i))
            throw new Error("invalid tagName:" + i);
        this.tagName = i
    },
    add: function(i, e, t) {
        if (!tagNamePattern.test(i))
            throw new Error("invalid attribute:" + i);
        this[this.length++] = {
            qName: i,
            value: e,
            offset: t
        }
    },
    length: 0,
    getLocalName: function(i) {
        return this[i].localName
    },
    getLocator: function(i) {
        return this[i].locator
    },
    getQName: function(i) {
        return this[i].qName
    },
    getURI: function(i) {
        return this[i].uri
    },
    getValue: function(i) {
        return this[i].value
    }
};
function _set_proto_(i, e) {
    return i.__proto__ = e,
    i
}
_set_proto_({}, _set_proto_.prototype)instanceof _set_proto_ || (_set_proto_ = function(i, e) {
    function t() {}
    t.prototype = e,
    t = new t;
    for (e in i)
        t[e] = i[e];
    return t
}
);
function split(i, e) {
    var t, r = [], n = /'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;
    for (n.lastIndex = e,
    n.exec(i); t = n.exec(i); )
        if (r.push(t),
        t[1])
            return r
}
sax.XMLReader = XMLReader$1;
var dom = {};
function copy(i, e) {
    for (var t in i)
        e[t] = i[t]
}
function _extends(i, e) {
    var t = i.prototype;
    if (Object.create) {
        var r = Object.create(e.prototype);
        t.__proto__ = r
    }
    if (!(t instanceof e)) {
        let n = function() {};
        n.prototype = e.prototype,
        n = new n,
        copy(t, n),
        i.prototype = t = n
    }
    t.constructor != i && (typeof i != "function" && console.error("unknow Class:" + i),
    t.constructor = i)
}
var htmlns = "http://www.w3.org/1999/xhtml"
  , NodeType = {}
  , ELEMENT_NODE = NodeType.ELEMENT_NODE = 1
  , ATTRIBUTE_NODE = NodeType.ATTRIBUTE_NODE = 2
  , TEXT_NODE = NodeType.TEXT_NODE = 3
  , CDATA_SECTION_NODE = NodeType.CDATA_SECTION_NODE = 4
  , ENTITY_REFERENCE_NODE = NodeType.ENTITY_REFERENCE_NODE = 5
  , ENTITY_NODE = NodeType.ENTITY_NODE = 6
  , PROCESSING_INSTRUCTION_NODE = NodeType.PROCESSING_INSTRUCTION_NODE = 7
  , COMMENT_NODE = NodeType.COMMENT_NODE = 8
  , DOCUMENT_NODE = NodeType.DOCUMENT_NODE = 9
  , DOCUMENT_TYPE_NODE = NodeType.DOCUMENT_TYPE_NODE = 10
  , DOCUMENT_FRAGMENT_NODE = NodeType.DOCUMENT_FRAGMENT_NODE = 11
  , NOTATION_NODE = NodeType.NOTATION_NODE = 12
  , ExceptionCode = {}
  , ExceptionMessage = {};
ExceptionCode.INDEX_SIZE_ERR = (ExceptionMessage[1] = "Index size error",
1);
ExceptionCode.DOMSTRING_SIZE_ERR = (ExceptionMessage[2] = "DOMString size error",
2);
var HIERARCHY_REQUEST_ERR = ExceptionCode.HIERARCHY_REQUEST_ERR = (ExceptionMessage[3] = "Hierarchy request error",
3);
ExceptionCode.WRONG_DOCUMENT_ERR = (ExceptionMessage[4] = "Wrong document",
4);
ExceptionCode.INVALID_CHARACTER_ERR = (ExceptionMessage[5] = "Invalid character",
5);
ExceptionCode.NO_DATA_ALLOWED_ERR = (ExceptionMessage[6] = "No data allowed",
6);
ExceptionCode.NO_MODIFICATION_ALLOWED_ERR = (ExceptionMessage[7] = "No modification allowed",
7);
var NOT_FOUND_ERR = ExceptionCode.NOT_FOUND_ERR = (ExceptionMessage[8] = "Not found",
8);
ExceptionCode.NOT_SUPPORTED_ERR = (ExceptionMessage[9] = "Not supported",
9);
var INUSE_ATTRIBUTE_ERR = ExceptionCode.INUSE_ATTRIBUTE_ERR = (ExceptionMessage[10] = "Attribute in use",
10);
ExceptionCode.INVALID_STATE_ERR = (ExceptionMessage[11] = "Invalid state",
11);
ExceptionCode.SYNTAX_ERR = (ExceptionMessage[12] = "Syntax error",
12);
ExceptionCode.INVALID_MODIFICATION_ERR = (ExceptionMessage[13] = "Invalid modification",
13);
ExceptionCode.NAMESPACE_ERR = (ExceptionMessage[14] = "Invalid namespace",
14);
ExceptionCode.INVALID_ACCESS_ERR = (ExceptionMessage[15] = "Invalid access",
15);
function DOMException(i, e) {
    if (e instanceof Error)
        var t = e;
    else
        t = this,
        Error.call(this, ExceptionMessage[i]),
        this.message = ExceptionMessage[i],
        Error.captureStackTrace && Error.captureStackTrace(this, DOMException);
    return t.code = i,
    e && (this.message = this.message + ": " + e),
    t
}
DOMException.prototype = Error.prototype;
copy(ExceptionCode, DOMException);
function NodeList() {}
NodeList.prototype = {
    length: 0,
    item: function(i) {
        return this[i] || null
    },
    toString: function(i, e) {
        for (var t = [], r = 0; r < this.length; r++)
            serializeToString(this[r], t, i, e);
        return t.join("")
    }
};
function LiveNodeList(i, e) {
    this._node = i,
    this._refresh = e,
    _updateLiveList(this)
}
function _updateLiveList(i) {
    var e = i._node._inc || i._node.ownerDocument._inc;
    if (i._inc != e) {
        var t = i._refresh(i._node);
        __set__(i, "length", t.length),
        copy(t, i),
        i._inc = e
    }
}
LiveNodeList.prototype.item = function(i) {
    return _updateLiveList(this),
    this[i]
}
;
_extends(LiveNodeList, NodeList);
function NamedNodeMap() {}
function _findNodeIndex(i, e) {
    for (var t = i.length; t--; )
        if (i[t] === e)
            return t
}
function _addNamedNode(i, e, t, r) {
    if (r ? e[_findNodeIndex(e, r)] = t : e[e.length++] = t,
    i) {
        t.ownerElement = i;
        var n = i.ownerDocument;
        n && (r && _onRemoveAttribute(n, i, r),
        _onAddAttribute(n, i, t))
    }
}
function _removeNamedNode(i, e, t) {
    var r = _findNodeIndex(e, t);
    if (r >= 0) {
        for (var n = e.length - 1; r < n; )
            e[r] = e[++r];
        if (e.length = n,
        i) {
            var o = i.ownerDocument;
            o && (_onRemoveAttribute(o, i, t),
            t.ownerElement = null)
        }
    } else
        throw DOMException(NOT_FOUND_ERR, new Error(i.tagName + "@" + t))
}
NamedNodeMap.prototype = {
    length: 0,
    item: NodeList.prototype.item,
    getNamedItem: function(i) {
        for (var e = this.length; e--; ) {
            var t = this[e];
            if (t.nodeName == i)
                return t
        }
    },
    setNamedItem: function(i) {
        var e = i.ownerElement;
        if (e && e != this._ownerElement)
            throw new DOMException(INUSE_ATTRIBUTE_ERR);
        var t = this.getNamedItem(i.nodeName);
        return _addNamedNode(this._ownerElement, this, i, t),
        t
    },
    setNamedItemNS: function(i) {
        var e = i.ownerElement, t;
        if (e && e != this._ownerElement)
            throw new DOMException(INUSE_ATTRIBUTE_ERR);
        return t = this.getNamedItemNS(i.namespaceURI, i.localName),
        _addNamedNode(this._ownerElement, this, i, t),
        t
    },
    removeNamedItem: function(i) {
        var e = this.getNamedItem(i);
        return _removeNamedNode(this._ownerElement, this, e),
        e
    },
    removeNamedItemNS: function(i, e) {
        var t = this.getNamedItemNS(i, e);
        return _removeNamedNode(this._ownerElement, this, t),
        t
    },
    getNamedItemNS: function(i, e) {
        for (var t = this.length; t--; ) {
            var r = this[t];
            if (r.localName == e && r.namespaceURI == i)
                return r
        }
        return null
    }
};
function DOMImplementation$1(i) {
    if (this._features = {},
    i)
        for (var e in i)
            this._features = i[e]
}
DOMImplementation$1.prototype = {
    hasFeature: function(i, e) {
        var t = this._features[i.toLowerCase()];
        return !!(t && (!e || e in t))
    },
    createDocument: function(i, e, t) {
        var r = new Document;
        if (r.implementation = this,
        r.childNodes = new NodeList,
        r.doctype = t,
        t && r.appendChild(t),
        e) {
            var n = r.createElementNS(i, e);
            r.appendChild(n)
        }
        return r
    },
    createDocumentType: function(i, e, t) {
        var r = new DocumentType;
        return r.name = i,
        r.nodeName = i,
        r.publicId = e,
        r.systemId = t,
        r
    }
};
function Node$1() {}
Node$1.prototype = {
    firstChild: null,
    lastChild: null,
    previousSibling: null,
    nextSibling: null,
    attributes: null,
    parentNode: null,
    childNodes: null,
    ownerDocument: null,
    nodeValue: null,
    namespaceURI: null,
    prefix: null,
    localName: null,
    insertBefore: function(i, e) {
        return _insertBefore(this, i, e)
    },
    replaceChild: function(i, e) {
        this.insertBefore(i, e),
        e && this.removeChild(e)
    },
    removeChild: function(i) {
        return _removeChild(this, i)
    },
    appendChild: function(i) {
        return this.insertBefore(i, null)
    },
    hasChildNodes: function() {
        return this.firstChild != null
    },
    cloneNode: function(i) {
        return cloneNode(this.ownerDocument || this, this, i)
    },
    normalize: function() {
        for (var i = this.firstChild; i; ) {
            var e = i.nextSibling;
            e && e.nodeType == TEXT_NODE && i.nodeType == TEXT_NODE ? (this.removeChild(e),
            i.appendData(e.data)) : (i.normalize(),
            i = e)
        }
    },
    isSupported: function(i, e) {
        return this.ownerDocument.implementation.hasFeature(i, e)
    },
    hasAttributes: function() {
        return this.attributes.length > 0
    },
    lookupPrefix: function(i) {
        for (var e = this; e; ) {
            var t = e._nsMap;
            if (t) {
                for (var r in t)
                    if (t[r] == i)
                        return r
            }
            e = e.nodeType == ATTRIBUTE_NODE ? e.ownerDocument : e.parentNode
        }
        return null
    },
    lookupNamespaceURI: function(i) {
        for (var e = this; e; ) {
            var t = e._nsMap;
            if (t && i in t)
                return t[i];
            e = e.nodeType == ATTRIBUTE_NODE ? e.ownerDocument : e.parentNode
        }
        return null
    },
    isDefaultNamespace: function(i) {
        var e = this.lookupPrefix(i);
        return e == null
    }
};
function _xmlEncoder(i) {
    return i == "<" && "&lt;" || i == ">" && "&gt;" || i == "&" && "&amp;" || i == '"' && "&quot;" || "&#" + i.charCodeAt() + ";"
}
copy(NodeType, Node$1);
copy(NodeType, Node$1.prototype);
function _visitNode(i, e) {
    if (e(i))
        return !0;
    if (i = i.firstChild)
        do
            if (_visitNode(i, e))
                return !0;
        while (i = i.nextSibling)
}
function Document() {}
function _onAddAttribute(i, e, t) {
    i && i._inc++;
    var r = t.namespaceURI;
    r == "http://www.w3.org/2000/xmlns/" && (e._nsMap[t.prefix ? t.localName : ""] = t.value)
}
function _onRemoveAttribute(i, e, t, r) {
    i && i._inc++;
    var n = t.namespaceURI;
    n == "http://www.w3.org/2000/xmlns/" && delete e._nsMap[t.prefix ? t.localName : ""]
}
function _onUpdateChild(i, e, t) {
    if (i && i._inc) {
        i._inc++;
        var r = e.childNodes;
        if (t)
            r[r.length++] = t;
        else {
            for (var n = e.firstChild, o = 0; n; )
                r[o++] = n,
                n = n.nextSibling;
            r.length = o
        }
    }
}
function _removeChild(i, e) {
    var t = e.previousSibling
      , r = e.nextSibling;
    return t ? t.nextSibling = r : i.firstChild = r,
    r ? r.previousSibling = t : i.lastChild = t,
    _onUpdateChild(i.ownerDocument, i),
    e
}
function _insertBefore(i, e, t) {
    var r = e.parentNode;
    if (r && r.removeChild(e),
    e.nodeType === DOCUMENT_FRAGMENT_NODE) {
        var n = e.firstChild;
        if (n == null)
            return e;
        var o = e.lastChild
    } else
        n = o = e;
    var a = t ? t.previousSibling : i.lastChild;
    n.previousSibling = a,
    o.nextSibling = t,
    a ? a.nextSibling = n : i.firstChild = n,
    t == null ? i.lastChild = o : t.previousSibling = o;
    do
        n.parentNode = i;
    while (n !== o && (n = n.nextSibling));
    return _onUpdateChild(i.ownerDocument || i, i),
    e.nodeType == DOCUMENT_FRAGMENT_NODE && (e.firstChild = e.lastChild = null),
    e
}
function _appendSingleChild(i, e) {
    var t = e.parentNode;
    if (t) {
        var r = i.lastChild;
        t.removeChild(e);
        var r = i.lastChild
    }
    var r = i.lastChild;
    return e.parentNode = i,
    e.previousSibling = r,
    e.nextSibling = null,
    r ? r.nextSibling = e : i.firstChild = e,
    i.lastChild = e,
    _onUpdateChild(i.ownerDocument, i, e),
    e
}
Document.prototype = {
    nodeName: "#document",
    nodeType: DOCUMENT_NODE,
    doctype: null,
    documentElement: null,
    _inc: 1,
    insertBefore: function(i, e) {
        if (i.nodeType == DOCUMENT_FRAGMENT_NODE) {
            for (var t = i.firstChild; t; ) {
                var r = t.nextSibling;
                this.insertBefore(t, e),
                t = r
            }
            return i
        }
        return this.documentElement == null && i.nodeType == ELEMENT_NODE && (this.documentElement = i),
        _insertBefore(this, i, e),
        i.ownerDocument = this,
        i
    },
    removeChild: function(i) {
        return this.documentElement == i && (this.documentElement = null),
        _removeChild(this, i)
    },
    importNode: function(i, e) {
        return importNode(this, i, e)
    },
    getElementById: function(i) {
        var e = null;
        return _visitNode(this.documentElement, function(t) {
            if (t.nodeType == ELEMENT_NODE && t.getAttribute("id") == i)
                return e = t,
                !0
        }),
        e
    },
    createElement: function(i) {
        var e = new Element;
        e.ownerDocument = this,
        e.nodeName = i,
        e.tagName = i,
        e.childNodes = new NodeList;
        var t = e.attributes = new NamedNodeMap;
        return t._ownerElement = e,
        e
    },
    createDocumentFragment: function() {
        var i = new DocumentFragment;
        return i.ownerDocument = this,
        i.childNodes = new NodeList,
        i
    },
    createTextNode: function(i) {
        var e = new Text;
        return e.ownerDocument = this,
        e.appendData(i),
        e
    },
    createComment: function(i) {
        var e = new Comment;
        return e.ownerDocument = this,
        e.appendData(i),
        e
    },
    createCDATASection: function(i) {
        var e = new CDATASection;
        return e.ownerDocument = this,
        e.appendData(i),
        e
    },
    createProcessingInstruction: function(i, e) {
        var t = new ProcessingInstruction;
        return t.ownerDocument = this,
        t.tagName = t.target = i,
        t.nodeValue = t.data = e,
        t
    },
    createAttribute: function(i) {
        var e = new Attr;
        return e.ownerDocument = this,
        e.name = i,
        e.nodeName = i,
        e.localName = i,
        e.specified = !0,
        e
    },
    createEntityReference: function(i) {
        var e = new EntityReference;
        return e.ownerDocument = this,
        e.nodeName = i,
        e
    },
    createElementNS: function(i, e) {
        var t = new Element
          , r = e.split(":")
          , n = t.attributes = new NamedNodeMap;
        return t.childNodes = new NodeList,
        t.ownerDocument = this,
        t.nodeName = e,
        t.tagName = e,
        t.namespaceURI = i,
        r.length == 2 ? (t.prefix = r[0],
        t.localName = r[1]) : t.localName = e,
        n._ownerElement = t,
        t
    },
    createAttributeNS: function(i, e) {
        var t = new Attr
          , r = e.split(":");
        return t.ownerDocument = this,
        t.nodeName = e,
        t.name = e,
        t.namespaceURI = i,
        t.specified = !0,
        r.length == 2 ? (t.prefix = r[0],
        t.localName = r[1]) : t.localName = e,
        t
    }
};
_extends(Document, Node$1);
function Element() {
    this._nsMap = {}
}
Element.prototype = {
    nodeType: ELEMENT_NODE,
    hasAttribute: function(i) {
        return this.getAttributeNode(i) != null
    },
    getAttribute: function(i) {
        var e = this.getAttributeNode(i);
        return e && e.value || ""
    },
    getAttributeNode: function(i) {
        return this.attributes.getNamedItem(i)
    },
    setAttribute: function(i, e) {
        var t = this.ownerDocument.createAttribute(i);
        t.value = t.nodeValue = "" + e,
        this.setAttributeNode(t)
    },
    removeAttribute: function(i) {
        var e = this.getAttributeNode(i);
        e && this.removeAttributeNode(e)
    },
    appendChild: function(i) {
        return i.nodeType === DOCUMENT_FRAGMENT_NODE ? this.insertBefore(i, null) : _appendSingleChild(this, i)
    },
    setAttributeNode: function(i) {
        return this.attributes.setNamedItem(i)
    },
    setAttributeNodeNS: function(i) {
        return this.attributes.setNamedItemNS(i)
    },
    removeAttributeNode: function(i) {
        return this.attributes.removeNamedItem(i.nodeName)
    },
    removeAttributeNS: function(i, e) {
        var t = this.getAttributeNodeNS(i, e);
        t && this.removeAttributeNode(t)
    },
    hasAttributeNS: function(i, e) {
        return this.getAttributeNodeNS(i, e) != null
    },
    getAttributeNS: function(i, e) {
        var t = this.getAttributeNodeNS(i, e);
        return t && t.value || ""
    },
    setAttributeNS: function(i, e, t) {
        var r = this.ownerDocument.createAttributeNS(i, e);
        r.value = r.nodeValue = "" + t,
        this.setAttributeNode(r)
    },
    getAttributeNodeNS: function(i, e) {
        return this.attributes.getNamedItemNS(i, e)
    },
    getElementsByTagName: function(i) {
        return new LiveNodeList(this,function(e) {
            var t = [];
            return _visitNode(e, function(r) {
                r !== e && r.nodeType == ELEMENT_NODE && (i === "*" || r.tagName == i) && t.push(r)
            }),
            t
        }
        )
    },
    getElementsByTagNameNS: function(i, e) {
        return new LiveNodeList(this,function(t) {
            var r = [];
            return _visitNode(t, function(n) {
                n !== t && n.nodeType === ELEMENT_NODE && (i === "*" || n.namespaceURI === i) && (e === "*" || n.localName == e) && r.push(n)
            }),
            r
        }
        )
    }
};
Document.prototype.getElementsByTagName = Element.prototype.getElementsByTagName;
Document.prototype.getElementsByTagNameNS = Element.prototype.getElementsByTagNameNS;
_extends(Element, Node$1);
function Attr() {}
Attr.prototype.nodeType = ATTRIBUTE_NODE;
_extends(Attr, Node$1);
function CharacterData() {}
CharacterData.prototype = {
    data: "",
    substringData: function(i, e) {
        return this.data.substring(i, i + e)
    },
    appendData: function(i) {
        i = this.data + i,
        this.nodeValue = this.data = i,
        this.length = i.length
    },
    insertData: function(i, e) {
        this.replaceData(i, 0, e)
    },
    appendChild: function(i) {
        throw new Error(ExceptionMessage[HIERARCHY_REQUEST_ERR])
    },
    deleteData: function(i, e) {
        this.replaceData(i, e, "")
    },
    replaceData: function(i, e, t) {
        var r = this.data.substring(0, i)
          , n = this.data.substring(i + e);
        t = r + t + n,
        this.nodeValue = this.data = t,
        this.length = t.length
    }
};
_extends(CharacterData, Node$1);
function Text() {}
Text.prototype = {
    nodeName: "#text",
    nodeType: TEXT_NODE,
    splitText: function(i) {
        var e = this.data
          , t = e.substring(i);
        e = e.substring(0, i),
        this.data = this.nodeValue = e,
        this.length = e.length;
        var r = this.ownerDocument.createTextNode(t);
        return this.parentNode && this.parentNode.insertBefore(r, this.nextSibling),
        r
    }
};
_extends(Text, CharacterData);
function Comment() {}
Comment.prototype = {
    nodeName: "#comment",
    nodeType: COMMENT_NODE
};
_extends(Comment, CharacterData);
function CDATASection() {}
CDATASection.prototype = {
    nodeName: "#cdata-section",
    nodeType: CDATA_SECTION_NODE
};
_extends(CDATASection, CharacterData);
function DocumentType() {}
DocumentType.prototype.nodeType = DOCUMENT_TYPE_NODE;
_extends(DocumentType, Node$1);
function Notation() {}
Notation.prototype.nodeType = NOTATION_NODE;
_extends(Notation, Node$1);
function Entity() {}
Entity.prototype.nodeType = ENTITY_NODE;
_extends(Entity, Node$1);
function EntityReference() {}
EntityReference.prototype.nodeType = ENTITY_REFERENCE_NODE;
_extends(EntityReference, Node$1);
function DocumentFragment() {}
DocumentFragment.prototype.nodeName = "#document-fragment";
DocumentFragment.prototype.nodeType = DOCUMENT_FRAGMENT_NODE;
_extends(DocumentFragment, Node$1);
function ProcessingInstruction() {}
ProcessingInstruction.prototype.nodeType = PROCESSING_INSTRUCTION_NODE;
_extends(ProcessingInstruction, Node$1);
function XMLSerializer$1() {}
XMLSerializer$1.prototype.serializeToString = function(i, e, t) {
    return nodeSerializeToString.call(i, e, t)
}
;
Node$1.prototype.toString = nodeSerializeToString;
function nodeSerializeToString(i, e) {
    var t = []
      , r = this.nodeType == 9 ? this.documentElement : this
      , n = r.prefix
      , o = r.namespaceURI;
    if (o && n == null) {
        var n = r.lookupPrefix(o);
        if (n == null)
            var a = [{
                namespace: o,
                prefix: null
            }]
    }
    return serializeToString(this, t, i, e, a),
    t.join("")
}
function needNamespaceDefine(i, e, t) {
    var r = i.prefix || ""
      , n = i.namespaceURI;
    if (!r && !n || r === "xml" && n === "http://www.w3.org/XML/1998/namespace" || n == "http://www.w3.org/2000/xmlns/")
        return !1;
    for (var o = t.length; o--; ) {
        var a = t[o];
        if (a.prefix == r)
            return a.namespace != n
    }
    return !0
}
function serializeToString(i, e, t, r, n) {
    if (r)
        if (i = r(i),
        i) {
            if (typeof i == "string") {
                e.push(i);
                return
            }
        } else
            return;
    switch (i.nodeType) {
    case ELEMENT_NODE:
        n || (n = []),
        n.length;
        var o = i.attributes
          , a = o.length
          , d = i.firstChild
          , s = i.tagName;
        t = htmlns === i.namespaceURI || t,
        e.push("<", s);
        for (var l = 0; l < a; l++) {
            var u = o.item(l);
            u.prefix == "xmlns" ? n.push({
                prefix: u.localName,
                namespace: u.value
            }) : u.nodeName == "xmlns" && n.push({
                prefix: "",
                namespace: u.value
            })
        }
        for (var l = 0; l < a; l++) {
            var u = o.item(l);
            if (needNamespaceDefine(u, t, n)) {
                var c = u.prefix || ""
                  , h = u.namespaceURI
                  , f = c ? " xmlns:" + c : " xmlns";
                e.push(f, '="', h, '"'),
                n.push({
                    prefix: c,
                    namespace: h
                })
            }
            serializeToString(u, e, t, r, n)
        }
        if (needNamespaceDefine(i, t, n)) {
            var c = i.prefix || ""
              , h = i.namespaceURI
              , f = c ? " xmlns:" + c : " xmlns";
            e.push(f, '="', h, '"'),
            n.push({
                prefix: c,
                namespace: h
            })
        }
        if (d || t && !/^(?:meta|link|img|br|hr|input)$/i.test(s)) {
            if (e.push(">"),
            t && /^script$/i.test(s))
                for (; d; )
                    d.data ? e.push(d.data) : serializeToString(d, e, t, r, n),
                    d = d.nextSibling;
            else
                for (; d; )
                    serializeToString(d, e, t, r, n),
                    d = d.nextSibling;
            e.push("</", s, ">")
        } else
            e.push("/>");
        return;
    case DOCUMENT_NODE:
    case DOCUMENT_FRAGMENT_NODE:
        for (var d = i.firstChild; d; )
            serializeToString(d, e, t, r, n),
            d = d.nextSibling;
        return;
    case ATTRIBUTE_NODE:
        return e.push(" ", i.name, '="', i.value.replace(/[<&"]/g, _xmlEncoder), '"');
    case TEXT_NODE:
        return e.push(i.data.replace(/[<&]/g, _xmlEncoder));
    case CDATA_SECTION_NODE:
        return e.push("<![CDATA[", i.data, "]]>");
    case COMMENT_NODE:
        return e.push("<!--", i.data, "-->");
    case DOCUMENT_TYPE_NODE:
        var _ = i.publicId
          , g = i.systemId;
        if (e.push("<!DOCTYPE ", i.name),
        _)
            e.push(' PUBLIC "', _),
            g && g != "." && e.push('" "', g),
            e.push('">');
        else if (g && g != ".")
            e.push(' SYSTEM "', g, '">');
        else {
            var m = i.internalSubset;
            m && e.push(" [", m, "]"),
            e.push(">")
        }
        return;
    case PROCESSING_INSTRUCTION_NODE:
        return e.push("<?", i.target, " ", i.data, "?>");
    case ENTITY_REFERENCE_NODE:
        return e.push("&", i.nodeName, ";");
    default:
        e.push("??", i.nodeName)
    }
}
function importNode(i, e, t) {
    var r;
    switch (e.nodeType) {
    case ELEMENT_NODE:
        r = e.cloneNode(!1),
        r.ownerDocument = i;
    case DOCUMENT_FRAGMENT_NODE:
        break;
    case ATTRIBUTE_NODE:
        t = !0;
        break
    }
    if (r || (r = e.cloneNode(!1)),
    r.ownerDocument = i,
    r.parentNode = null,
    t)
        for (var n = e.firstChild; n; )
            r.appendChild(importNode(i, n, t)),
            n = n.nextSibling;
    return r
}
function cloneNode(i, e, t) {
    var r = new e.constructor;
    for (var n in e) {
        var o = e[n];
        typeof o != "object" && o != r[n] && (r[n] = o)
    }
    switch (e.childNodes && (r.childNodes = new NodeList),
    r.ownerDocument = i,
    r.nodeType) {
    case ELEMENT_NODE:
        var a = e.attributes
          , s = r.attributes = new NamedNodeMap
          , l = a.length;
        s._ownerElement = r;
        for (var u = 0; u < l; u++)
            r.setAttributeNode(cloneNode(i, a.item(u), !0));
        break;
    case ATTRIBUTE_NODE:
        t = !0
    }
    if (t)
        for (var c = e.firstChild; c; )
            r.appendChild(cloneNode(i, c, t)),
            c = c.nextSibling;
    return r
}
function __set__(i, e, t) {
    i[e] = t
}
try {
    if (Object.defineProperty) {
        let i = function(e) {
            switch (e.nodeType) {
            case ELEMENT_NODE:
            case DOCUMENT_FRAGMENT_NODE:
                var t = [];
                for (e = e.firstChild; e; )
                    e.nodeType !== 7 && e.nodeType !== 8 && t.push(i(e)),
                    e = e.nextSibling;
                return t.join("");
            default:
                return e.nodeValue
            }
        };
        Object.defineProperty(LiveNodeList.prototype, "length", {
            get: function() {
                return _updateLiveList(this),
                this.$$length
            }
        }),
        Object.defineProperty(Node$1.prototype, "textContent", {
            get: function() {
                return i(this)
            },
            set: function(e) {
                switch (this.nodeType) {
                case ELEMENT_NODE:
                case DOCUMENT_FRAGMENT_NODE:
                    for (; this.firstChild; )
                        this.removeChild(this.firstChild);
                    (e || String(e)) && this.appendChild(this.ownerDocument.createTextNode(e));
                    break;
                default:
                    this.data = e,
                    this.value = e,
                    this.nodeValue = e
                }
            }
        }),
        __set__ = function(e, t, r) {
            e["$$" + t] = r
        }
    }
} catch (i) {}
dom.DOMImplementation = DOMImplementation$1;
dom.XMLSerializer = XMLSerializer$1;
function DOMParser$1(i) {
    this.options = i || {
        locator: {}
    }
}
DOMParser$1.prototype.parseFromString = function(i, e) {
    var t = this.options
      , r = new XMLReader
      , n = t.domBuilder || new DOMHandler
      , o = t.errorHandler
      , a = t.locator
      , s = t.xmlns || {}
      , l = {
        lt: "<",
        gt: ">",
        amp: "&",
        quot: '"',
        apos: "'"
    };
    return a && n.setDocumentLocator(a),
    r.errorHandler = buildErrorHandler(o, n, a),
    r.domBuilder = t.domBuilder || n,
    /\/x?html?$/.test(e) && (l.nbsp = "\xA0",
    l.copy = "\xA9",
    s[""] = "http://www.w3.org/1999/xhtml"),
    s.xml = s.xml || "http://www.w3.org/XML/1998/namespace",
    i ? r.parse(i, s, l) : r.errorHandler.error("invalid doc source"),
    n.doc
}
;
function buildErrorHandler(i, e, t) {
    if (!i) {
        if (e instanceof DOMHandler)
            return e;
        i = e
    }
    var r = {}
      , n = i instanceof Function;
    t = t || {};
    function o(a) {
        var s = i[a];
        !s && n && (s = i.length == 2 ? function(l) {
            i(a, l)
        }
        : i),
        r[a] = s && function(l) {
            s("[xmldom " + a + "]	" + l + _locator(t))
        }
        || function() {}
    }
    return o("warning"),
    o("error"),
    o("fatalError"),
    r
}
function DOMHandler() {
    this.cdata = !1
}
function position(i, e) {
    e.lineNumber = i.lineNumber,
    e.columnNumber = i.columnNumber
}
DOMHandler.prototype = {
    startDocument: function() {
        this.doc = new DOMImplementation().createDocument(null, null, null),
        this.locator && (this.doc.documentURI = this.locator.systemId)
    },
    startElement: function(i, e, t, r) {
        var n = this.doc
          , o = n.createElementNS(i, t || e)
          , a = r.length;
        appendElement(this, o),
        this.currentElement = o,
        this.locator && position(this.locator, o);
        for (var s = 0; s < a; s++) {
            var i = r.getURI(s)
              , l = r.getValue(s)
              , t = r.getQName(s)
              , u = n.createAttributeNS(i, t);
            this.locator && position(r.getLocator(s), u),
            u.value = u.nodeValue = l,
            o.setAttributeNode(u)
        }
    },
    endElement: function(i, e, t) {
        var r = this.currentElement;
        r.tagName,
        this.currentElement = r.parentNode
    },
    startPrefixMapping: function(i, e) {},
    endPrefixMapping: function(i) {},
    processingInstruction: function(i, e) {
        var t = this.doc.createProcessingInstruction(i, e);
        this.locator && position(this.locator, t),
        appendElement(this, t)
    },
    ignorableWhitespace: function(i, e, t) {},
    characters: function(i, e, t) {
        if (i = _toString.apply(this, arguments),
        i) {
            if (this.cdata)
                var r = this.doc.createCDATASection(i);
            else
                var r = this.doc.createTextNode(i);
            this.currentElement ? this.currentElement.appendChild(r) : /^\s*$/.test(i) && this.doc.appendChild(r),
            this.locator && position(this.locator, r)
        }
    },
    skippedEntity: function(i) {},
    endDocument: function() {
        this.doc.normalize()
    },
    setDocumentLocator: function(i) {
        (this.locator = i) && (i.lineNumber = 0)
    },
    comment: function(i, e, t) {
        i = _toString.apply(this, arguments);
        var r = this.doc.createComment(i);
        this.locator && position(this.locator, r),
        appendElement(this, r)
    },
    startCDATA: function() {
        this.cdata = !0
    },
    endCDATA: function() {
        this.cdata = !1
    },
    startDTD: function(i, e, t) {
        var r = this.doc.implementation;
        if (r && r.createDocumentType) {
            var n = r.createDocumentType(i, e, t);
            this.locator && position(this.locator, n),
            appendElement(this, n)
        }
    },
    warning: function(i) {
        console.warn("[xmldom warning]	" + i, _locator(this.locator))
    },
    error: function(i) {
        console.error("[xmldom error]	" + i, _locator(this.locator))
    },
    fatalError: function(i) {
        throw console.error("[xmldom fatalError]	" + i, _locator(this.locator)),
        i
    }
};
function _locator(i) {
    if (i)
        return `
@` + (i.systemId || "") + "#[line:" + i.lineNumber + ",col:" + i.columnNumber + "]"
}
function _toString(i, e, t) {
    return typeof i == "string" ? i.substr(e, t) : i.length >= e + t || e ? new java.lang.String(i,e,t) + "" : i
}
"endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g, function(i) {
    DOMHandler.prototype[i] = function() {
        return null
    }
});
function appendElement(i, e) {
    i.currentElement ? i.currentElement.appendChild(e) : i.doc.appendChild(e)
}
var XMLReader = sax.XMLReader
  , DOMImplementation = domParser.DOMImplementation = dom.DOMImplementation;
domParser.XMLSerializer = dom.XMLSerializer;
domParser.DOMParser = DOMParser$1;
var DOMParser = domParser.DOMParser
  , xmlToJSON = function() {
    this.version = "1.3.5";
    var i = {
        mergeCDATA: !0,
        normalize: !0,
        stripElemPrefix: !0
    }
      , e = new RegExp(/(?!xmlns)^.*:/);
    return this.grokType = function(t) {
        return /^\s*$/.test(t) ? null : /^(?:true|false)$/i.test(t) ? t.toLowerCase() === "true" : isFinite(t) ? parseFloat(t) : t
    }
    ,
    this.parseString = function(t, r) {
        if (t) {
            var n = this.stringToXML(t);
            return n.getElementsByTagName("parsererror").length ? null : this.parseXML(n, r)
        } else
            return null
    }
    ,
    this.parseXML = function(t, r) {
        for (var n in r)
            i[n] = r[n];
        var o = {}
          , a = 0
          , s = ""
          , l = t.childNodes.length;
        if (l)
            for (var u, c, h, f = 0; f < t.childNodes.length; f++)
                u = t.childNodes.item(f),
                u.nodeType === 4 ? i.mergeCDATA && (s += u.nodeValue) : u.nodeType === 3 ? s += u.nodeValue : u.nodeType === 1 && (a === 0 && (o = {}),
                i.stripElemPrefix ? c = u.nodeName.replace(e, "") : c = u.nodeName,
                h = xmlToJSON.parseXML(u),
                o.hasOwnProperty(c) ? (o[c].constructor !== Array && (o[c] = [o[c]]),
                o[c].push(h)) : (o[c] = h,
                a++));
        return Object.keys(o).length || (o = s || ""),
        o
    }
    ,
    this.xmlToString = function(t) {
        try {
            var r = t.xml ? t.xml : new XMLSerializer().serializeToString(t);
            return r
        } catch {
            return null
        }
    }
    ,
    this.stringToXML = function(t) {
        try {
            var r = null;
            if (window.DOMParser) {
                var n = new DOMParser;
                return r = n.parseFromString(t, "text/xml"),
                r
            } else
                return r = new ActiveXObject("Microsoft.XMLDOM"),
                r.async = !1,
                r.loadXML(t),
                r
        } catch {
            return null
        }
    }
    ,
    this
}
.call({})
  , xml2json$1 = function(i) {
    return xmlToJSON.parseString(i)
}
  , xml2json_1 = xml2json$1
  , element_start_char = "a-zA-Z_\xC0-\xD6\xD8-\xF6\xF8-\xFF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FFF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD"
  , element_non_start_char = "-.0-9\xB7\u0300-\u036F\u203F\u2040"
  , element_replace = new RegExp("^([^" + element_start_char + "])|^((x|X)(m|M)(l|L))|([^" + element_start_char + element_non_start_char + "])","g")
  , not_safe_in_xml = /[^\x09\x0A\x0D\x20-\xFF\x85\xA0-\uD7FF\uE000-\uFDCF\uFDE0-\uFFFD]/gm
  , objKeys = function(i) {
    var e = [];
    if (i instanceof Object)
        for (var t in i)
            i.hasOwnProperty(t) && e.push(t);
    return e
}
  , process_to_xml = function(i, e) {
    var t = function(r, n, o, a, s) {
        var l = e.indent !== void 0 ? e.indent : "	"
          , u = e.prettyPrint ? `
` + new Array(a).join(l) : "";
        e.removeIllegalNameCharacters && (r = r.replace(element_replace, "_"));
        var c = [u, "<", r, o || ""];
        return n && n.length > 0 ? (c.push(">"),
        c.push(n),
        s && c.push(u),
        c.push("</"),
        c.push(r),
        c.push(">")) : c.push("/>"),
        c.join("")
    };
    return function r(n, o, a) {
        var s = typeof n;
        switch ((Array.isArray ? Array.isArray(n) : n instanceof Array) ? s = "array" : n instanceof Date && (s = "date"),
        s) {
        case "array":
            var l = [];
            return n.map(function(f) {
                l.push(r(f, 1, a + 1))
            }),
            e.prettyPrint && l.push(`
`),
            l.join("");
        case "date":
            return n.toJSON ? n.toJSON() : n + "";
        case "object":
            var u = [];
            for (var c in n)
                if (n.hasOwnProperty(c))
                    if (n[c]instanceof Array)
                        for (var h = 0; h < n[c].length; h++)
                            n[c].hasOwnProperty(h) && u.push(t(c, r(n[c][h], 0, a + 1), null, a + 1, objKeys(n[c][h]).length));
                    else
                        u.push(t(c, r(n[c], 0, a + 1), null, a + 1));
            return e.prettyPrint && u.length > 0 && u.push(`
`),
            u.join("");
        case "function":
            return n();
        default:
            return e.escape ? esc(n) : "" + n
        }
    }(i, 0, 0)
}
  , xml_header = function(i) {
    var e = ['<?xml version="1.0" encoding="UTF-8"'];
    return i && e.push(' standalone="yes"'),
    e.push("?>"),
    e.join("")
};
function esc(i) {
    return ("" + i).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/'/g, "&apos;").replace(/"/g, "&quot;").replace(not_safe_in_xml, "")
}
var json2xml$1 = function(i, e) {
    if (e || (e = {
        xmlHeader: {
            standalone: !0
        },
        prettyPrint: !0,
        indent: "  ",
        escape: !0
    }),
    typeof i == "string")
        try {
            i = JSON.parse(i.toString())
        } catch {
            return !1
        }
    var t = ""
      , r = "";
    e && (typeof e == "object" ? (e.xmlHeader && (t = xml_header(!!e.xmlHeader.standalone)),
    typeof e.docType != "undefined" && (r = "<!DOCTYPE " + e.docType + ">")) : t = xml_header()),
    e = e || {};
    var n = [t, e.prettyPrint && r ? `
` : "", r, process_to_xml(i, e)];
    return n.join("").replace(/\n{2,}/g, `
`).replace(/\s+$/g, "")
}
  , md5 = md5$1.exports
  , CryptoJS = crypto.exports
  , xml2json = xml2json_1
  , json2xml = json2xml$1;
function camSafeUrlEncode(i) {
    return encodeURIComponent(i).replace(/!/g, "%21").replace(/'/g, "%27").replace(/\(/g, "%28").replace(/\)/g, "%29").replace(/\*/g, "%2A")
}
function getObjectKeys(i, e) {
    var t = [];
    for (var r in i)
        i.hasOwnProperty(r) && t.push(e ? camSafeUrlEncode(r).toLowerCase() : r);
    return t.sort(function(n, o) {
        return n = n.toLowerCase(),
        o = o.toLowerCase(),
        n === o ? 0 : n > o ? 1 : -1
    })
}
var obj2str = function(i, e) {
    var t, r, n, o = [], a = getObjectKeys(i);
    for (t = 0; t < a.length; t++)
        r = a[t],
        n = i[r] === void 0 || i[r] === null ? "" : "" + i[r],
        r = e ? camSafeUrlEncode(r).toLowerCase() : camSafeUrlEncode(r),
        n = camSafeUrlEncode(n) || "",
        o.push(r + "=" + n);
    return o.join("&")
}
  , signHeaders = ["content-disposition", "content-encoding", "content-length", "content-md5", "expect", "host", "if-match", "if-modified-since", "if-none-match", "if-unmodified-since", "origin", "range", "response-cache-control", "response-content-disposition", "response-content-encoding", "response-content-language", "response-content-type", "response-expires", "transfer-encoding", "versionid"]
  , getSignHeaderObj = function(i) {
    var e = {};
    for (var t in i) {
        var r = t.toLowerCase();
        (r.indexOf("x-cos-") > -1 || signHeaders.indexOf(r) > -1) && (e[t] = i[t])
    }
    return e
}
  , getAuth$1 = function(i) {
    i = i || {};
    var e = i.SecretId, t = i.SecretKey, r = i.KeyTime, n = (i.method || i.Method || "get").toLowerCase(), o = clone(i.Query || i.params || {}), a = getSignHeaderObj(clone(i.Headers || i.headers || {})), s = i.Key || "", l;
    if (i.UseRawKey ? l = i.Pathname || i.pathname || "/" + s : (l = i.Pathname || i.pathname || s,
    l.indexOf("/") !== 0 && (l = "/" + l)),
    !a.Host && !a.host && i.Bucket && i.Region && (a.Host = i.Bucket + ".cos." + i.Region + ".myqcloud.com"),
    !e)
        throw new Error("missing param SecretId");
    if (!t)
        throw new Error("missing param SecretKey");
    var u = Math.round(getSkewTime(i.SystemClockOffset) / 1e3) - 1
      , c = u
      , h = i.Expires || i.expires;
    h === void 0 ? c += 900 : c += h * 1 || 0;
    var f = "sha1"
      , d = e
      , _ = r || u + ";" + c
      , g = r || u + ";" + c
      , m = getObjectKeys(a, !0).join(";").toLowerCase()
      , v = getObjectKeys(o, !0).join(";").toLowerCase()
      , y = CryptoJS.HmacSHA1(g, t).toString()
      , b = [n, l, util$5.obj2str(o, !0), util$5.obj2str(a, !0), ""].join(`
`)
      , T = ["sha1", _, CryptoJS.SHA1(b).toString(), ""].join(`
`)
      , C = CryptoJS.HmacSHA1(T, y).toString()
      , A = ["q-sign-algorithm=" + f, "q-ak=" + d, "q-sign-time=" + _, "q-key-time=" + g, "q-header-list=" + m, "q-url-param-list=" + v, "q-signature=" + C].join("&");
    return A
}
  , readIntBE = function(i, e, t) {
    var r = e / 8
      , n = i.slice(t, t + r);
    return new Uint8Array(n).reverse(),
    new {
        8: Uint8Array,
        16: Uint16Array,
        32: Uint32Array
    }[e](n)[0]
}
  , buf2str = function(i, e, t, r) {
    var n = i.slice(e, t)
      , o = "";
    return new Uint8Array(n).forEach(function(a) {
        o += String.fromCharCode(a)
    }),
    r && (o = decodeURIComponent(escape(o))),
    o
}
  , parseSelectPayload = function(i) {
    for (var e = {}, t = buf2str(i), r = {
        records: []
    }; i.byteLength; ) {
        var n = readIntBE(i, 32, 0), o = readIntBE(i, 32, 4), a = n - o - 16, s = 0, l;
        for (i = i.slice(12); s < o; ) {
            var u = readIntBE(i, 8, s)
              , c = buf2str(i, s + 1, s + 1 + u)
              , h = readIntBE(i, 16, s + u + 2)
              , f = buf2str(i, s + u + 4, s + u + 4 + h);
            e[c] = f,
            s += u + 4 + h
        }
        if (e[":event-type"] === "Records")
            l = buf2str(i, s, s + a, !0),
            r.records.push(l);
        else if (e[":event-type"] === "Stats")
            l = buf2str(i, s, s + a, !0),
            r.stats = util$5.xml2json(l).Stats;
        else if (e[":event-type"] === "error") {
            var d = e[":error-code"]
              , _ = e[":error-message"]
              , g = new Error(_);
            g.message = _,
            g.name = g.code = d,
            r.error = g
        } else
            ["Progress", "Continuation", "End"].includes(e[":event-type"]);
        i = i.slice(s + a + 4)
    }
    return {
        payload: r.records.join(""),
        body: t
    }
}
  , getSourceParams = function(i) {
    var e = this.options.CopySourceParser;
    if (e)
        return e(i);
    var t = i.match(/^([^.]+-\d+)\.cos(v6|-cdc)?\.([^.]+)\.myqcloud\.com\/(.+)$/);
    return t ? {
        Bucket: t[1],
        Region: t[3],
        Key: t[4]
    } : null
}
  , noop = function() {}
  , clearKey = function(i) {
    var e = {};
    for (var t in i)
        i.hasOwnProperty(t) && i[t] !== void 0 && i[t] !== null && (e[t] = i[t]);
    return e
}
  , readAsBinaryString = function(i, e) {
    var t, r = new FileReader;
    FileReader.prototype.readAsBinaryString ? (t = FileReader.prototype.readAsBinaryString,
    r.onload = function() {
        e(this.result)
    }
    ) : FileReader.prototype.readAsArrayBuffer ? t = function(n) {
        var o = ""
          , a = new FileReader;
        a.onload = function(s) {
            for (var l = new Uint8Array(a.result), u = l.byteLength, c = 0; c < u; c++)
                o += String.fromCharCode(l[c]);
            e(o)
        }
        ,
        a.readAsArrayBuffer(n)
    }
    : console.error("FileReader not support readAsBinaryString"),
    t.call(r, i)
}
  , fileSliceNeedCopy = function() {
    var i = function(t, r) {
        t = t.split("."),
        r = r.split(".");
        for (var n = 0; n < r.length; n++)
            if (t[n] !== r[n])
                return parseInt(t[n]) > parseInt(r[n]) ? 1 : -1;
        return 0
    }
      , e = function(t) {
        if (!t)
            return !1;
        var r = (t.match(/Chrome\/([.\d]+)/) || [])[1]
          , n = (t.match(/QBCore\/([.\d]+)/) || [])[1]
          , o = (t.match(/QQBrowser\/([.\d]+)/) || [])[1]
          , a = r && i(r, "53.0.2785.116") < 0 && n && i(n, "3.53.991.400") < 0 && o && i(o, "9.0.2524.400") <= 0 || !1;
        return a
    };
    return e(typeof navigator != "undefined" && navigator.userAgent)
}()
  , fileSlice = function(i, e, t, r, n) {
    var o;
    if (i.slice ? o = i.slice(e, t) : i.mozSlice ? o = i.mozSlice(e, t) : i.webkitSlice && (o = i.webkitSlice(e, t)),
    r && fileSliceNeedCopy) {
        var a = new FileReader;
        a.onload = function(s) {
            o = null,
            n(new Blob([a.result]))
        }
        ,
        a.readAsArrayBuffer(o)
    } else
        n(o)
}
  , getBodyMd5 = function(i, e, t, r) {
    t = t || noop,
    i ? typeof e == "string" ? t(util$5.md5(e, !0)) : Blob && e instanceof Blob ? util$5.getFileMd5(e, function(n, o) {
        t(o)
    }, r) : t() : t()
}
  , md5ChunkSize = 1024 * 1024
  , getFileMd5 = function(i, e, t) {
    var r = i.size
      , n = 0
      , o = md5.getCtx()
      , a = function(s) {
        if (s >= r) {
            var l = o.digest("hex");
            e(null, l);
            return
        }
        var u = Math.min(r, s + md5ChunkSize);
        util$5.fileSlice(i, s, u, !1, function(c) {
            readAsBinaryString(c, function(h) {
                c = null,
                o = o.update(h, !0),
                n += h.length,
                h = null,
                t && t({
                    loaded: n,
                    total: r,
                    percent: Math.round(n / r * 1e4) / 1e4
                }),
                a(s + md5ChunkSize)
            })
        })
    };
    a(0)
};
function clone(i) {
    return map(i, function(e) {
        return typeof e == "object" && e !== null ? clone(e) : e
    })
}
function attr(i, e, t) {
    return i && e in i ? i[e] : t
}
function extend$1(i, e) {
    return each(e, function(t, r) {
        i[r] = e[r]
    }),
    i
}
function isArray$1(i) {
    return i instanceof Array
}
function isInArray(i, e) {
    for (var t = !1, r = 0; r < i.length; r++)
        if (e === i[r]) {
            t = !0;
            break
        }
    return t
}
function makeArray(i) {
    return isArray$1(i) ? i : [i]
}
function each(i, e) {
    for (var t in i)
        i.hasOwnProperty(t) && e(i[t], t)
}
function map(i, e) {
    var t = isArray$1(i) ? [] : {};
    for (var r in i)
        i.hasOwnProperty(r) && (t[r] = e(i[r], r));
    return t
}
function filter(i, e) {
    var t = isArray$1(i)
      , r = t ? [] : {};
    for (var n in i)
        i.hasOwnProperty(n) && e(i[n], n) && (t ? r.push(i[n]) : r[n] = i[n]);
    return r
}
var binaryBase64 = function(i) {
    var e, t, r, n = "";
    for (e = 0,
    t = i.length / 2; e < t; e++)
        r = parseInt(i[e * 2] + i[e * 2 + 1], 16),
        n += String.fromCharCode(r);
    return btoa(n)
}
  , uuid = function() {
    var i = function() {
        return ((1 + Math.random()) * 65536 | 0).toString(16).substring(1)
    };
    return i() + i() + "-" + i() + "-" + i() + "-" + i() + "-" + i() + i() + i()
}
  , hasMissingParams = function(i, e) {
    var t = e.Bucket
      , r = e.Region
      , n = e.Key
      , o = this.options.Domain
      , a = !o || o.indexOf("{Bucket}") > -1
      , s = !o || o.indexOf("{Region}") > -1;
    if (i.indexOf("Bucket") > -1 || i === "deleteMultipleObject" || i === "multipartList" || i === "listObjectVersions") {
        if (a && !t)
            return "Bucket";
        if (s && !r)
            return "Region"
    } else if (i.indexOf("Object") > -1 || i.indexOf("multipart") > -1 || i === "sliceUploadFile" || i === "abortUploadTask") {
        if (a && !t)
            return "Bucket";
        if (s && !r)
            return "Region";
        if (!n)
            return "Key"
    }
    return !1
}
  , formatParams = function(i, e) {
    if (e = extend$1({}, e),
    i !== "getAuth" && i !== "getV4Auth" && i !== "getObjectUrl") {
        var t = e.Headers || {};
        if (e && typeof e == "object") {
            (function() {
                for (var n in e)
                    e.hasOwnProperty(n) && n.indexOf("x-cos-") > -1 && (t[n] = e[n])
            }
            )();
            var r = {
                "x-cos-mfa": "MFA",
                "Content-MD5": "ContentMD5",
                "Content-Length": "ContentLength",
                "Content-Type": "ContentType",
                Expect: "Expect",
                Expires: "Expires",
                "Cache-Control": "CacheControl",
                "Content-Disposition": "ContentDisposition",
                "Content-Encoding": "ContentEncoding",
                Range: "Range",
                "If-Modified-Since": "IfModifiedSince",
                "If-Unmodified-Since": "IfUnmodifiedSince",
                "If-Match": "IfMatch",
                "If-None-Match": "IfNoneMatch",
                "x-cos-copy-source": "CopySource",
                "x-cos-copy-source-Range": "CopySourceRange",
                "x-cos-metadata-directive": "MetadataDirective",
                "x-cos-copy-source-If-Modified-Since": "CopySourceIfModifiedSince",
                "x-cos-copy-source-If-Unmodified-Since": "CopySourceIfUnmodifiedSince",
                "x-cos-copy-source-If-Match": "CopySourceIfMatch",
                "x-cos-copy-source-If-None-Match": "CopySourceIfNoneMatch",
                "x-cos-acl": "ACL",
                "x-cos-grant-read": "GrantRead",
                "x-cos-grant-write": "GrantWrite",
                "x-cos-grant-full-control": "GrantFullControl",
                "x-cos-grant-read-acp": "GrantReadAcp",
                "x-cos-grant-write-acp": "GrantWriteAcp",
                "x-cos-storage-class": "StorageClass",
                "x-cos-traffic-limit": "TrafficLimit",
                "x-cos-mime-limit": "MimeLimit",
                "x-cos-server-side-encryption-customer-algorithm": "SSECustomerAlgorithm",
                "x-cos-server-side-encryption-customer-key": "SSECustomerKey",
                "x-cos-server-side-encryption-customer-key-MD5": "SSECustomerKeyMD5",
                "x-cos-server-side-encryption": "ServerSideEncryption",
                "x-cos-server-side-encryption-cos-kms-key-id": "SSEKMSKeyId",
                "x-cos-server-side-encryption-context": "SSEContext"
            };
            util$5.each(r, function(n, o) {
                e[n] !== void 0 && (t[o] = e[n])
            }),
            e.Headers = clearKey(t)
        }
    }
    return e
}
  , apiWrapper = function(i, e) {
    return function(t, r) {
        var n = this;
        typeof t == "function" && (r = t,
        t = {}),
        t = formatParams(i, t);
        var o = function(h) {
            return h && h.headers && (h.headers["x-cos-request-id"] && (h.RequestId = h.headers["x-cos-request-id"]),
            h.headers["x-cos-version-id"] && (h.VersionId = h.headers["x-cos-version-id"]),
            h.headers["x-cos-delete-marker"] && (h.DeleteMarker = h.headers["x-cos-delete-marker"])),
            h
        }
          , a = function(h, f) {
            r && r(o(h), o(f))
        }
          , s = function() {
            if (i !== "getService" && i !== "abortUploadTask") {
                var h = hasMissingParams.call(n, i, t);
                if (h)
                    return "missing param " + h;
                if (t.Region) {
                    if (n.options.CompatibilityMode) {
                        if (!/^([a-z\d-.]+)$/.test(t.Region))
                            return "Region format error."
                    } else {
                        if (t.Region.indexOf("cos.") > -1)
                            return 'param Region should not be start with "cos."';
                        if (!/^([a-z\d-]+)$/.test(t.Region))
                            return "Region format error."
                    }
                    !n.options.CompatibilityMode && t.Region.indexOf("-") === -1 && t.Region !== "yfb" && t.Region !== "default" && t.Region !== "accelerate" && console.warn("warning: param Region format error, find help here: https://cloud.tencent.com/document/product/436/6224")
                }
                if (t.Bucket) {
                    if (!/^([a-z\d-]+)-(\d+)$/.test(t.Bucket))
                        if (t.AppId)
                            t.Bucket = t.Bucket + "-" + t.AppId;
                        else if (n.options.AppId)
                            t.Bucket = t.Bucket + "-" + n.options.AppId;
                        else
                            return 'Bucket should format as "test-1250000000".';
                    t.AppId && (console.warn('warning: AppId has been deprecated, Please put it at the end of parameter Bucket(E.g Bucket:"test-1250000000" ).'),
                    delete t.AppId)
                }
                !n.options.UseRawKey && t.Key && t.Key.substr(0, 1) === "/" && (t.Key = t.Key.substr(1))
            }
        }
          , l = s()
          , u = i === "getAuth" || i === "getObjectUrl";
        if (window.Promise && !u && !r)
            return new Promise(function(h, f) {
                if (r = function(d, _) {
                    d ? f(d) : h(_)
                }
                ,
                l)
                    return a(util$5.error(new Error(l)));
                e.call(n, t, a)
            }
            );
        if (l)
            return a(util$5.error(new Error(l)));
        var c = e.call(n, t, a);
        if (u)
            return c
    }
}
  , throttleOnProgress = function(i, e) {
    var t = this, r = 0, n = 0, o = Date.now(), a, s;
    function l() {
        if (s = 0,
        e && typeof e == "function") {
            a = Date.now();
            var u = Math.max(0, Math.round((n - r) / ((a - o) / 1e3) * 100) / 100) || 0, c;
            n === 0 && i === 0 ? c = 1 : c = Math.floor(n / i * 100) / 100 || 0,
            o = a,
            r = n;
            try {
                e({
                    loaded: n,
                    total: i,
                    speed: u,
                    percent: c
                })
            } catch {}
        }
    }
    return function(u, c) {
        if (u && (n = u.loaded,
        i = u.total),
        c)
            clearTimeout(s),
            l();
        else {
            if (s)
                return;
            s = setTimeout(l, t.options.ProgressInterval)
        }
    }
}
  , getFileSize = function(i, e, t) {
    var r;
    if (typeof e.Body == "string" ? e.Body = new Blob([e.Body],{
        type: "text/plain"
    }) : e.Body instanceof ArrayBuffer && (e.Body = new Blob([e.Body])),
    e.Body && (e.Body instanceof Blob || e.Body.toString() === "[object File]" || e.Body.toString() === "[object Blob]"))
        r = e.Body.size;
    else {
        t(util$5.error(new Error("params body format error, Only allow File|Blob|String.")));
        return
    }
    e.ContentLength = r,
    t(null, r)
}
  , getSkewTime = function(i) {
    return Date.now() + (i || 0)
}
  , error = function(i, e) {
    var t = i;
    return i.message = i.message || null,
    typeof e == "string" ? (i.error = e,
    i.message = e) : typeof e == "object" && e !== null && (extend$1(i, e),
    (e.code || e.name) && (i.code = e.code || e.name),
    e.message && (i.message = e.message),
    e.stack && (i.stack = e.stack)),
    typeof Object.defineProperty == "function" && (Object.defineProperty(i, "name", {
        writable: !0,
        enumerable: !1
    }),
    Object.defineProperty(i, "message", {
        enumerable: !0
    })),
    i.name = e && e.name || i.name || i.code || "Error",
    i.code || (i.code = i.name),
    i.error || (i.error = clone(t)),
    i
}
  , isNode = function() {
    return typeof window != "object" && typeof process == "object" && typeof commonjsRequire == "function"
}
  , isCIHost = function(i) {
    return /^https?:\/\/([^/]+\.)?ci\.[^/]+/.test(i)
}
  , util$5 = {
    noop,
    formatParams,
    apiWrapper,
    xml2json,
    json2xml,
    md5,
    clearKey,
    fileSlice,
    getBodyMd5,
    getFileMd5,
    binaryBase64,
    extend: extend$1,
    isArray: isArray$1,
    isInArray,
    makeArray,
    each,
    map,
    filter,
    clone,
    attr,
    uuid,
    camSafeUrlEncode,
    throttleOnProgress,
    getFileSize,
    getSkewTime,
    error,
    obj2str,
    getAuth: getAuth$1,
    parseSelectPayload,
    getSourceParams,
    isBrowser: !0,
    isNode,
    isCIHost
}
  , util_1 = util$5
  , event$1 = {}
  , initEvent = function(i) {
    var e = {}
      , t = function(r) {
        return !e[r] && (e[r] = []),
        e[r]
    };
    i.on = function(r, n) {
        r === "task-list-update" && console.warn('warning: Event "' + r + '" has been deprecated. Please use "list-update" instead.'),
        t(r).push(n)
    }
    ,
    i.off = function(r, n) {
        for (var o = t(r), a = o.length - 1; a >= 0; a--)
            n === o[a] && o.splice(a, 1)
    }
    ,
    i.emit = function(r, n) {
        for (var o = t(r).map(function(s) {
            return s
        }), a = 0; a < o.length; a++)
            o[a](n)
    }
}
  , EventProxy$1 = function() {
    initEvent(this)
};
event$1.init = initEvent;
event$1.EventProxy = EventProxy$1;
var task$1 = {}, util$4 = util_1, cacheKey = "cos_sdk_upload_cache", expires = 30 * 24 * 3600, cache, timer, getCache = function() {
    try {
        var i = JSON.parse(localStorage.getItem(cacheKey))
    } catch {}
    i || (i = []),
    cache = i
}, setCache = function() {
    try {
        localStorage.setItem(cacheKey, JSON.stringify(cache))
    } catch {}
}, init = function() {
    if (!cache) {
        getCache.call(this);
        for (var i = !1, e = Math.round(Date.now() / 1e3), t = cache.length - 1; t >= 0; t--) {
            var r = cache[t][2];
            (!r || r + expires < e) && (cache.splice(t, 1),
            i = !0)
        }
        i && setCache()
    }
}, save = function() {
    timer || (timer = setTimeout(function() {
        setCache(),
        timer = null
    }, 400))
}, mod = {
    using: {},
    setUsing: function(i) {
        mod.using[i] = !0
    },
    removeUsing: function(i) {
        delete mod.using[i]
    },
    getFileId: function(i, e, t, r) {
        return i.name && i.size && i.lastModifiedDate && e ? util$4.md5([i.name, i.size, i.lastModifiedDate, e, t, r].join("::")) : null
    },
    getUploadIdList: function(i) {
        if (!i)
            return null;
        init.call(this);
        for (var e = [], t = 0; t < cache.length; t++)
            cache[t][0] === i && e.push(cache[t][1]);
        return e.length ? e : null
    },
    saveUploadId: function(i, e, t) {
        if (init.call(this),
        !!i) {
            for (var r = cache.length - 1; r >= 0; r--) {
                var n = cache[r];
                n[0] === i && n[1] === e && cache.splice(r, 1)
            }
            cache.unshift([i, e, Math.round(Date.now() / 1e3)]),
            cache.length > t && cache.splice(t),
            save()
        }
    },
    removeUploadId: function(i) {
        init.call(this),
        delete mod.using[i];
        for (var e = cache.length - 1; e >= 0; e--)
            cache[e][1] === i && cache.splice(e, 1);
        save()
    }
}, session$2 = mod, session$1 = session$2, util$3 = util_1, originApiMap = {}, transferToTaskMethod = function(i, e) {
    originApiMap[e] = i[e],
    i[e] = function(t, r) {
        t.SkipTask ? originApiMap[e].call(this, t, r) : this._addTask(e, t, r)
    }
}, initTask = function(i) {
    var e = []
      , t = {}
      , r = 0
      , n = 0
      , o = function(h) {
        var f = {
            id: h.id,
            Bucket: h.Bucket,
            Region: h.Region,
            Key: h.Key,
            FilePath: h.FilePath,
            state: h.state,
            loaded: h.loaded,
            size: h.size,
            speed: h.speed,
            percent: h.percent,
            hashPercent: h.hashPercent,
            error: h.error
        };
        return h.FilePath && (f.FilePath = h.FilePath),
        h._custom && (f._custom = h._custom),
        f
    }
      , a = function() {
        var h, f = function() {
            h = 0,
            i.emit("task-list-update", {
                list: util$3.map(e, o)
            }),
            i.emit("list-update", {
                list: util$3.map(e, o)
            })
        };
        return function() {
            h || (h = setTimeout(f))
        }
    }()
      , s = function() {
        if (!(e.length <= i.options.UploadQueueSize)) {
            for (var h = 0; h < n && h < e.length && e.length > i.options.UploadQueueSize; ) {
                var f = e[h].state === "waiting" || e[h].state === "checking" || e[h].state === "uploading";
                !e[h] || !f ? (t[e[h].id] && delete t[e[h].id],
                e.splice(h, 1),
                n--) : h++
            }
            a()
        }
    }
      , l = function() {
        if (!(r >= i.options.FileParallelLimit)) {
            for (; e[n] && e[n].state !== "waiting"; )
                n++;
            if (!(n >= e.length)) {
                var h = e[n];
                n++,
                r++,
                h.state = "checking",
                h.params.onTaskStart && h.params.onTaskStart(o(h)),
                !h.params.UploadData && (h.params.UploadData = {});
                var f = util$3.formatParams(h.api, h.params);
                originApiMap[h.api].call(i, f, function(d, _) {
                    !i._isRunningTask(h.id) || ((h.state === "checking" || h.state === "uploading") && (h.state = d ? "error" : "success",
                    d && (h.error = d),
                    r--,
                    a(),
                    l(),
                    h.callback && h.callback(d, _),
                    h.state === "success" && (h.params && (delete h.params.UploadData,
                    delete h.params.Body,
                    delete h.params),
                    delete h.callback)),
                    s())
                }),
                a(),
                setTimeout(l)
            }
        }
    }
      , u = function(h, f) {
        var d = t[h];
        if (!!d) {
            var _ = d && d.state === "waiting"
              , g = d && (d.state === "checking" || d.state === "uploading");
            if (f === "canceled" && d.state !== "canceled" || f === "paused" && _ || f === "paused" && g) {
                if (f === "paused" && d.params.Body && typeof d.params.Body.pipe == "function") {
                    console.error("stream not support pause");
                    return
                }
                d.state = f,
                i.emit("inner-kill-task", {
                    TaskId: h,
                    toState: f
                });
                try {
                    var m = d && d.params && d.params.UploadData.UploadId
                } catch {}
                f === "canceled" && m && session$1.removeUsing(m),
                a(),
                g && (r--,
                l()),
                f === "canceled" && (d.params && (delete d.params.UploadData,
                delete d.params.Body,
                delete d.params),
                delete d.callback)
            }
            s()
        }
    };
    i._addTasks = function(h) {
        util$3.each(h, function(f) {
            i._addTask(f.api, f.params, f.callback, !0)
        }),
        a()
    }
    ;
    var c = !0;
    i._addTask = function(h, f, d, _) {
        f = util$3.formatParams(h, f);
        var g = util$3.uuid();
        f.TaskId = g,
        f.onTaskReady && f.onTaskReady(g),
        f.TaskReady && (f.TaskReady(g),
        c && console.warn('warning: Param "TaskReady" has been deprecated. Please use "onTaskReady" instead.'),
        c = !1);
        var m = {
            params: f,
            callback: d,
            api: h,
            index: e.length,
            id: g,
            Bucket: f.Bucket,
            Region: f.Region,
            Key: f.Key,
            FilePath: f.FilePath || "",
            state: "waiting",
            loaded: 0,
            size: 0,
            speed: 0,
            percent: 0,
            hashPercent: 0,
            error: null,
            _custom: f._custom
        }
          , v = f.onHashProgress;
        f.onHashProgress = function(b) {
            !i._isRunningTask(m.id) || (m.hashPercent = b.percent,
            v && v(b),
            a())
        }
        ;
        var y = f.onProgress;
        return f.onProgress = function(b) {
            !i._isRunningTask(m.id) || (m.state === "checking" && (m.state = "uploading"),
            m.loaded = b.loaded,
            m.speed = b.speed,
            m.percent = b.percent,
            y && y(b),
            a())
        }
        ,
        util$3.getFileSize(h, f, function(b, T) {
            if (b)
                return d(util$3.error(b));
            t[g] = m,
            e.push(m),
            m.size = T,
            !_ && a(),
            l(),
            s()
        }),
        g
    }
    ,
    i._isRunningTask = function(h) {
        var f = t[h];
        return !!(f && (f.state === "checking" || f.state === "uploading"))
    }
    ,
    i.getTaskList = function() {
        return util$3.map(e, o)
    }
    ,
    i.cancelTask = function(h) {
        u(h, "canceled")
    }
    ,
    i.pauseTask = function(h) {
        u(h, "paused")
    }
    ,
    i.restartTask = function(h) {
        var f = t[h];
        f && (f.state === "paused" || f.state === "error") && (f.state = "waiting",
        a(),
        n = Math.min(n, f.index),
        l())
    }
    ,
    i.isUploadRunning = function() {
        return r || n < e.length
    }
};
task$1.transferToTaskMethod = transferToTaskMethod;
task$1.init = initTask;
var base$1 = {}
  , stringifyPrimitive = function(i) {
    switch (typeof i) {
    case "string":
        return i;
    case "boolean":
        return i ? "true" : "false";
    case "number":
        return isFinite(i) ? i : "";
    default:
        return ""
    }
}
  , queryStringify = function(i, e, t, r) {
    return e = e || "&",
    t = t || "=",
    i === null && (i = void 0),
    typeof i == "object" ? Object.keys(i).map(function(n) {
        var o = encodeURIComponent(stringifyPrimitive(n)) + t;
        return Array.isArray(i[n]) ? i[n].map(function(a) {
            return o + encodeURIComponent(stringifyPrimitive(a))
        }).join(e) : o + encodeURIComponent(stringifyPrimitive(i[n]))
    }).filter(Boolean).join(e) : r ? encodeURIComponent(stringifyPrimitive(r)) + t + encodeURIComponent(stringifyPrimitive(i)) : ""
}
  , xhrRes = function(i, e, t) {
    var r = {};
    return e.getAllResponseHeaders().trim().split(`
`).forEach(function(n) {
        if (n) {
            var o = n.indexOf(":")
              , a = n.substr(0, o).trim().toLowerCase()
              , s = n.substr(o + 1).trim();
            r[a] = s
        }
    }),
    {
        error: i,
        statusCode: e.status,
        statusMessage: e.statusText,
        headers: r,
        body: t
    }
}
  , xhrBody = function(i, e) {
    return !e && e === "text" ? i.responseText : i.response
}
  , request$1 = function(i, e) {
    var t = (i.method || "GET").toUpperCase()
      , r = i.url;
    if (i.qs) {
        var n = queryStringify(i.qs);
        n && (r += (r.indexOf("?") === -1 ? "?" : "&") + n)
    }
    var o = new XMLHttpRequest;
    if (o.open(t, r, !0),
    o.responseType = i.dataType || "text",
    i.xhrFields)
        for (var a in i.xhrFields)
            o[a] = i.xhrFields[a];
    var s = i.headers;
    if (s)
        for (var l in s)
            s.hasOwnProperty(l) && l.toLowerCase() !== "content-length" && l.toLowerCase() !== "user-agent" && l.toLowerCase() !== "origin" && l.toLowerCase() !== "host" && o.setRequestHeader(l, s[l]);
    return i.onProgress && o.upload && (o.upload.onprogress = i.onProgress),
    i.onDownloadProgress && (o.onprogress = i.onDownloadProgress),
    i.timeout && (o.timeout = i.timeout),
    o.ontimeout = function(u) {
        var c = new Error("timeout");
        e(xhrRes(c, o))
    }
    ,
    o.onload = function() {
        e(xhrRes(null, o, xhrBody(o, i.dataType)))
    }
    ,
    o.onerror = function(u) {
        var c = xhrBody(o, i.dataType);
        if (c)
            e(xhrRes(null, o, c));
        else {
            var h = o.statusText;
            !h && o.status === 0 && (h = new Error("CORS blocked or network error")),
            e(xhrRes(h, o, c))
        }
    }
    ,
    o.send(i.body || ""),
    o
}
  , request_1 = request$1
  , REQUEST = request_1
  , util$2 = util_1;
function getService(i, e) {
    typeof i == "function" && (e = i,
    i = {});
    var t = this.options.Protocol || (util$2.isBrowser && location.protocol === "http:" ? "http:" : "https:")
      , r = this.options.ServiceDomain
      , n = i.AppId || this.options.appId
      , o = i.Region;
    r ? (r = r.replace(/\{\{AppId\}\}/ig, n || "").replace(/\{\{Region\}\}/ig, o || "").replace(/\{\{.*?\}\}/ig, ""),
    /^[a-zA-Z]+:\/\//.test(r) || (r = t + "//" + r),
    r.slice(-1) === "/" && (r = r.slice(0, -1))) : o ? r = t + "//cos." + o + ".myqcloud.com" : r = t + "//service.cos.myqcloud.com";
    var a = ""
      , s = o ? "cos." + o + ".myqcloud.com" : "service.cos.myqcloud.com"
      , l = r.replace(/^https?:\/\/([^/]+)(\/.*)?$/, "$1");
    s === l && (a = s),
    submitRequest.call(this, {
        Action: "name/cos:GetService",
        url: r,
        method: "GET",
        headers: i.Headers,
        SignHost: a
    }, function(u, c) {
        if (u)
            return e(u);
        var h = c && c.ListAllMyBucketsResult && c.ListAllMyBucketsResult.Buckets && c.ListAllMyBucketsResult.Buckets.Bucket || [];
        h = util$2.isArray(h) ? h : [h];
        var f = c && c.ListAllMyBucketsResult && c.ListAllMyBucketsResult.Owner || {};
        e(null, {
            Buckets: h,
            Owner: f,
            statusCode: c.statusCode,
            headers: c.headers
        })
    })
}
function putBucket(i, e) {
    var t = this
      , r = "";
    if (i.BucketAZConfig) {
        var n = {
            BucketAZConfig: i.BucketAZConfig
        };
        r = util$2.json2xml({
            CreateBucketConfiguration: n
        })
    }
    submitRequest.call(this, {
        Action: "name/cos:PutBucket",
        method: "PUT",
        Bucket: i.Bucket,
        Region: i.Region,
        headers: i.Headers,
        body: r
    }, function(o, a) {
        if (o)
            return e(o);
        var s = getUrl({
            protocol: t.options.Protocol,
            domain: t.options.Domain,
            bucket: i.Bucket,
            region: i.Region,
            isLocation: !0
        });
        e(null, {
            Location: s,
            statusCode: a.statusCode,
            headers: a.headers
        })
    })
}
function headBucket(i, e) {
    submitRequest.call(this, {
        Action: "name/cos:HeadBucket",
        Bucket: i.Bucket,
        Region: i.Region,
        headers: i.Headers,
        method: "HEAD"
    }, e)
}
function getBucket(i, e) {
    var t = {};
    t.prefix = i.Prefix || "",
    t.delimiter = i.Delimiter,
    t.marker = i.Marker,
    t["max-keys"] = i.MaxKeys,
    t["encoding-type"] = i.EncodingType,
    submitRequest.call(this, {
        Action: "name/cos:GetBucket",
        ResourceKey: t.prefix,
        method: "GET",
        Bucket: i.Bucket,
        Region: i.Region,
        headers: i.Headers,
        qs: t
    }, function(r, n) {
        if (r)
            return e(r);
        var o = n.ListBucketResult || {}
          , a = o.Contents || []
          , s = o.CommonPrefixes || [];
        a = util$2.isArray(a) ? a : [a],
        s = util$2.isArray(s) ? s : [s];
        var l = util$2.clone(o);
        util$2.extend(l, {
            Contents: a,
            CommonPrefixes: s,
            statusCode: n.statusCode,
            headers: n.headers
        }),
        e(null, l)
    })
}
function deleteBucket(i, e) {
    submitRequest.call(this, {
        Action: "name/cos:DeleteBucket",
        Bucket: i.Bucket,
        Region: i.Region,
        headers: i.Headers,
        method: "DELETE"
    }, function(t, r) {
        if (t && t.statusCode === 204)
            return e(null, {
                statusCode: t.statusCode
            });
        if (t)
            return e(t);
        e(null, {
            statusCode: r.statusCode,
            headers: r.headers
        })
    })
}
function putBucketAcl(i, e) {
    var t = i.Headers
      , r = "";
    if (i.AccessControlPolicy) {
        var n = util$2.clone(i.AccessControlPolicy || {})
          , o = n.Grants || n.Grant;
        o = util$2.isArray(o) ? o : [o],
        delete n.Grant,
        delete n.Grants,
        n.AccessControlList = {
            Grant: o
        },
        r = util$2.json2xml({
            AccessControlPolicy: n
        }),
        t["Content-Type"] = "application/xml",
        t["Content-MD5"] = util$2.binaryBase64(util$2.md5(r))
    }
    util$2.each(t, function(a, s) {
        s.indexOf("x-cos-grant-") === 0 && (t[s] = uniqGrant(t[s]))
    }),
    submitRequest.call(this, {
        Action: "name/cos:PutBucketACL",
        method: "PUT",
        Bucket: i.Bucket,
        Region: i.Region,
        headers: t,
        action: "acl",
        body: r
    }, function(a, s) {
        if (a)
            return e(a);
        e(null, {
            statusCode: s.statusCode,
            headers: s.headers
        })
    })
}
function getBucketAcl(i, e) {
    submitRequest.call(this, {
        Action: "name/cos:GetBucketACL",
        method: "GET",
        Bucket: i.Bucket,
        Region: i.Region,
        headers: i.Headers,
        action: "acl"
    }, function(t, r) {
        if (t)
            return e(t);
        var n = r.AccessControlPolicy || {}
          , o = n.Owner || {}
          , a = n.AccessControlList.Grant || [];
        a = util$2.isArray(a) ? a : [a];
        var s = decodeAcl(n);
        r.headers && r.headers["x-cos-acl"] && (s.ACL = r.headers["x-cos-acl"]),
        s = util$2.extend(s, {
            Owner: o,
            Grants: a,
            statusCode: r.statusCode,
            headers: r.headers
        }),
        e(null, s)
    })
}
function putBucketCors(i, e) {
    var t = i.CORSConfiguration || {}
      , r = t.CORSRules || i.CORSRules || [];
    r = util$2.clone(util$2.isArray(r) ? r : [r]),
    util$2.each(r, function(a) {
        util$2.each(["AllowedOrigin", "AllowedHeader", "AllowedMethod", "ExposeHeader"], function(s) {
            var l = s + "s"
              , u = a[l] || a[s] || [];
            delete a[l],
            a[s] = util$2.isArray(u) ? u : [u]
        })
    });
    var n = util$2.json2xml({
        CORSConfiguration: {
            CORSRule: r
        }
    })
      , o = i.Headers;
    o["Content-Type"] = "application/xml",
    o["Content-MD5"] = util$2.binaryBase64(util$2.md5(n)),
    submitRequest.call(this, {
        Action: "name/cos:PutBucketCORS",
        method: "PUT",
        Bucket: i.Bucket,
        Region: i.Region,
        body: n,
        action: "cors",
        headers: o
    }, function(a, s) {
        if (a)
            return e(a);
        e(null, {
            statusCode: s.statusCode,
            headers: s.headers
        })
    })
}
function getBucketCors(i, e) {
    submitRequest.call(this, {
        Action: "name/cos:GetBucketCORS",
        method: "GET",
        Bucket: i.Bucket,
        Region: i.Region,
        headers: i.Headers,
        action: "cors"
    }, function(t, r) {
        if (t) {
            if (t.statusCode === 404 && t.error && t.error.Code === "NoSuchCORSConfiguration") {
                var n = {
                    CORSRules: [],
                    statusCode: t.statusCode
                };
                t.headers && (n.headers = t.headers),
                e(null, n)
            } else
                e(t);
            return
        }
        var o = r.CORSConfiguration || {}
          , a = o.CORSRules || o.CORSRule || [];
        a = util$2.clone(util$2.isArray(a) ? a : [a]),
        util$2.each(a, function(s) {
            util$2.each(["AllowedOrigin", "AllowedHeader", "AllowedMethod", "ExposeHeader"], function(l) {
                var u = l + "s"
                  , c = s[u] || s[l] || [];
                delete s[l],
                s[u] = util$2.isArray(c) ? c : [c]
            })
        }),
        e(null, {
            CORSRules: a,
            statusCode: r.statusCode,
            headers: r.headers
        })
    })
}
function deleteBucketCors(i, e) {
    submitRequest.call(this, {
        Action: "name/cos:DeleteBucketCORS",
        method: "DELETE",
        Bucket: i.Bucket,
        Region: i.Region,
        headers: i.Headers,
        action: "cors"
    }, function(t, r) {
        if (t && t.statusCode === 204)
            return e(null, {
                statusCode: t.statusCode
            });
        if (t)
            return e(t);
        e(null, {
            statusCode: r.statusCode || t.statusCode,
            headers: r.headers
        })
    })
}
function getBucketLocation(i, e) {
    submitRequest.call(this, {
        Action: "name/cos:GetBucketLocation",
        method: "GET",
        Bucket: i.Bucket,
        Region: i.Region,
        headers: i.Headers,
        action: "location"
    }, e)
}
function putBucketPolicy(i, e) {
    var t = i.Policy;
    try {
        typeof t == "string" && (t = JSON.parse(t))
    } catch {}
    if (!t || typeof t == "string")
        return e(util$2.error(new Error("Policy format error")));
    var r = JSON.stringify(t);
    t.version || (t.version = "2.0");
    var n = i.Headers;
    n["Content-Type"] = "application/json",
    n["Content-MD5"] = util$2.binaryBase64(util$2.md5(r)),
    submitRequest.call(this, {
        Action: "name/cos:PutBucketPolicy",
        method: "PUT",
        Bucket: i.Bucket,
        Region: i.Region,
        action: "policy",
        body: r,
        headers: n
    }, function(o, a) {
        if (o && o.statusCode === 204)
            return e(null, {
                statusCode: o.statusCode
            });
        if (o)
            return e(o);
        e(null, {
            statusCode: a.statusCode,
            headers: a.headers
        })
    })
}
function getBucketPolicy(i, e) {
    submitRequest.call(this, {
        Action: "name/cos:GetBucketPolicy",
        method: "GET",
        Bucket: i.Bucket,
        Region: i.Region,
        headers: i.Headers,
        action: "policy",
        rawBody: !0
    }, function(t, r) {
        if (t)
            return t.statusCode && t.statusCode === 403 ? e(util$2.error(t, {
                ErrorStatus: "Access Denied"
            })) : t.statusCode && t.statusCode === 405 ? e(util$2.error(t, {
                ErrorStatus: "Method Not Allowed"
            })) : t.statusCode && t.statusCode === 404 ? e(util$2.error(t, {
                ErrorStatus: "Policy Not Found"
            })) : e(t);
        var n = {};
        try {
            n = JSON.parse(r.body)
        } catch {}
        e(null, {
            Policy: n,
            statusCode: r.statusCode,
            headers: r.headers
        })
    })
}
function deleteBucketPolicy(i, e) {
    submitRequest.call(this, {
        Action: "name/cos:DeleteBucketPolicy",
        method: "DELETE",
        Bucket: i.Bucket,
        Region: i.Region,
        headers: i.Headers,
        action: "policy"
    }, function(t, r) {
        if (t && t.statusCode === 204)
            return e(null, {
                statusCode: t.statusCode
            });
        if (t)
            return e(t);
        e(null, {
            statusCode: r.statusCode || t.statusCode,
            headers: r.headers
        })
    })
}
function putBucketTagging(i, e) {
    var t = i.Tagging || {}
      , r = t.TagSet || t.Tags || i.Tags || [];
    r = util$2.clone(util$2.isArray(r) ? r : [r]);
    var n = util$2.json2xml({
        Tagging: {
            TagSet: {
                Tag: r
            }
        }
    })
      , o = i.Headers;
    o["Content-Type"] = "application/xml",
    o["Content-MD5"] = util$2.binaryBase64(util$2.md5(n)),
    submitRequest.call(this, {
        Action: "name/cos:PutBucketTagging",
        method: "PUT",
        Bucket: i.Bucket,
        Region: i.Region,
        body: n,
        action: "tagging",
        headers: o
    }, function(a, s) {
        if (a && a.statusCode === 204)
            return e(null, {
                statusCode: a.statusCode
            });
        if (a)
            return e(a);
        e(null, {
            statusCode: s.statusCode,
            headers: s.headers
        })
    })
}
function getBucketTagging(i, e) {
    submitRequest.call(this, {
        Action: "name/cos:GetBucketTagging",
        method: "GET",
        Bucket: i.Bucket,
        Region: i.Region,
        headers: i.Headers,
        action: "tagging"
    }, function(t, r) {
        if (t) {
            if (t.statusCode === 404 && t.error && (t.error === "Not Found" || t.error.Code === "NoSuchTagSet")) {
                var n = {
                    Tags: [],
                    statusCode: t.statusCode
                };
                t.headers && (n.headers = t.headers),
                e(null, n)
            } else
                e(t);
            return
        }
        var o = [];
        try {
            o = r.Tagging.TagSet.Tag || []
        } catch {}
        o = util$2.clone(util$2.isArray(o) ? o : [o]),
        e(null, {
            Tags: o,
            statusCode: r.statusCode,
            headers: r.headers
        })
    })
}
function deleteBucketTagging(i, e) {
    submitRequest.call(this, {
        Action: "name/cos:DeleteBucketTagging",
        method: "DELETE",
        Bucket: i.Bucket,
        Region: i.Region,
        headers: i.Headers,
        action: "tagging"
    }, function(t, r) {
        if (t && t.statusCode === 204)
            return e(null, {
                statusCode: t.statusCode
            });
        if (t)
            return e(t);
        e(null, {
            statusCode: r.statusCode,
            headers: r.headers
        })
    })
}
function putBucketLifecycle(i, e) {
    var t = i.LifecycleConfiguration || {}
      , r = t.Rules || i.Rules || [];
    r = util$2.clone(r);
    var n = util$2.json2xml({
        LifecycleConfiguration: {
            Rule: r
        }
    })
      , o = i.Headers;
    o["Content-Type"] = "application/xml",
    o["Content-MD5"] = util$2.binaryBase64(util$2.md5(n)),
    submitRequest.call(this, {
        Action: "name/cos:PutBucketLifecycle",
        method: "PUT",
        Bucket: i.Bucket,
        Region: i.Region,
        body: n,
        action: "lifecycle",
        headers: o
    }, function(a, s) {
        if (a && a.statusCode === 204)
            return e(null, {
                statusCode: a.statusCode
            });
        if (a)
            return e(a);
        e(null, {
            statusCode: s.statusCode,
            headers: s.headers
        })
    })
}
function getBucketLifecycle(i, e) {
    submitRequest.call(this, {
        Action: "name/cos:GetBucketLifecycle",
        method: "GET",
        Bucket: i.Bucket,
        Region: i.Region,
        headers: i.Headers,
        action: "lifecycle"
    }, function(t, r) {
        if (t) {
            if (t.statusCode === 404 && t.error && t.error.Code === "NoSuchLifecycleConfiguration") {
                var n = {
                    Rules: [],
                    statusCode: t.statusCode
                };
                t.headers && (n.headers = t.headers),
                e(null, n)
            } else
                e(t);
            return
        }
        var o = [];
        try {
            o = r.LifecycleConfiguration.Rule || []
        } catch {}
        o = util$2.clone(util$2.isArray(o) ? o : [o]),
        e(null, {
            Rules: o,
            statusCode: r.statusCode,
            headers: r.headers
        })
    })
}
function deleteBucketLifecycle(i, e) {
    submitRequest.call(this, {
        Action: "name/cos:DeleteBucketLifecycle",
        method: "DELETE",
        Bucket: i.Bucket,
        Region: i.Region,
        headers: i.Headers,
        action: "lifecycle"
    }, function(t, r) {
        if (t && t.statusCode === 204)
            return e(null, {
                statusCode: t.statusCode
            });
        if (t)
            return e(t);
        e(null, {
            statusCode: r.statusCode,
            headers: r.headers
        })
    })
}
function putBucketVersioning(i, e) {
    if (!i.VersioningConfiguration) {
        e(util$2.error(new Error("missing param VersioningConfiguration")));
        return
    }
    var t = i.VersioningConfiguration || {}
      , r = util$2.json2xml({
        VersioningConfiguration: t
    })
      , n = i.Headers;
    n["Content-Type"] = "application/xml",
    n["Content-MD5"] = util$2.binaryBase64(util$2.md5(r)),
    submitRequest.call(this, {
        Action: "name/cos:PutBucketVersioning",
        method: "PUT",
        Bucket: i.Bucket,
        Region: i.Region,
        body: r,
        action: "versioning",
        headers: n
    }, function(o, a) {
        if (o && o.statusCode === 204)
            return e(null, {
                statusCode: o.statusCode
            });
        if (o)
            return e(o);
        e(null, {
            statusCode: a.statusCode,
            headers: a.headers
        })
    })
}
function getBucketVersioning(i, e) {
    submitRequest.call(this, {
        Action: "name/cos:GetBucketVersioning",
        method: "GET",
        Bucket: i.Bucket,
        Region: i.Region,
        headers: i.Headers,
        action: "versioning"
    }, function(t, r) {
        t || !r.VersioningConfiguration && (r.VersioningConfiguration = {}),
        e(t, r)
    })
}
function putBucketReplication(i, e) {
    var t = util$2.clone(i.ReplicationConfiguration)
      , r = util$2.json2xml({
        ReplicationConfiguration: t
    });
    r = r.replace(/<(\/?)Rules>/ig, "<$1Rule>"),
    r = r.replace(/<(\/?)Tags>/ig, "<$1Tag>");
    var n = i.Headers;
    n["Content-Type"] = "application/xml",
    n["Content-MD5"] = util$2.binaryBase64(util$2.md5(r)),
    submitRequest.call(this, {
        Action: "name/cos:PutBucketReplication",
        method: "PUT",
        Bucket: i.Bucket,
        Region: i.Region,
        body: r,
        action: "replication",
        headers: n
    }, function(o, a) {
        if (o && o.statusCode === 204)
            return e(null, {
                statusCode: o.statusCode
            });
        if (o)
            return e(o);
        e(null, {
            statusCode: a.statusCode,
            headers: a.headers
        })
    })
}
function getBucketReplication(i, e) {
    submitRequest.call(this, {
        Action: "name/cos:GetBucketReplication",
        method: "GET",
        Bucket: i.Bucket,
        Region: i.Region,
        headers: i.Headers,
        action: "replication"
    }, function(t, r) {
        if (t) {
            if (t.statusCode === 404 && t.error && (t.error === "Not Found" || t.error.Code === "ReplicationConfigurationnotFoundError")) {
                var n = {
                    ReplicationConfiguration: {
                        Rules: []
                    },
                    statusCode: t.statusCode
                };
                t.headers && (n.headers = t.headers),
                e(null, n)
            } else
                e(t);
            return
        }
        !r.ReplicationConfiguration && (r.ReplicationConfiguration = {}),
        r.ReplicationConfiguration.Rule && (r.ReplicationConfiguration.Rules = util$2.makeArray(r.ReplicationConfiguration.Rule),
        delete r.ReplicationConfiguration.Rule),
        e(t, r)
    })
}
function deleteBucketReplication(i, e) {
    submitRequest.call(this, {
        Action: "name/cos:DeleteBucketReplication",
        method: "DELETE",
        Bucket: i.Bucket,
        Region: i.Region,
        headers: i.Headers,
        action: "replication"
    }, function(t, r) {
        if (t && t.statusCode === 204)
            return e(null, {
                statusCode: t.statusCode
            });
        if (t)
            return e(t);
        e(null, {
            statusCode: r.statusCode,
            headers: r.headers
        })
    })
}
function putBucketWebsite(i, e) {
    if (!i.WebsiteConfiguration) {
        e(util$2.error(new Error("missing param WebsiteConfiguration")));
        return
    }
    var t = util$2.clone(i.WebsiteConfiguration || {})
      , r = t.RoutingRules || t.RoutingRule || [];
    r = util$2.isArray(r) ? r : [r],
    delete t.RoutingRule,
    delete t.RoutingRules,
    r.length && (t.RoutingRules = {
        RoutingRule: r
    });
    var n = util$2.json2xml({
        WebsiteConfiguration: t
    })
      , o = i.Headers;
    o["Content-Type"] = "application/xml",
    o["Content-MD5"] = util$2.binaryBase64(util$2.md5(n)),
    submitRequest.call(this, {
        Action: "name/cos:PutBucketWebsite",
        method: "PUT",
        Bucket: i.Bucket,
        Region: i.Region,
        body: n,
        action: "website",
        headers: o
    }, function(a, s) {
        if (a && a.statusCode === 204)
            return e(null, {
                statusCode: a.statusCode
            });
        if (a)
            return e(a);
        e(null, {
            statusCode: s.statusCode,
            headers: s.headers
        })
    })
}
function getBucketWebsite(i, e) {
    submitRequest.call(this, {
        Action: "name/cos:GetBucketWebsite",
        method: "GET",
        Bucket: i.Bucket,
        Region: i.Region,
        Key: i.Key,
        headers: i.Headers,
        action: "website"
    }, function(t, r) {
        if (t) {
            if (t.statusCode === 404 && t.error.Code === "NoSuchWebsiteConfiguration") {
                var n = {
                    WebsiteConfiguration: {},
                    statusCode: t.statusCode
                };
                t.headers && (n.headers = t.headers),
                e(null, n)
            } else
                e(t);
            return
        }
        var o = r.WebsiteConfiguration || {};
        if (o.RoutingRules) {
            var a = util$2.clone(o.RoutingRules.RoutingRule || []);
            a = util$2.makeArray(a),
            o.RoutingRules = a
        }
        e(null, {
            WebsiteConfiguration: o,
            statusCode: r.statusCode,
            headers: r.headers
        })
    })
}
function deleteBucketWebsite(i, e) {
    submitRequest.call(this, {
        Action: "name/cos:DeleteBucketWebsite",
        method: "DELETE",
        Bucket: i.Bucket,
        Region: i.Region,
        headers: i.Headers,
        action: "website"
    }, function(t, r) {
        if (t && t.statusCode === 204)
            return e(null, {
                statusCode: t.statusCode
            });
        if (t)
            return e(t);
        e(null, {
            statusCode: r.statusCode,
            headers: r.headers
        })
    })
}
function putBucketReferer(i, e) {
    if (!i.RefererConfiguration) {
        e(util$2.error(new Error("missing param RefererConfiguration")));
        return
    }
    var t = util$2.clone(i.RefererConfiguration || {})
      , r = t.DomainList || {}
      , n = r.Domains || r.Domain || [];
    n = util$2.isArray(n) ? n : [n],
    n.length && (t.DomainList = {
        Domain: n
    });
    var o = util$2.json2xml({
        RefererConfiguration: t
    })
      , a = i.Headers;
    a["Content-Type"] = "application/xml",
    a["Content-MD5"] = util$2.binaryBase64(util$2.md5(o)),
    submitRequest.call(this, {
        Action: "name/cos:PutBucketReferer",
        method: "PUT",
        Bucket: i.Bucket,
        Region: i.Region,
        body: o,
        action: "referer",
        headers: a
    }, function(s, l) {
        if (s && s.statusCode === 204)
            return e(null, {
                statusCode: s.statusCode
            });
        if (s)
            return e(s);
        e(null, {
            statusCode: l.statusCode,
            headers: l.headers
        })
    })
}
function getBucketReferer(i, e) {
    submitRequest.call(this, {
        Action: "name/cos:GetBucketReferer",
        method: "GET",
        Bucket: i.Bucket,
        Region: i.Region,
        Key: i.Key,
        headers: i.Headers,
        action: "referer"
    }, function(t, r) {
        if (t) {
            if (t.statusCode === 404 && t.error.Code === "NoSuchRefererConfiguration") {
                var n = {
                    WebsiteConfiguration: {},
                    statusCode: t.statusCode
                };
                t.headers && (n.headers = t.headers),
                e(null, n)
            } else
                e(t);
            return
        }
        var o = r.RefererConfiguration || {};
        if (o.DomainList) {
            var a = util$2.makeArray(o.DomainList.Domain || []);
            o.DomainList = {
                Domains: a
            }
        }
        e(null, {
            RefererConfiguration: o,
            statusCode: r.statusCode,
            headers: r.headers
        })
    })
}
function putBucketDomain(i, e) {
    var t = i.DomainConfiguration || {}
      , r = t.DomainRule || i.DomainRule || [];
    r = util$2.clone(r);
    var n = util$2.json2xml({
        DomainConfiguration: {
            DomainRule: r
        }
    })
      , o = i.Headers;
    o["Content-Type"] = "application/xml",
    o["Content-MD5"] = util$2.binaryBase64(util$2.md5(n)),
    submitRequest.call(this, {
        Action: "name/cos:PutBucketDomain",
        method: "PUT",
        Bucket: i.Bucket,
        Region: i.Region,
        body: n,
        action: "domain",
        headers: o
    }, function(a, s) {
        if (a && a.statusCode === 204)
            return e(null, {
                statusCode: a.statusCode
            });
        if (a)
            return e(a);
        e(null, {
            statusCode: s.statusCode,
            headers: s.headers
        })
    })
}
function getBucketDomain(i, e) {
    submitRequest.call(this, {
        Action: "name/cos:GetBucketDomain",
        method: "GET",
        Bucket: i.Bucket,
        Region: i.Region,
        headers: i.Headers,
        action: "domain"
    }, function(t, r) {
        if (t)
            return e(t);
        var n = [];
        try {
            n = r.DomainConfiguration.DomainRule || []
        } catch {}
        n = util$2.clone(util$2.isArray(n) ? n : [n]),
        e(null, {
            DomainRule: n,
            statusCode: r.statusCode,
            headers: r.headers
        })
    })
}
function deleteBucketDomain(i, e) {
    submitRequest.call(this, {
        Action: "name/cos:DeleteBucketDomain",
        method: "DELETE",
        Bucket: i.Bucket,
        Region: i.Region,
        headers: i.Headers,
        action: "domain"
    }, function(t, r) {
        if (t && t.statusCode === 204)
            return e(null, {
                statusCode: t.statusCode
            });
        if (t)
            return e(t);
        e(null, {
            statusCode: r.statusCode,
            headers: r.headers
        })
    })
}
function putBucketOrigin(i, e) {
    var t = i.OriginConfiguration || {}
      , r = t.OriginRule || i.OriginRule || [];
    r = util$2.clone(r);
    var n = util$2.json2xml({
        OriginConfiguration: {
            OriginRule: r
        }
    })
      , o = i.Headers;
    o["Content-Type"] = "application/xml",
    o["Content-MD5"] = util$2.binaryBase64(util$2.md5(n)),
    submitRequest.call(this, {
        Action: "name/cos:PutBucketOrigin",
        method: "PUT",
        Bucket: i.Bucket,
        Region: i.Region,
        body: n,
        action: "origin",
        headers: o
    }, function(a, s) {
        if (a && a.statusCode === 204)
            return e(null, {
                statusCode: a.statusCode
            });
        if (a)
            return e(a);
        e(null, {
            statusCode: s.statusCode,
            headers: s.headers
        })
    })
}
function getBucketOrigin(i, e) {
    submitRequest.call(this, {
        Action: "name/cos:GetBucketOrigin",
        method: "GET",
        Bucket: i.Bucket,
        Region: i.Region,
        headers: i.Headers,
        action: "origin"
    }, function(t, r) {
        if (t)
            return e(t);
        var n = [];
        try {
            n = r.OriginConfiguration.OriginRule || []
        } catch {}
        n = util$2.clone(util$2.isArray(n) ? n : [n]),
        e(null, {
            OriginRule: n,
            statusCode: r.statusCode,
            headers: r.headers
        })
    })
}
function deleteBucketOrigin(i, e) {
    submitRequest.call(this, {
        Action: "name/cos:DeleteBucketOrigin",
        method: "DELETE",
        Bucket: i.Bucket,
        Region: i.Region,
        headers: i.Headers,
        action: "origin"
    }, function(t, r) {
        if (t && t.statusCode === 204)
            return e(null, {
                statusCode: t.statusCode
            });
        if (t)
            return e(t);
        e(null, {
            statusCode: r.statusCode,
            headers: r.headers
        })
    })
}
function putBucketLogging(i, e) {
    var t = util$2.json2xml({
        BucketLoggingStatus: i.BucketLoggingStatus || ""
    })
      , r = i.Headers;
    r["Content-Type"] = "application/xml",
    r["Content-MD5"] = util$2.binaryBase64(util$2.md5(t)),
    submitRequest.call(this, {
        Action: "name/cos:PutBucketLogging",
        method: "PUT",
        Bucket: i.Bucket,
        Region: i.Region,
        body: t,
        action: "logging",
        headers: r
    }, function(n, o) {
        if (n && n.statusCode === 204)
            return e(null, {
                statusCode: n.statusCode
            });
        if (n)
            return e(n);
        e(null, {
            statusCode: o.statusCode,
            headers: o.headers
        })
    })
}
function getBucketLogging(i, e) {
    submitRequest.call(this, {
        Action: "name/cos:GetBucketLogging",
        method: "GET",
        Bucket: i.Bucket,
        Region: i.Region,
        headers: i.Headers,
        action: "logging"
    }, function(t, r) {
        if (t)
            return e(t);
        e(null, {
            BucketLoggingStatus: r.BucketLoggingStatus,
            statusCode: r.statusCode,
            headers: r.headers
        })
    })
}
function putBucketInventory(i, e) {
    var t = util$2.clone(i.InventoryConfiguration);
    if (t.OptionalFields) {
        var r = t.OptionalFields || [];
        t.OptionalFields = {
            Field: r
        }
    }
    if (t.Destination && t.Destination.COSBucketDestination && t.Destination.COSBucketDestination.Encryption) {
        var n = t.Destination.COSBucketDestination.Encryption;
        Object.keys(n).indexOf("SSECOS") > -1 && (n["SSE-COS"] = n.SSECOS,
        delete n.SSECOS)
    }
    var o = util$2.json2xml({
        InventoryConfiguration: t
    })
      , a = i.Headers;
    a["Content-Type"] = "application/xml",
    a["Content-MD5"] = util$2.binaryBase64(util$2.md5(o)),
    submitRequest.call(this, {
        Action: "name/cos:PutBucketInventory",
        method: "PUT",
        Bucket: i.Bucket,
        Region: i.Region,
        body: o,
        action: "inventory",
        qs: {
            id: i.Id
        },
        headers: a
    }, function(s, l) {
        if (s && s.statusCode === 204)
            return e(null, {
                statusCode: s.statusCode
            });
        if (s)
            return e(s);
        e(null, {
            statusCode: l.statusCode,
            headers: l.headers
        })
    })
}
function getBucketInventory(i, e) {
    submitRequest.call(this, {
        Action: "name/cos:GetBucketInventory",
        method: "GET",
        Bucket: i.Bucket,
        Region: i.Region,
        headers: i.Headers,
        action: "inventory",
        qs: {
            id: i.Id
        }
    }, function(t, r) {
        if (t)
            return e(t);
        var n = r.InventoryConfiguration;
        if (n && n.OptionalFields && n.OptionalFields.Field) {
            var o = n.OptionalFields.Field;
            util$2.isArray(o) || (o = [o]),
            n.OptionalFields = o
        }
        if (n.Destination && n.Destination.COSBucketDestination && n.Destination.COSBucketDestination.Encryption) {
            var a = n.Destination.COSBucketDestination.Encryption;
            Object.keys(a).indexOf("SSE-COS") > -1 && (a.SSECOS = a["SSE-COS"],
            delete a["SSE-COS"])
        }
        e(null, {
            InventoryConfiguration: n,
            statusCode: r.statusCode,
            headers: r.headers
        })
    })
}
function listBucketInventory(i, e) {
    submitRequest.call(this, {
        Action: "name/cos:ListBucketInventory",
        method: "GET",
        Bucket: i.Bucket,
        Region: i.Region,
        headers: i.Headers,
        action: "inventory",
        qs: {
            "continuation-token": i.ContinuationToken
        }
    }, function(t, r) {
        if (t)
            return e(t);
        var n = r.ListInventoryConfigurationResult
          , o = n.InventoryConfiguration || [];
        o = util$2.isArray(o) ? o : [o],
        delete n.InventoryConfiguration,
        util$2.each(o, function(a) {
            if (a && a.OptionalFields && a.OptionalFields.Field) {
                var s = a.OptionalFields.Field;
                util$2.isArray(s) || (s = [s]),
                a.OptionalFields = s
            }
            if (a.Destination && a.Destination.COSBucketDestination && a.Destination.COSBucketDestination.Encryption) {
                var l = a.Destination.COSBucketDestination.Encryption;
                Object.keys(l).indexOf("SSE-COS") > -1 && (l.SSECOS = l["SSE-COS"],
                delete l["SSE-COS"])
            }
        }),
        n.InventoryConfigurations = o,
        util$2.extend(n, {
            statusCode: r.statusCode,
            headers: r.headers
        }),
        e(null, n)
    })
}
function deleteBucketInventory(i, e) {
    submitRequest.call(this, {
        Action: "name/cos:DeleteBucketInventory",
        method: "DELETE",
        Bucket: i.Bucket,
        Region: i.Region,
        headers: i.Headers,
        action: "inventory",
        qs: {
            id: i.Id
        }
    }, function(t, r) {
        if (t && t.statusCode === 204)
            return e(null, {
                statusCode: t.statusCode
            });
        if (t)
            return e(t);
        e(null, {
            statusCode: r.statusCode,
            headers: r.headers
        })
    })
}
function putBucketAccelerate(i, e) {
    if (!i.AccelerateConfiguration) {
        e(util$2.error(new Error("missing param AccelerateConfiguration")));
        return
    }
    var t = {
        AccelerateConfiguration: i.AccelerateConfiguration || {}
    }
      , r = util$2.json2xml(t)
      , n = {};
    n["Content-Type"] = "application/xml",
    n["Content-MD5"] = util$2.binaryBase64(util$2.md5(r)),
    submitRequest.call(this, {
        Action: "name/cos:PutBucketAccelerate",
        method: "PUT",
        Bucket: i.Bucket,
        Region: i.Region,
        body: r,
        action: "accelerate",
        headers: n
    }, function(o, a) {
        if (o)
            return e(o);
        e(null, {
            statusCode: a.statusCode,
            headers: a.headers
        })
    })
}
function getBucketAccelerate(i, e) {
    submitRequest.call(this, {
        Action: "name/cos:GetBucketAccelerate",
        method: "GET",
        Bucket: i.Bucket,
        Region: i.Region,
        action: "accelerate"
    }, function(t, r) {
        t || !r.AccelerateConfiguration && (r.AccelerateConfiguration = {}),
        e(t, r)
    })
}
function putBucketEncryption(i, e) {
    var t = i.ServerSideEncryptionConfiguration || {}
      , r = t.Rule || t.Rules || []
      , n = util$2.json2xml({
        ServerSideEncryptionConfiguration: {
            Rule: r
        }
    })
      , o = i.Headers;
    o["Content-Type"] = "application/xml",
    o["Content-MD5"] = util$2.binaryBase64(util$2.md5(n)),
    submitRequest.call(this, {
        Action: "name/cos:PutBucketEncryption",
        method: "PUT",
        Bucket: i.Bucket,
        Region: i.Region,
        body: n,
        action: "encryption",
        headers: o
    }, function(a, s) {
        if (a && a.statusCode === 204)
            return e(null, {
                statusCode: a.statusCode
            });
        if (a)
            return e(a);
        e(null, {
            statusCode: s.statusCode,
            headers: s.headers
        })
    })
}
function getBucketEncryption(i, e) {
    submitRequest.call(this, {
        Action: "name/cos:GetBucketEncryption",
        method: "GET",
        Bucket: i.Bucket,
        Region: i.Region,
        headers: i.Headers,
        action: "encryption"
    }, function(t, r) {
        if (t) {
            if (t.statusCode === 404 && t.code === "NoSuchEncryptionConfiguration") {
                var n = {
                    EncryptionConfiguration: {
                        Rules: []
                    },
                    statusCode: t.statusCode
                };
                t.headers && (n.headers = t.headers),
                e(null, n)
            } else
                e(t);
            return
        }
        var o = util$2.makeArray(r.EncryptionConfiguration && r.EncryptionConfiguration.Rule || []);
        r.EncryptionConfiguration = {
            Rules: o
        },
        e(t, r)
    })
}
function deleteBucketEncryption(i, e) {
    submitRequest.call(this, {
        Action: "name/cos:DeleteBucketReplication",
        method: "DELETE",
        Bucket: i.Bucket,
        Region: i.Region,
        headers: i.Headers,
        action: "encryption"
    }, function(t, r) {
        if (t && t.statusCode === 204)
            return e(null, {
                statusCode: t.statusCode
            });
        if (t)
            return e(t);
        e(null, {
            statusCode: r.statusCode,
            headers: r.headers
        })
    })
}
function headObject(i, e) {
    submitRequest.call(this, {
        Action: "name/cos:HeadObject",
        method: "HEAD",
        Bucket: i.Bucket,
        Region: i.Region,
        Key: i.Key,
        VersionId: i.VersionId,
        headers: i.Headers
    }, function(t, r) {
        if (t) {
            var n = t.statusCode;
            return i.Headers["If-Modified-Since"] && n && n === 304 ? e(null, {
                NotModified: !0,
                statusCode: n
            }) : e(t)
        }
        r.ETag = util$2.attr(r.headers, "etag", ""),
        e(null, r)
    })
}
function listObjectVersions(i, e) {
    var t = {};
    t.prefix = i.Prefix || "",
    t.delimiter = i.Delimiter,
    t["key-marker"] = i.KeyMarker,
    t["version-id-marker"] = i.VersionIdMarker,
    t["max-keys"] = i.MaxKeys,
    t["encoding-type"] = i.EncodingType,
    submitRequest.call(this, {
        Action: "name/cos:GetBucketObjectVersions",
        ResourceKey: t.prefix,
        method: "GET",
        Bucket: i.Bucket,
        Region: i.Region,
        headers: i.Headers,
        qs: t,
        action: "versions"
    }, function(r, n) {
        if (r)
            return e(r);
        var o = n.ListVersionsResult || {}
          , a = o.DeleteMarker || [];
        a = util$2.isArray(a) ? a : [a];
        var s = o.Version || [];
        s = util$2.isArray(s) ? s : [s];
        var l = util$2.clone(o);
        delete l.DeleteMarker,
        delete l.Version,
        util$2.extend(l, {
            DeleteMarkers: a,
            Versions: s,
            statusCode: n.statusCode,
            headers: n.headers
        }),
        e(null, l)
    })
}
function getObject(i, e) {
    var t = i.Query || {}
      , r = i.QueryString || ""
      , n = util$2.throttleOnProgress.call(this, 0, i.onProgress);
    t["response-content-type"] = i.ResponseContentType,
    t["response-content-language"] = i.ResponseContentLanguage,
    t["response-expires"] = i.ResponseExpires,
    t["response-cache-control"] = i.ResponseCacheControl,
    t["response-content-disposition"] = i.ResponseContentDisposition,
    t["response-content-encoding"] = i.ResponseContentEncoding,
    submitRequest.call(this, {
        Action: "name/cos:GetObject",
        method: "GET",
        Bucket: i.Bucket,
        Region: i.Region,
        Key: i.Key,
        VersionId: i.VersionId,
        DataType: i.DataType,
        headers: i.Headers,
        qs: t,
        qsStr: r,
        rawBody: !0,
        onDownloadProgress: n
    }, function(o, a) {
        if (n(null, !0),
        o) {
            var s = o.statusCode;
            return i.Headers["If-Modified-Since"] && s && s === 304 ? e(null, {
                NotModified: !0
            }) : e(o)
        }
        e(null, {
            Body: a.body,
            ETag: util$2.attr(a.headers, "etag", ""),
            statusCode: a.statusCode,
            headers: a.headers
        })
    })
}
function putObject(i, e) {
    var t = this
      , r = i.ContentLength
      , n = util$2.throttleOnProgress.call(t, r, i.onProgress)
      , o = i.Headers;
    !o["Cache-Control"] && !o["cache-control"] && (o["Cache-Control"] = ""),
    !o["Content-Type"] && !o["content-type"] && (o["Content-Type"] = i.Body && i.Body.type || "");
    var a = i.UploadAddMetaMd5 || t.options.UploadAddMetaMd5 || t.options.UploadCheckContentMd5;
    util$2.getBodyMd5(a, i.Body, function(s) {
        s && (t.options.UploadCheckContentMd5 && (o["Content-MD5"] = util$2.binaryBase64(s)),
        (i.UploadAddMetaMd5 || t.options.UploadAddMetaMd5) && (o["x-cos-meta-md5"] = s)),
        i.ContentLength !== void 0 && (o["Content-Length"] = i.ContentLength),
        n(null, !0),
        submitRequest.call(t, {
            Action: "name/cos:PutObject",
            TaskId: i.TaskId,
            method: "PUT",
            Bucket: i.Bucket,
            Region: i.Region,
            Key: i.Key,
            headers: i.Headers,
            qs: i.Query,
            body: i.Body,
            onProgress: n
        }, function(l, u) {
            if (l)
                return n(null, !0),
                e(l);
            n({
                loaded: r,
                total: r
            }, !0);
            var c = getUrl({
                ForcePathStyle: t.options.ForcePathStyle,
                protocol: t.options.Protocol,
                domain: t.options.Domain,
                bucket: i.Bucket,
                region: t.options.UseAccelerate ? "accelerate" : i.Region,
                object: i.Key
            });
            c = c.substr(c.indexOf("://") + 3),
            u.Location = c,
            u.ETag = util$2.attr(u.headers, "etag", ""),
            e(null, u)
        })
    }, i.onHashProgress)
}
function deleteObject(i, e) {
    submitRequest.call(this, {
        Action: "name/cos:DeleteObject",
        method: "DELETE",
        Bucket: i.Bucket,
        Region: i.Region,
        Key: i.Key,
        headers: i.Headers,
        VersionId: i.VersionId,
        action: i.Recursive ? "recursive" : ""
    }, function(t, r) {
        if (t) {
            var n = t.statusCode;
            return n && n === 404 ? e(null, {
                BucketNotFound: !0,
                statusCode: n
            }) : e(t)
        }
        e(null, {
            statusCode: r.statusCode,
            headers: r.headers
        })
    })
}
function getObjectAcl(i, e) {
    submitRequest.call(this, {
        Action: "name/cos:GetObjectACL",
        method: "GET",
        Bucket: i.Bucket,
        Region: i.Region,
        Key: i.Key,
        headers: i.Headers,
        action: "acl"
    }, function(t, r) {
        if (t)
            return e(t);
        var n = r.AccessControlPolicy || {}
          , o = n.Owner || {}
          , a = n.AccessControlList && n.AccessControlList.Grant || [];
        a = util$2.isArray(a) ? a : [a];
        var s = decodeAcl(n);
        delete s.GrantWrite,
        r.headers && r.headers["x-cos-acl"] && (s.ACL = r.headers["x-cos-acl"]),
        s = util$2.extend(s, {
            Owner: o,
            Grants: a,
            statusCode: r.statusCode,
            headers: r.headers
        }),
        e(null, s)
    })
}
function putObjectAcl(i, e) {
    var t = i.Headers
      , r = "";
    if (i.AccessControlPolicy) {
        var n = util$2.clone(i.AccessControlPolicy || {})
          , o = n.Grants || n.Grant;
        o = util$2.isArray(o) ? o : [o],
        delete n.Grant,
        delete n.Grants,
        n.AccessControlList = {
            Grant: o
        },
        r = util$2.json2xml({
            AccessControlPolicy: n
        }),
        t["Content-Type"] = "application/xml",
        t["Content-MD5"] = util$2.binaryBase64(util$2.md5(r))
    }
    util$2.each(t, function(a, s) {
        s.indexOf("x-cos-grant-") === 0 && (t[s] = uniqGrant(t[s]))
    }),
    submitRequest.call(this, {
        Action: "name/cos:PutObjectACL",
        method: "PUT",
        Bucket: i.Bucket,
        Region: i.Region,
        Key: i.Key,
        action: "acl",
        headers: t,
        body: r
    }, function(a, s) {
        if (a)
            return e(a);
        e(null, {
            statusCode: s.statusCode,
            headers: s.headers
        })
    })
}
function optionsObject(i, e) {
    var t = i.Headers;
    t.Origin = i.Origin,
    t["Access-Control-Request-Method"] = i.AccessControlRequestMethod,
    t["Access-Control-Request-Headers"] = i.AccessControlRequestHeaders,
    submitRequest.call(this, {
        Action: "name/cos:OptionsObject",
        method: "OPTIONS",
        Bucket: i.Bucket,
        Region: i.Region,
        Key: i.Key,
        headers: t
    }, function(r, n) {
        if (r)
            return r.statusCode && r.statusCode === 403 ? e(null, {
                OptionsForbidden: !0,
                statusCode: r.statusCode
            }) : e(r);
        var o = n.headers || {};
        e(null, {
            AccessControlAllowOrigin: o["access-control-allow-origin"],
            AccessControlAllowMethods: o["access-control-allow-methods"],
            AccessControlAllowHeaders: o["access-control-allow-headers"],
            AccessControlExposeHeaders: o["access-control-expose-headers"],
            AccessControlMaxAge: o["access-control-max-age"],
            statusCode: n.statusCode,
            headers: n.headers
        })
    })
}
function putObjectCopy(i, e) {
    var t = this
      , r = i.Headers;
    !r["Cache-Control"] && !r["cache-control"] && (r["Cache-Control"] = "");
    var n = i.CopySource || ""
      , o = util$2.getSourceParams.call(this, n);
    if (!o) {
        e(util$2.error(new Error("CopySource format error")));
        return
    }
    var a = o[1]
      , s = o[3]
      , l = decodeURIComponent(o[4]);
    submitRequest.call(this, {
        Scope: [{
            action: "name/cos:GetObject",
            bucket: a,
            region: s,
            prefix: l
        }, {
            action: "name/cos:PutObject",
            bucket: i.Bucket,
            region: i.Region,
            prefix: i.Key
        }],
        method: "PUT",
        Bucket: i.Bucket,
        Region: i.Region,
        Key: i.Key,
        VersionId: i.VersionId,
        headers: i.Headers
    }, function(u, c) {
        if (u)
            return e(u);
        var h = util$2.clone(c.CopyObjectResult || {})
          , f = getUrl({
            ForcePathStyle: t.options.ForcePathStyle,
            protocol: t.options.Protocol,
            domain: t.options.Domain,
            bucket: i.Bucket,
            region: i.Region,
            object: i.Key,
            isLocation: !0
        });
        util$2.extend(h, {
            Location: f,
            statusCode: c.statusCode,
            headers: c.headers
        }),
        e(null, h)
    })
}
function uploadPartCopy(i, e) {
    var t = i.CopySource || ""
      , r = util$2.getSourceParams.call(this, t);
    if (!r) {
        e(util$2.error(new Error("CopySource format error")));
        return
    }
    var n = r[1]
      , o = r[3]
      , a = decodeURIComponent(r[4]);
    submitRequest.call(this, {
        Scope: [{
            action: "name/cos:GetObject",
            bucket: n,
            region: o,
            prefix: a
        }, {
            action: "name/cos:PutObject",
            bucket: i.Bucket,
            region: i.Region,
            prefix: i.Key
        }],
        method: "PUT",
        Bucket: i.Bucket,
        Region: i.Region,
        Key: i.Key,
        VersionId: i.VersionId,
        qs: {
            partNumber: i.PartNumber,
            uploadId: i.UploadId
        },
        headers: i.Headers
    }, function(s, l) {
        if (s)
            return e(s);
        var u = util$2.clone(l.CopyPartResult || {});
        util$2.extend(u, {
            statusCode: l.statusCode,
            headers: l.headers
        }),
        e(null, u)
    })
}
function deleteMultipleObject(i, e) {
    var t = i.Objects || []
      , r = i.Quiet;
    t = util$2.isArray(t) ? t : [t];
    var n = util$2.json2xml({
        Delete: {
            Object: t,
            Quiet: r || !1
        }
    })
      , o = i.Headers;
    o["Content-Type"] = "application/xml",
    o["Content-MD5"] = util$2.binaryBase64(util$2.md5(n));
    var a = util$2.map(t, function(s) {
        return {
            action: "name/cos:DeleteObject",
            bucket: i.Bucket,
            region: i.Region,
            prefix: s.Key
        }
    });
    submitRequest.call(this, {
        Scope: a,
        method: "POST",
        Bucket: i.Bucket,
        Region: i.Region,
        body: n,
        action: "delete",
        headers: o
    }, function(s, l) {
        if (s)
            return e(s);
        var u = l.DeleteResult || {}
          , c = u.Deleted || []
          , h = u.Error || [];
        c = util$2.isArray(c) ? c : [c],
        h = util$2.isArray(h) ? h : [h];
        var f = util$2.clone(u);
        util$2.extend(f, {
            Error: h,
            Deleted: c,
            statusCode: l.statusCode,
            headers: l.headers
        }),
        e(null, f)
    })
}
function restoreObject(i, e) {
    var t = i.Headers;
    if (!i.RestoreRequest) {
        e(util$2.error(new Error("missing param RestoreRequest")));
        return
    }
    var r = i.RestoreRequest || {}
      , n = util$2.json2xml({
        RestoreRequest: r
    });
    t["Content-Type"] = "application/xml",
    t["Content-MD5"] = util$2.binaryBase64(util$2.md5(n)),
    submitRequest.call(this, {
        Action: "name/cos:RestoreObject",
        method: "POST",
        Bucket: i.Bucket,
        Region: i.Region,
        Key: i.Key,
        VersionId: i.VersionId,
        body: n,
        action: "restore",
        headers: t
    }, e)
}
function putObjectTagging(i, e) {
    var t = i.Tagging || {}
      , r = t.TagSet || t.Tags || i.Tags || [];
    r = util$2.clone(util$2.isArray(r) ? r : [r]);
    var n = util$2.json2xml({
        Tagging: {
            TagSet: {
                Tag: r
            }
        }
    })
      , o = i.Headers;
    o["Content-Type"] = "application/xml",
    o["Content-MD5"] = util$2.binaryBase64(util$2.md5(n)),
    submitRequest.call(this, {
        Action: "name/cos:PutObjectTagging",
        method: "PUT",
        Bucket: i.Bucket,
        Key: i.Key,
        Region: i.Region,
        body: n,
        action: "tagging",
        headers: o,
        VersionId: i.VersionId
    }, function(a, s) {
        if (a && a.statusCode === 204)
            return e(null, {
                statusCode: a.statusCode
            });
        if (a)
            return e(a);
        e(null, {
            statusCode: s.statusCode,
            headers: s.headers
        })
    })
}
function getObjectTagging(i, e) {
    submitRequest.call(this, {
        Action: "name/cos:GetObjectTagging",
        method: "GET",
        Key: i.Key,
        Bucket: i.Bucket,
        Region: i.Region,
        headers: i.Headers,
        action: "tagging",
        VersionId: i.VersionId
    }, function(t, r) {
        if (t) {
            if (t.statusCode === 404 && t.error && (t.error === "Not Found" || t.error.Code === "NoSuchTagSet")) {
                var n = {
                    Tags: [],
                    statusCode: t.statusCode
                };
                t.headers && (n.headers = t.headers),
                e(null, n)
            } else
                e(t);
            return
        }
        var o = [];
        try {
            o = r.Tagging.TagSet.Tag || []
        } catch {}
        o = util$2.clone(util$2.isArray(o) ? o : [o]),
        e(null, {
            Tags: o,
            statusCode: r.statusCode,
            headers: r.headers
        })
    })
}
function deleteObjectTagging(i, e) {
    submitRequest.call(this, {
        Action: "name/cos:DeleteObjectTagging",
        method: "DELETE",
        Bucket: i.Bucket,
        Region: i.Region,
        Key: i.Key,
        headers: i.Headers,
        action: "tagging",
        VersionId: i.VersionId
    }, function(t, r) {
        if (t && t.statusCode === 204)
            return e(null, {
                statusCode: t.statusCode
            });
        if (t)
            return e(t);
        e(null, {
            statusCode: r.statusCode,
            headers: r.headers
        })
    })
}
function selectObjectContent(i, e) {
    var t = i.SelectType;
    if (!t)
        return e(util$2.error(new Error("missing param SelectType")));
    var r = i.SelectRequest || {}
      , n = util$2.json2xml({
        SelectRequest: r
    })
      , o = i.Headers;
    o["Content-Type"] = "application/xml",
    o["Content-MD5"] = util$2.binaryBase64(util$2.md5(n)),
    submitRequest.call(this, {
        Action: "name/cos:GetObject",
        method: "POST",
        Bucket: i.Bucket,
        Region: i.Region,
        Key: i.Key,
        headers: i.Headers,
        action: "select",
        qs: {
            "select-type": i.SelectType
        },
        VersionId: i.VersionId,
        body: n,
        DataType: "arraybuffer",
        rawBody: !0
    }, function(a, s) {
        if (a && a.statusCode === 204)
            return e(null, {
                statusCode: a.statusCode
            });
        if (a)
            return e(a);
        var l = util$2.parseSelectPayload(s.body);
        e(null, {
            statusCode: s.statusCode,
            headers: s.headers,
            Body: l.body,
            Payload: l.payload
        })
    })
}
function multipartInit(i, e) {
    var t = this
      , r = i.Headers;
    !r["Cache-Control"] && !r["cache-control"] && (r["Cache-Control"] = ""),
    !r["Content-Type"] && !r["content-type"] && (r["Content-Type"] = i.Body && i.Body.type || ""),
    util$2.getBodyMd5(i.Body && (i.UploadAddMetaMd5 || t.options.UploadAddMetaMd5), i.Body, function(n) {
        n && (i.Headers["x-cos-meta-md5"] = n),
        submitRequest.call(t, {
            Action: "name/cos:InitiateMultipartUpload",
            method: "POST",
            Bucket: i.Bucket,
            Region: i.Region,
            Key: i.Key,
            action: "uploads",
            headers: i.Headers,
            qs: i.Query
        }, function(o, a) {
            if (o)
                return e(o);
            if (a = util$2.clone(a || {}),
            a && a.InitiateMultipartUploadResult)
                return e(null, util$2.extend(a.InitiateMultipartUploadResult, {
                    statusCode: a.statusCode,
                    headers: a.headers
                }));
            e(null, a)
        })
    }, i.onHashProgress)
}
function multipartUpload(i, e) {
    var t = this;
    util$2.getFileSize("multipartUpload", i, function() {
        util$2.getBodyMd5(t.options.UploadCheckContentMd5, i.Body, function(r) {
            r && (i.Headers["Content-MD5"] = util$2.binaryBase64(r)),
            submitRequest.call(t, {
                Action: "name/cos:UploadPart",
                TaskId: i.TaskId,
                method: "PUT",
                Bucket: i.Bucket,
                Region: i.Region,
                Key: i.Key,
                qs: {
                    partNumber: i.PartNumber,
                    uploadId: i.UploadId
                },
                headers: i.Headers,
                onProgress: i.onProgress,
                body: i.Body || null
            }, function(n, o) {
                if (n)
                    return e(n);
                e(null, {
                    ETag: util$2.attr(o.headers, "etag", ""),
                    statusCode: o.statusCode,
                    headers: o.headers
                })
            })
        })
    })
}
function multipartComplete(i, e) {
    for (var t = this, r = i.UploadId, n = i.Parts, o = 0, a = n.length; o < a; o++)
        n[o].ETag && n[o].ETag.indexOf('"') === 0 || (n[o].ETag = '"' + n[o].ETag + '"');
    var s = util$2.json2xml({
        CompleteMultipartUpload: {
            Part: n
        }
    });
    s = s.replace(/\n\s*/g, "");
    var l = i.Headers;
    l["Content-Type"] = "application/xml",
    l["Content-MD5"] = util$2.binaryBase64(util$2.md5(s)),
    submitRequest.call(this, {
        Action: "name/cos:CompleteMultipartUpload",
        method: "POST",
        Bucket: i.Bucket,
        Region: i.Region,
        Key: i.Key,
        qs: {
            uploadId: r
        },
        body: s,
        headers: l
    }, function(u, c) {
        if (u)
            return e(u);
        var h = getUrl({
            ForcePathStyle: t.options.ForcePathStyle,
            protocol: t.options.Protocol,
            domain: t.options.Domain,
            bucket: i.Bucket,
            region: i.Region,
            object: i.Key,
            isLocation: !0
        })
          , f = c.CompleteMultipartUploadResult || {};
        f.ProcessResults && f && f.ProcessResults && (f.UploadResult = {
            OriginalInfo: {
                Key: f.Key,
                Location: h,
                ETag: f.ETag,
                ImageInfo: f.ImageInfo
            },
            ProcessResults: f.ProcessResults
        },
        delete f.ImageInfo,
        delete f.ProcessResults);
        var d = util$2.extend(f, {
            Location: h,
            statusCode: c.statusCode,
            headers: c.headers
        });
        e(null, d)
    })
}
function multipartList(i, e) {
    var t = {};
    t.delimiter = i.Delimiter,
    t["encoding-type"] = i.EncodingType,
    t.prefix = i.Prefix || "",
    t["max-uploads"] = i.MaxUploads,
    t["key-marker"] = i.KeyMarker,
    t["upload-id-marker"] = i.UploadIdMarker,
    t = util$2.clearKey(t),
    submitRequest.call(this, {
        Action: "name/cos:ListMultipartUploads",
        ResourceKey: t.prefix,
        method: "GET",
        Bucket: i.Bucket,
        Region: i.Region,
        headers: i.Headers,
        qs: t,
        action: "uploads"
    }, function(r, n) {
        if (r)
            return e(r);
        if (n && n.ListMultipartUploadsResult) {
            var o = n.ListMultipartUploadsResult.Upload || [];
            o = util$2.isArray(o) ? o : [o],
            n.ListMultipartUploadsResult.Upload = o
        }
        var a = util$2.clone(n.ListMultipartUploadsResult || {});
        util$2.extend(a, {
            statusCode: n.statusCode,
            headers: n.headers
        }),
        e(null, a)
    })
}
function multipartListPart(i, e) {
    var t = {};
    t.uploadId = i.UploadId,
    t["encoding-type"] = i.EncodingType,
    t["max-parts"] = i.MaxParts,
    t["part-number-marker"] = i.PartNumberMarker,
    submitRequest.call(this, {
        Action: "name/cos:ListParts",
        method: "GET",
        Bucket: i.Bucket,
        Region: i.Region,
        Key: i.Key,
        headers: i.Headers,
        qs: t
    }, function(r, n) {
        if (r)
            return e(r);
        var o = n.ListPartsResult || {}
          , a = o.Part || [];
        a = util$2.isArray(a) ? a : [a],
        o.Part = a;
        var s = util$2.clone(o);
        util$2.extend(s, {
            statusCode: n.statusCode,
            headers: n.headers
        }),
        e(null, s)
    })
}
function multipartAbort(i, e) {
    var t = {};
    t.uploadId = i.UploadId,
    submitRequest.call(this, {
        Action: "name/cos:AbortMultipartUpload",
        method: "DELETE",
        Bucket: i.Bucket,
        Region: i.Region,
        Key: i.Key,
        headers: i.Headers,
        qs: t
    }, function(r, n) {
        if (r)
            return e(r);
        e(null, {
            statusCode: n.statusCode,
            headers: n.headers
        })
    })
}
function request(i, e) {
    submitRequest.call(this, {
        method: i.Method,
        Bucket: i.Bucket,
        Region: i.Region,
        Key: i.Key,
        action: i.Action,
        headers: i.Headers,
        qs: i.Query,
        body: i.Body,
        Url: i.Url,
        rawBody: i.RawBody,
        DataType: i.DataType
    }, function(t, r) {
        if (t)
            return e(t);
        r && r.body && (r.Body = r.body,
        delete r.body),
        e(t, r)
    })
}
function appendObject(i, e) {
    var t = i.Headers;
    !t["Cache-Control"] && !t["cache-control"] && (t["Cache-Control"] = ""),
    !t["Content-Type"] && !t["content-type"] && (t["Content-Type"] = i.Body && i.Body.type || ""),
    submitRequest.call(this, {
        Action: "name/cos:AppendObject",
        method: "POST",
        Bucket: i.Bucket,
        Region: i.Region,
        action: "append",
        Key: i.Key,
        body: i.Body,
        qs: {
            position: i.Position
        },
        headers: i.Headers
    }, function(r, n) {
        if (r)
            return e(r);
        e(null, n)
    })
}
function getAuth(i) {
    var e = this;
    return util$2.getAuth({
        SecretId: i.SecretId || this.options.SecretId || "",
        SecretKey: i.SecretKey || this.options.SecretKey || "",
        Bucket: i.Bucket,
        Region: i.Region,
        Method: i.Method,
        Key: i.Key,
        Query: i.Query,
        Headers: i.Headers,
        Expires: i.Expires,
        UseRawKey: e.options.UseRawKey,
        SystemClockOffset: e.options.SystemClockOffset
    })
}
function getObjectUrl(i, e) {
    var t = this
      , r = getUrl({
        ForcePathStyle: t.options.ForcePathStyle,
        protocol: i.Protocol || t.options.Protocol,
        domain: i.Domain || t.options.Domain,
        bucket: i.Bucket,
        region: i.Region,
        object: i.Key
    })
      , n = "";
    i.Query && (n += util$2.obj2str(i.Query)),
    i.QueryString && (n += (n ? "&" : "") + i.QueryString);
    var o = r;
    if (i.Sign !== void 0 && !i.Sign)
        return n && (o += "?" + n),
        e(null, {
            Url: o
        }),
        o;
    var a = getSignHost.call(this, {
        Bucket: i.Bucket,
        Region: i.Region,
        Url: r
    })
      , s = getAuthorizationAsync.call(this, {
        Action: (i.Method || "").toUpperCase() === "PUT" ? "name/cos:PutObject" : "name/cos:GetObject",
        Bucket: i.Bucket || "",
        Region: i.Region || "",
        Method: i.Method || "get",
        Key: i.Key,
        Expires: i.Expires,
        Headers: i.Headers,
        Query: i.Query,
        SignHost: a
    }, function(l, u) {
        if (!!e) {
            if (l) {
                e(l);
                return
            }
            var c = function(f) {
                var d = f.match(/q-url-param-list.*?(?=&)/g)[0]
                  , _ = "q-url-param-list=" + encodeURIComponent(d.replace(/q-url-param-list=/, "")).toLowerCase()
                  , g = new RegExp(d,"g")
                  , m = f.replace(g, _);
                return m
            }
              , h = r;
            h += "?" + (u.Authorization.indexOf("q-signature") > -1 ? c(u.Authorization) : "sign=" + encodeURIComponent(u.Authorization)),
            u.SecurityToken && (h += "&x-cos-security-token=" + u.SecurityToken),
            u.ClientIP && (h += "&clientIP=" + u.ClientIP),
            u.ClientUA && (h += "&clientUA=" + u.ClientUA),
            u.Token && (h += "&token=" + u.Token),
            n && (h += "&" + n),
            setTimeout(function() {
                e(null, {
                    Url: h
                })
            })
        }
    });
    return s ? (o += "?" + s.Authorization + (s.SecurityToken ? "&x-cos-security-token=" + s.SecurityToken : ""),
    n && (o += "&" + n)) : n && (o += "?" + n),
    o
}
function decodeAcl(i) {
    var e = {
        GrantFullControl: [],
        GrantWrite: [],
        GrantRead: [],
        GrantReadAcp: [],
        GrantWriteAcp: [],
        ACL: ""
    }
      , t = {
        FULL_CONTROL: "GrantFullControl",
        WRITE: "GrantWrite",
        READ: "GrantRead",
        READ_ACP: "GrantReadAcp",
        WRITE_ACP: "GrantWriteAcp"
    }
      , r = i && i.AccessControlList || {}
      , n = r.Grant;
    n && (n = util$2.isArray(n) ? n : [n]);
    var o = {
        READ: 0,
        WRITE: 0,
        FULL_CONTROL: 0
    };
    return n && n.length && util$2.each(n, function(a) {
        a.Grantee.ID === "qcs::cam::anyone:anyone" || a.Grantee.URI === "http://cam.qcloud.com/groups/global/AllUsers" ? o[a.Permission] = 1 : a.Grantee.ID !== i.Owner.ID && e[t[a.Permission]].push('id="' + a.Grantee.ID + '"')
    }),
    o.FULL_CONTROL || o.WRITE && o.READ ? e.ACL = "public-read-write" : o.READ ? e.ACL = "public-read" : e.ACL = "private",
    util$2.each(t, function(a) {
        e[a] = uniqGrant(e[a].join(","))
    }),
    e
}
function uniqGrant(i) {
    var e = i.split(","), t = {}, r, n;
    for (r = 0; r < e.length; )
        n = e[r].trim(),
        t[n] ? e.splice(r, 1) : (t[n] = !0,
        e[r] = n,
        r++);
    return e.join(",")
}
function getUrl(i) {
    var e = i.region || ""
      , t = i.bucket || ""
      , r = t.substr(0, t.lastIndexOf("-"))
      , n = t.substr(t.lastIndexOf("-") + 1)
      , o = i.domain
      , a = i.object;
    typeof o == "function" && (o = o({
        Bucket: t,
        Region: e
    }));
    var s = i.protocol || (util$2.isBrowser && location.protocol === "http:" ? "http:" : "https:");
    o || (["cn-south", "cn-south-2", "cn-north", "cn-east", "cn-southwest", "sg"].indexOf(e) > -1 ? o = "{Region}.myqcloud.com" : o = "cos.{Region}.myqcloud.com",
    i.ForcePathStyle || (o = "{Bucket}." + o)),
    o = o.replace(/\{\{AppId\}\}/ig, n).replace(/\{\{Bucket\}\}/ig, r).replace(/\{\{Region\}\}/ig, e).replace(/\{\{.*?\}\}/ig, ""),
    o = o.replace(/\{AppId\}/ig, n).replace(/\{BucketName\}/ig, r).replace(/\{Bucket\}/ig, t).replace(/\{Region\}/ig, e).replace(/\{.*?\}/ig, ""),
    /^[a-zA-Z]+:\/\//.test(o) || (o = s + "//" + o),
    o.slice(-1) === "/" && (o = o.slice(0, -1));
    var l = o;
    return i.ForcePathStyle && (l += "/" + t),
    l += "/",
    a && (l += util$2.camSafeUrlEncode(a).replace(/%2F/g, "/")),
    i.isLocation && (l = l.replace(/^https?:\/\//, "")),
    l
}
var getSignHost = function(i) {
    if (!i.Bucket || !i.Region)
        return "";
    var e = i.Url || getUrl({
        ForcePathStyle: this.options.ForcePathStyle,
        protocol: this.options.Protocol,
        domain: this.options.Domain,
        bucket: i.Bucket,
        region: this.options.UseAccelerate ? "accelerate" : i.Region
    })
      , t = e.replace(/^https?:\/\/([^/]+)(\/.*)?$/, "$1")
      , r = new RegExp("^([a-z\\d-]+-\\d+\\.)?(cos|cosv6|ci|pic)\\.([a-z\\d-]+)\\.myqcloud\\.com$");
    return r.test(t) ? t : ""
};
function getAuthorizationAsync(i, e) {
    var t = util$2.clone(i.Headers)
      , r = "";
    util$2.each(t, function(y, b) {
        (y === "" || ["content-type", "cache-control", "expires"].indexOf(b.toLowerCase()) > -1) && delete t[b],
        b.toLowerCase() === "host" && (r = y)
    }),
    !r && i.SignHost && (t.Host = i.SignHost);
    var n = !1
      , o = function(y, b) {
        n || (n = !0,
        b && b.XCosSecurityToken && !b.SecurityToken && (b = util$2.clone(b),
        b.SecurityToken = b.XCosSecurityToken,
        delete b.XCosSecurityToken),
        e && e(y, b))
    }
      , a = this
      , s = i.Bucket || ""
      , l = i.Region || ""
      , u = i.Key || "";
    a.options.ForcePathStyle && s && (u = s + "/" + u);
    var c = "/" + u
      , h = {}
      , f = i.Scope;
    if (!f) {
        var d = i.Action || ""
          , _ = i.ResourceKey || i.Key || "";
        f = i.Scope || [{
            action: d,
            bucket: s,
            region: l,
            prefix: _
        }]
    }
    var g = util$2.md5(JSON.stringify(f));
    a._StsCache = a._StsCache || [],
    function() {
        var y, b;
        for (y = a._StsCache.length - 1; y >= 0; y--) {
            b = a._StsCache[y];
            var T = Math.round(util$2.getSkewTime(a.options.SystemClockOffset) / 1e3) + 30;
            if (b.StartTime && T < b.StartTime || T >= b.ExpiredTime) {
                a._StsCache.splice(y, 1);
                continue
            }
            if (!b.ScopeLimit || b.ScopeLimit && b.ScopeKey === g) {
                h = b;
                break
            }
        }
    }();
    var m = function() {
        var y = h.StartTime && h.ExpiredTime ? h.StartTime + ";" + h.ExpiredTime : ""
          , b = util$2.getAuth({
            SecretId: h.TmpSecretId,
            SecretKey: h.TmpSecretKey,
            Method: i.Method,
            Pathname: c,
            Query: i.Query,
            Headers: t,
            Expires: i.Expires,
            UseRawKey: a.options.UseRawKey,
            SystemClockOffset: a.options.SystemClockOffset,
            KeyTime: y
        })
          , T = {
            Authorization: b,
            SecurityToken: h.SecurityToken || h.XCosSecurityToken || "",
            Token: h.Token || "",
            ClientIP: h.ClientIP || "",
            ClientUA: h.ClientUA || ""
        };
        o(null, T)
    }
      , v = function(y) {
        if (y.Authorization) {
            var b = !1
              , T = y.Authorization;
            if (T)
                if (T.indexOf(" ") > -1)
                    b = !1;
                else if (T.indexOf("q-sign-algorithm=") > -1 && T.indexOf("q-ak=") > -1 && T.indexOf("q-sign-time=") > -1 && T.indexOf("q-key-time=") > -1 && T.indexOf("q-url-param-list=") > -1)
                    b = !0;
                else
                    try {
                        T = atob(T),
                        T.indexOf("a=") > -1 && T.indexOf("k=") > -1 && T.indexOf("t=") > -1 && T.indexOf("r=") > -1 && T.indexOf("b=") > -1 && (b = !0)
                    } catch {}
            if (!b)
                return util$2.error(new Error("getAuthorization callback params format error"))
        } else {
            if (!y.TmpSecretId)
                return util$2.error(new Error('getAuthorization callback params missing "TmpSecretId"'));
            if (!y.TmpSecretKey)
                return util$2.error(new Error('getAuthorization callback params missing "TmpSecretKey"'));
            if (!y.SecurityToken && !y.XCosSecurityToken)
                return util$2.error(new Error('getAuthorization callback params missing "SecurityToken"'));
            if (!y.ExpiredTime)
                return util$2.error(new Error('getAuthorization callback params missing "ExpiredTime"'));
            if (y.ExpiredTime && y.ExpiredTime.toString().length !== 10)
                return util$2.error(new Error('getAuthorization callback params "ExpiredTime" should be 10 digits'));
            if (y.StartTime && y.StartTime.toString().length !== 10)
                return util$2.error(new Error('getAuthorization callback params "StartTime" should be 10 StartTime'))
        }
        return !1
    };
    if (h.ExpiredTime && h.ExpiredTime - util$2.getSkewTime(a.options.SystemClockOffset) / 1e3 > 60)
        m();
    else if (a.options.getAuthorization)
        a.options.getAuthorization.call(a, {
            Bucket: s,
            Region: l,
            Method: i.Method,
            Key: u,
            Pathname: c,
            Query: i.Query,
            Headers: t,
            Scope: f,
            SystemClockOffset: a.options.SystemClockOffset
        }, function(y) {
            typeof y == "string" && (y = {
                Authorization: y
            });
            var b = v(y);
            if (b)
                return o(b);
            y.Authorization ? o(null, y) : (h = y || {},
            h.Scope = f,
            h.ScopeKey = g,
            a._StsCache.push(h),
            m())
        });
    else if (a.options.getSTS)
        a.options.getSTS.call(a, {
            Bucket: s,
            Region: l
        }, function(y) {
            h = y || {},
            h.Scope = f,
            h.ScopeKey = g,
            h.TmpSecretId || (h.TmpSecretId = h.SecretId),
            h.TmpSecretKey || (h.TmpSecretKey = h.SecretKey);
            var b = v(h);
            if (b)
                return o(b);
            a._StsCache.push(h),
            m()
        });
    else
        return function() {
            var y = util$2.getAuth({
                SecretId: i.SecretId || a.options.SecretId,
                SecretKey: i.SecretKey || a.options.SecretKey,
                Method: i.Method,
                Pathname: c,
                Query: i.Query,
                Headers: t,
                Expires: i.Expires,
                UseRawKey: a.options.UseRawKey,
                SystemClockOffset: a.options.SystemClockOffset
            })
              , b = {
                Authorization: y,
                SecurityToken: a.options.SecurityToken || a.options.XCosSecurityToken
            };
            return o(null, b),
            b
        }();
    return ""
}
function allowRetry(i) {
    var e = !1
      , t = !1
      , r = i.headers && (i.headers.date || i.headers.Date) || i.error && i.error.ServerTime;
    try {
        var n = i.error.Code
          , o = i.error.Message;
        (n === "RequestTimeTooSkewed" || n === "AccessDenied" && o === "Request has expired") && (t = !0)
    } catch {}
    if (i)
        if (t && r) {
            var a = Date.parse(r);
            this.options.CorrectClockSkew && Math.abs(util$2.getSkewTime(this.options.SystemClockOffset) - a) >= 3e4 && (console.error("error: Local time is too skewed."),
            this.options.SystemClockOffset = a - Date.now(),
            e = !0)
        } else
            Math.floor(i.statusCode / 100) === 5 && (e = !0);
    return e
}
function submitRequest(i, e) {
    var t = this;
    !i.headers && (i.headers = {}),
    !i.qs && (i.qs = {}),
    i.VersionId && (i.qs.versionId = i.VersionId),
    i.qs = util$2.clearKey(i.qs),
    i.headers && (i.headers = util$2.clearKey(i.headers)),
    i.qs && (i.qs = util$2.clearKey(i.qs));
    var r = util$2.clone(i.qs);
    i.action && (r[i.action] = "");
    var n = i.url || i.Url
      , o = i.SignHost || getSignHost.call(this, {
        Bucket: i.Bucket,
        Region: i.Region,
        Url: n
    })
      , a = function(s) {
        var l = t.options.SystemClockOffset;
        getAuthorizationAsync.call(t, {
            Bucket: i.Bucket || "",
            Region: i.Region || "",
            Method: i.method,
            Key: i.Key,
            Query: r,
            Headers: i.headers,
            SignHost: o,
            Action: i.Action,
            ResourceKey: i.ResourceKey,
            Scope: i.Scope
        }, function(u, c) {
            if (u) {
                e(u);
                return
            }
            i.AuthData = c,
            _submitRequest.call(t, i, function(h, f) {
                h && s < 2 && (l !== t.options.SystemClockOffset || allowRetry.call(t, h)) ? (i.headers && (delete i.headers.Authorization,
                delete i.headers.token,
                delete i.headers.clientIP,
                delete i.headers.clientUA,
                i.headers["x-cos-security-token"] && delete i.headers["x-cos-security-token"],
                i.headers["x-ci-security-token"] && delete i.headers["x-ci-security-token"]),
                a(s + 1)) : e(h, f)
            })
        })
    };
    a(1)
}
function _submitRequest(i, e) {
    var t = this
      , r = i.TaskId;
    if (!(r && !t._isRunningTask(r))) {
        var n = i.Bucket
          , o = i.Region
          , a = i.Key
          , s = i.method || "GET"
          , l = i.Url || i.url
          , u = i.body
          , c = i.rawBody;
        t.options.UseAccelerate && (o = "accelerate"),
        l = l || getUrl({
            ForcePathStyle: t.options.ForcePathStyle,
            protocol: t.options.Protocol,
            domain: t.options.Domain,
            bucket: n,
            region: o,
            object: a
        }),
        i.action && (l = l + "?" + i.action),
        i.qsStr && (l.indexOf("?") > -1 ? l = l + "&" + i.qsStr : l = l + "?" + i.qsStr);
        var h = {
            method: s,
            url: l,
            headers: i.headers,
            qs: i.qs,
            body: u
        }
          , f = "x-cos-security-token";
        if (util$2.isCIHost(l) && (f = "x-ci-security-token"),
        h.headers.Authorization = i.AuthData.Authorization,
        i.AuthData.Token && (h.headers.token = i.AuthData.Token),
        i.AuthData.ClientIP && (h.headers.clientIP = i.AuthData.ClientIP),
        i.AuthData.ClientUA && (h.headers.clientUA = i.AuthData.ClientUA),
        i.AuthData.SecurityToken && (h.headers[f] = i.AuthData.SecurityToken),
        h.headers && (h.headers = util$2.clearKey(h.headers)),
        h = util$2.clearKey(h),
        i.onProgress && typeof i.onProgress == "function") {
            var d = u && (u.size || u.length) || 0;
            h.onProgress = function(m) {
                if (!(r && !t._isRunningTask(r))) {
                    var v = m ? m.loaded : 0;
                    i.onProgress({
                        loaded: v,
                        total: d
                    })
                }
            }
        }
        i.onDownloadProgress && (h.onDownloadProgress = i.onDownloadProgress),
        i.DataType && (h.dataType = i.DataType),
        this.options.Timeout && (h.timeout = this.options.Timeout),
        t.options.ForcePathStyle && (h.pathStyle = t.options.ForcePathStyle),
        t.emit("before-send", h);
        var _ = (t.options.Request || REQUEST)(h, function(m) {
            if (m.error !== "abort") {
                var v = {
                    options: h,
                    error: b,
                    statusCode: y && y.statusCode || 0,
                    headers: y && y.headers || {},
                    body: T
                };
                t.emit("after-receive", v),
                b = v.error,
                T = v.body,
                y = {
                    statusCode: v.statusCode,
                    headers: v.headers
                },
                t.emit("after-receive", m);
                var y = {
                    statusCode: m.statusCode,
                    statusMessage: m.statusMessage,
                    headers: m.headers
                }, b = m.error, T = m.body, C, A = function(x, I) {
                    if (r && t.off("inner-kill-task", g),
                    !C) {
                        C = !0;
                        var w = {};
                        y && y.statusCode && (w.statusCode = y.statusCode),
                        y && y.headers && (w.headers = y.headers),
                        x ? (x = util$2.extend(x || {}, w),
                        e(x, null)) : (I = util$2.extend(I || {}, w),
                        e(null, I)),
                        _ = null
                    }
                };
                if (b)
                    return A(util$2.error(b));
                var S = y.statusCode
                  , P = Math.floor(S / 100) === 2;
                if (c && P)
                    return A(null, {
                        body: T
                    });
                var R;
                try {
                    R = T && T.indexOf("<") > -1 && T.indexOf(">") > -1 && util$2.xml2json(T) || {}
                } catch {
                    R = {}
                }
                var M = R && R.Error;
                P ? A(null, R) : M ? A(util$2.error(new Error(M.Message), {
                    code: M.Code,
                    error: M
                })) : S ? A(util$2.error(new Error(y.statusMessage), {
                    code: "" + S
                })) : S && A(util$2.error(new Error("statusCode error")))
            }
        })
          , g = function(m) {
            m.TaskId === r && (_ && _.abort && _.abort(),
            t.off("inner-kill-task", g))
        };
        r && t.on("inner-kill-task", g)
    }
}
var API_MAP$1 = {
    getService,
    putBucket,
    headBucket,
    getBucket,
    deleteBucket,
    putBucketAcl,
    getBucketAcl,
    putBucketCors,
    getBucketCors,
    deleteBucketCors,
    getBucketLocation,
    getBucketPolicy,
    putBucketPolicy,
    deleteBucketPolicy,
    putBucketTagging,
    getBucketTagging,
    deleteBucketTagging,
    putBucketLifecycle,
    getBucketLifecycle,
    deleteBucketLifecycle,
    putBucketVersioning,
    getBucketVersioning,
    putBucketReplication,
    getBucketReplication,
    deleteBucketReplication,
    putBucketWebsite,
    getBucketWebsite,
    deleteBucketWebsite,
    putBucketReferer,
    getBucketReferer,
    putBucketDomain,
    getBucketDomain,
    deleteBucketDomain,
    putBucketOrigin,
    getBucketOrigin,
    deleteBucketOrigin,
    putBucketLogging,
    getBucketLogging,
    putBucketInventory,
    getBucketInventory,
    listBucketInventory,
    deleteBucketInventory,
    putBucketAccelerate,
    getBucketAccelerate,
    putBucketEncryption,
    getBucketEncryption,
    deleteBucketEncryption,
    getObject,
    headObject,
    listObjectVersions,
    putObject,
    deleteObject,
    getObjectAcl,
    putObjectAcl,
    optionsObject,
    putObjectCopy,
    deleteMultipleObject,
    restoreObject,
    putObjectTagging,
    getObjectTagging,
    deleteObjectTagging,
    selectObjectContent,
    appendObject,
    uploadPartCopy,
    multipartInit,
    multipartUpload,
    multipartComplete,
    multipartList,
    multipartListPart,
    multipartAbort,
    request,
    getObjectUrl,
    getAuth
};
function warnOldApi(i, e, t) {
    util$2.each(["Cors", "Acl"], function(r) {
        if (i.slice(-r.length) === r) {
            var n = i.slice(0, -r.length) + r.toUpperCase()
              , o = util$2.apiWrapper(i, e)
              , a = !1;
            t[n] = function() {
                !a && console.warn("warning: cos." + n + " has been deprecated. Please Use cos." + i + " instead."),
                a = !0,
                o.apply(this, arguments)
            }
        }
    })
}
base$1.init = function(i, e) {
    e.transferToTaskMethod(API_MAP$1, "putObject"),
    util$2.each(API_MAP$1, function(t, r) {
        i.prototype[r] = util$2.apiWrapper(r, t),
        warnOldApi(r, t, i.prototype)
    })
}
;
var advance$1 = {}
  , eachLimit = function(i, e, t, r) {
    if (r = r || function() {}
    ,
    !i.length || e <= 0)
        return r();
    var n = 0
      , o = 0
      , a = 0;
    (function s() {
        if (n >= i.length)
            return r();
        for (; a < e && o < i.length; )
            o += 1,
            a += 1,
            t(i[o - 1], function(l) {
                l ? (r(l),
                r = function() {}
                ) : (n += 1,
                a -= 1,
                n >= i.length ? r() : s())
            })
    }
    )()
}
  , retry = function(i, e, t) {
    var r = function(n) {
        e(function(o, a) {
            o && n < i ? r(n + 1) : t(o, a)
        })
    };
    i < 1 ? t() : r(1)
}
  , async = {
    eachLimit,
    retry
}
  , async_1 = async
  , session = session$2
  , Async = async_1
  , EventProxy = event$1.EventProxy
  , util$1 = util_1;
function sliceUploadFile(i, e) {
    var t = this, r = new EventProxy, n = i.TaskId, o = i.Bucket, a = i.Region, s = i.Key, l = i.Body, u = i.ChunkSize || i.SliceSize || t.options.ChunkSize, c = i.AsyncLimit, h = i.StorageClass, f = i.ServerSideEncryption, d, _, g = i.onHashProgress;
    r.on("error", function(m) {
        if (!!t._isRunningTask(n))
            return m.UploadId = i.UploadData.UploadId || "",
            e(m)
    }),
    r.on("upload_complete", function(m) {
        var v = util$1.extend({
            UploadId: i.UploadData.UploadId || ""
        }, m);
        e(null, v)
    }),
    r.on("upload_slice_complete", function(m) {
        var v = {};
        util$1.each(i.Headers, function(y, b) {
            var T = b.toLowerCase();
            (T.indexOf("x-cos-meta-") === 0 || T === "pic-operations") && (v[b] = y)
        }),
        uploadSliceComplete.call(t, {
            Bucket: o,
            Region: a,
            Key: s,
            UploadId: m.UploadId,
            SliceList: m.SliceList,
            Headers: v
        }, function(y, b) {
            if (!!t._isRunningTask(n)) {
                if (session.removeUsing(m.UploadId),
                y)
                    return _(null, !0),
                    r.emit("error", y);
                session.removeUploadId.call(t, m.UploadId),
                _({
                    loaded: d,
                    total: d
                }, !0),
                r.emit("upload_complete", b)
            }
        })
    }),
    r.on("get_upload_data_finish", function(m) {
        var v = session.getFileId(l, i.ChunkSize, o, s);
        v && session.saveUploadId.call(t, v, m.UploadId, t.options.UploadIdCacheLimit),
        session.setUsing(m.UploadId),
        _(null, !0),
        uploadSliceList.call(t, {
            TaskId: n,
            Bucket: o,
            Region: a,
            Key: s,
            Body: l,
            FileSize: d,
            SliceSize: u,
            AsyncLimit: c,
            ServerSideEncryption: f,
            UploadData: m,
            Headers: i.Headers,
            onProgress: _
        }, function(y, b) {
            if (!!t._isRunningTask(n)) {
                if (y)
                    return _(null, !0),
                    r.emit("error", y);
                r.emit("upload_slice_complete", b)
            }
        })
    }),
    r.on("get_file_size_finish", function() {
        if (_ = util$1.throttleOnProgress.call(t, d, i.onProgress),
        i.UploadData.UploadId)
            r.emit("get_upload_data_finish", i.UploadData);
        else {
            var m = util$1.extend({
                TaskId: n,
                Bucket: o,
                Region: a,
                Key: s,
                Headers: i.Headers,
                StorageClass: h,
                Body: l,
                FileSize: d,
                SliceSize: u,
                onHashProgress: g
            }, i);
            getUploadIdAndPartList.call(t, m, function(v, y) {
                if (!!t._isRunningTask(n)) {
                    if (v)
                        return r.emit("error", v);
                    i.UploadData.UploadId = y.UploadId,
                    i.UploadData.PartList = y.PartList,
                    r.emit("get_upload_data_finish", i.UploadData)
                }
            })
        }
    }),
    d = i.ContentLength,
    delete i.ContentLength,
    !i.Headers && (i.Headers = {}),
    util$1.each(i.Headers, function(m, v) {
        v.toLowerCase() === "content-length" && delete i.Headers[v]
    }),
    function() {
        for (var m = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 5120], v = 1024 * 1024, y = 0; y < m.length && (v = m[y] * 1024 * 1024,
        !(d / v <= t.options.MaxPartNumber)); y++)
            ;
        i.ChunkSize = i.SliceSize = u = Math.max(u, v)
    }(),
    d === 0 ? (i.Body = "",
    i.ContentLength = 0,
    i.SkipTask = !0,
    t.putObject(i, e)) : r.emit("get_file_size_finish")
}
function getUploadIdAndPartList(i, e) {
    var t = i.TaskId
      , r = i.Bucket
      , n = i.Region
      , o = i.Key
      , a = i.StorageClass
      , s = this
      , l = {}
      , u = i.FileSize
      , c = i.SliceSize
      , h = Math.ceil(u / c)
      , f = 0
      , d = util$1.throttleOnProgress.call(s, u, i.onHashProgress)
      , _ = function(v, y) {
        var b = c * (v - 1)
          , T = Math.min(b + c, u)
          , C = T - b;
        l[v] ? y(null, {
            PartNumber: v,
            ETag: l[v],
            Size: C
        }) : util$1.fileSlice(i.Body, b, T, !1, function(A) {
            util$1.getFileMd5(A, function(S, P) {
                if (S)
                    return y(util$1.error(S));
                var R = '"' + P + '"';
                l[v] = R,
                f += C,
                d({
                    loaded: f,
                    total: u
                }),
                y(null, {
                    PartNumber: v,
                    ETag: R,
                    Size: C
                })
            })
        })
    }
      , g = function(v, y) {
        var b = v.length;
        if (b === 0)
            return y(null, !0);
        if (b > h)
            return y(null, !1);
        if (b > 1) {
            var T = Math.max(v[0].Size, v[1].Size);
            if (T !== c)
                return y(null, !1)
        }
        var C = function(A) {
            if (A < b) {
                var S = v[A];
                _(S.PartNumber, function(P, R) {
                    R && R.ETag === S.ETag && R.Size === S.Size ? C(A + 1) : y(null, !1)
                })
            } else
                y(null, !0)
        };
        C(0)
    }
      , m = new EventProxy;
    m.on("error", function(v) {
        if (!!s._isRunningTask(t))
            return e(v)
    }),
    m.on("upload_id_available", function(v) {
        var y = {}
          , b = [];
        util$1.each(v.PartList, function(A) {
            y[A.PartNumber] = A
        });
        for (var T = 1; T <= h; T++) {
            var C = y[T];
            C ? (C.PartNumber = T,
            C.Uploaded = !0) : C = {
                PartNumber: T,
                ETag: null,
                Uploaded: !1
            },
            b.push(C)
        }
        v.PartList = b,
        e(null, v)
    }),
    m.on("no_available_upload_id", function() {
        if (!!s._isRunningTask(t)) {
            var v = util$1.extend({
                Bucket: r,
                Region: n,
                Key: o,
                Query: util$1.clone(i.Query),
                StorageClass: a,
                Body: i.Body
            }, i)
              , y = util$1.clone(i.Headers);
            delete y["x-cos-mime-limit"],
            v.Headers = y,
            s.multipartInit(v, function(b, T) {
                if (!!s._isRunningTask(t)) {
                    if (b)
                        return m.emit("error", b);
                    var C = T.UploadId;
                    if (!C)
                        return e(util$1.error(new Error("no such upload id")));
                    m.emit("upload_id_available", {
                        UploadId: C,
                        PartList: []
                    })
                }
            })
        }
    }),
    m.on("has_and_check_upload_id", function(v) {
        v = v.reverse(),
        Async.eachLimit(v, 1, function(y, b) {
            if (!!s._isRunningTask(t)) {
                if (session.using[y]) {
                    b();
                    return
                }
                wholeMultipartListPart.call(s, {
                    Bucket: r,
                    Region: n,
                    Key: o,
                    UploadId: y
                }, function(T, C) {
                    if (!!s._isRunningTask(t)) {
                        if (T)
                            return session.removeUsing(y),
                            m.emit("error", T);
                        var A = C.PartList;
                        A.forEach(function(S) {
                            S.PartNumber *= 1,
                            S.Size *= 1,
                            S.ETag = S.ETag || ""
                        }),
                        g(A, function(S, P) {
                            if (!!s._isRunningTask(t)) {
                                if (S)
                                    return m.emit("error", S);
                                P ? b({
                                    UploadId: y,
                                    PartList: A
                                }) : b()
                            }
                        })
                    }
                })
            }
        }, function(y) {
            !s._isRunningTask(t) || (d(null, !0),
            y && y.UploadId ? m.emit("upload_id_available", y) : m.emit("no_available_upload_id"))
        })
    }),
    m.on("seek_local_avail_upload_id", function(v) {
        var y = session.getFileId(i.Body, i.ChunkSize, r, o)
          , b = session.getUploadIdList.call(s, y);
        if (!y || !b) {
            m.emit("has_and_check_upload_id", v);
            return
        }
        var T = function(C) {
            if (C >= b.length) {
                m.emit("has_and_check_upload_id", v);
                return
            }
            var A = b[C];
            if (!util$1.isInArray(v, A)) {
                session.removeUploadId.call(s, A),
                T(C + 1);
                return
            }
            if (session.using[A]) {
                T(C + 1);
                return
            }
            wholeMultipartListPart.call(s, {
                Bucket: r,
                Region: n,
                Key: o,
                UploadId: A
            }, function(S, P) {
                !s._isRunningTask(t) || (S ? (session.removeUploadId.call(s, A),
                T(C + 1)) : m.emit("upload_id_available", {
                    UploadId: A,
                    PartList: P.PartList
                }))
            })
        };
        T(0)
    }),
    m.on("get_remote_upload_id_list", function() {
        wholeMultipartList.call(s, {
            Bucket: r,
            Region: n,
            Key: o
        }, function(v, y) {
            if (!!s._isRunningTask(t)) {
                if (v)
                    return m.emit("error", v);
                var b = util$1.filter(y.UploadList, function(A) {
                    return A.Key === o && (!a || A.StorageClass.toUpperCase() === a.toUpperCase())
                }).reverse().map(function(A) {
                    return A.UploadId || A.UploadID
                });
                if (b.length)
                    m.emit("seek_local_avail_upload_id", b);
                else {
                    var T = session.getFileId(i.Body, i.ChunkSize, r, o), C;
                    T && (C = session.getUploadIdList.call(s, T)) && util$1.each(C, function(A) {
                        session.removeUploadId.call(s, A)
                    }),
                    m.emit("no_available_upload_id")
                }
            }
        })
    }),
    m.emit("get_remote_upload_id_list")
}
function wholeMultipartList(i, e) {
    var t = this
      , r = []
      , n = {
        Bucket: i.Bucket,
        Region: i.Region,
        Prefix: i.Key
    }
      , o = function() {
        t.multipartList(n, function(a, s) {
            if (a)
                return e(a);
            r.push.apply(r, s.Upload || []),
            s.IsTruncated === "true" ? (n.KeyMarker = s.NextKeyMarker,
            n.UploadIdMarker = s.NextUploadIdMarker,
            o()) : e(null, {
                UploadList: r
            })
        })
    };
    o()
}
function wholeMultipartListPart(i, e) {
    var t = this
      , r = []
      , n = {
        Bucket: i.Bucket,
        Region: i.Region,
        Key: i.Key,
        UploadId: i.UploadId
    }
      , o = function() {
        t.multipartListPart(n, function(a, s) {
            if (a)
                return e(a);
            r.push.apply(r, s.Part || []),
            s.IsTruncated === "true" ? (n.PartNumberMarker = s.NextPartNumberMarker,
            o()) : e(null, {
                PartList: r
            })
        })
    };
    o()
}
function uploadSliceList(i, e) {
    var t = this
      , r = i.TaskId
      , n = i.Bucket
      , o = i.Region
      , a = i.Key
      , s = i.UploadData
      , l = i.FileSize
      , u = i.SliceSize
      , c = Math.min(i.AsyncLimit || t.options.ChunkParallelLimit || 1, 256)
      , h = i.Body
      , f = Math.ceil(l / u)
      , d = 0
      , _ = i.ServerSideEncryption
      , g = i.Headers
      , m = util$1.filter(s.PartList, function(y) {
        return y.Uploaded && (d += y.PartNumber >= f && l % u || u),
        !y.Uploaded
    })
      , v = i.onProgress;
    Async.eachLimit(m, c, function(y, b) {
        if (!!t._isRunningTask(r)) {
            var T = y.PartNumber
              , C = Math.min(l, y.PartNumber * u) - (y.PartNumber - 1) * u
              , A = 0;
            uploadSliceItem.call(t, {
                TaskId: r,
                Bucket: n,
                Region: o,
                Key: a,
                SliceSize: u,
                FileSize: l,
                PartNumber: T,
                ServerSideEncryption: _,
                Body: h,
                UploadData: s,
                Headers: g,
                onProgress: function(S) {
                    d += S.loaded - A,
                    A = S.loaded,
                    v({
                        loaded: d,
                        total: l
                    })
                }
            }, function(S, P) {
                !t._isRunningTask(r) || (!S && !P.ETag && (S = 'get ETag error, please add "ETag" to CORS ExposeHeader setting.( \u83B7\u53D6ETag\u5931\u8D25\uFF0C\u8BF7\u5728CORS ExposeHeader\u8BBE\u7F6E\u4E2D\u6DFB\u52A0ETag\uFF0C\u8BF7\u53C2\u8003\u6587\u6863\uFF1Ahttps://cloud.tencent.com/document/product/436/13318 )'),
                S ? d -= A : (d += C - A,
                y.ETag = P.ETag),
                v({
                    loaded: d,
                    total: l
                }),
                b(S || null, P))
            })
        }
    }, function(y) {
        if (!!t._isRunningTask(r)) {
            if (y)
                return e(y);
            e(null, {
                UploadId: s.UploadId,
                SliceList: s.PartList
            })
        }
    })
}
function uploadSliceItem(i, e) {
    var t = this
      , r = i.TaskId
      , n = i.Bucket
      , o = i.Region
      , a = i.Key
      , s = i.FileSize
      , l = i.Body
      , u = i.PartNumber * 1
      , c = i.SliceSize
      , h = i.ServerSideEncryption
      , f = i.UploadData
      , d = i.Headers || {}
      , _ = t.options.ChunkRetryTimes + 1
      , g = c * (u - 1)
      , m = c
      , v = g + c;
    v > s && (v = s,
    m = v - g);
    var y = ["x-cos-traffic-limit", "x-cos-mime-limit"]
      , b = {};
    util$1.each(d, function(C, A) {
        y.indexOf(A) > -1 && (b[A] = C)
    });
    var T = f.PartList[u - 1];
    Async.retry(_, function(C) {
        !t._isRunningTask(r) || util$1.fileSlice(l, g, v, !0, function(A) {
            t.multipartUpload({
                TaskId: r,
                Bucket: n,
                Region: o,
                Key: a,
                ContentLength: m,
                PartNumber: u,
                UploadId: f.UploadId,
                ServerSideEncryption: h,
                Body: A,
                Headers: b,
                onProgress: i.onProgress
            }, function(S, P) {
                if (!!t._isRunningTask(r))
                    return S ? C(S) : (T.Uploaded = !0,
                    C(null, P))
            })
        })
    }, function(C, A) {
        if (!!t._isRunningTask(r))
            return e(C, A)
    })
}
function uploadSliceComplete(i, e) {
    var t = i.Bucket
      , r = i.Region
      , n = i.Key
      , o = i.UploadId
      , a = i.SliceList
      , s = this
      , l = this.options.ChunkRetryTimes + 1
      , u = i.Headers
      , c = a.map(function(h) {
        return {
            PartNumber: h.PartNumber,
            ETag: h.ETag
        }
    });
    Async.retry(l, function(h) {
        s.multipartComplete({
            Bucket: t,
            Region: r,
            Key: n,
            UploadId: o,
            Parts: c,
            Headers: u
        }, h)
    }, function(h, f) {
        e(h, f)
    })
}
function abortUploadTask(i, e) {
    var t = i.Bucket
      , r = i.Region
      , n = i.Key
      , o = i.UploadId
      , a = i.Level || "task"
      , s = i.AsyncLimit
      , l = this
      , u = new EventProxy;
    if (u.on("error", function(c) {
        return e(c)
    }),
    u.on("get_abort_array", function(c) {
        abortUploadTaskArray.call(l, {
            Bucket: t,
            Region: r,
            Key: n,
            Headers: i.Headers,
            AsyncLimit: s,
            AbortArray: c
        }, e)
    }),
    a === "bucket")
        wholeMultipartList.call(l, {
            Bucket: t,
            Region: r
        }, function(c, h) {
            if (c)
                return e(c);
            u.emit("get_abort_array", h.UploadList || [])
        });
    else if (a === "file") {
        if (!n)
            return e(util$1.error(new Error("abort_upload_task_no_key")));
        wholeMultipartList.call(l, {
            Bucket: t,
            Region: r,
            Key: n
        }, function(c, h) {
            if (c)
                return e(c);
            u.emit("get_abort_array", h.UploadList || [])
        })
    } else if (a === "task") {
        if (!o)
            return e(util$1.error(new Error("abort_upload_task_no_id")));
        if (!n)
            return e(util$1.error(new Error("abort_upload_task_no_key")));
        u.emit("get_abort_array", [{
            Key: n,
            UploadId: o
        }])
    } else
        return e(util$1.error(new Error("abort_unknown_level")))
}
function abortUploadTaskArray(i, e) {
    var t = i.Bucket
      , r = i.Region
      , n = i.Key
      , o = i.AbortArray
      , a = i.AsyncLimit || 1
      , s = this
      , l = 0
      , u = new Array(o.length);
    Async.eachLimit(o, a, function(c, h) {
        var f = l;
        if (n && n !== c.Key) {
            u[f] = {
                error: {
                    KeyNotMatch: !0
                }
            },
            h(null);
            return
        }
        var d = c.UploadId || c.UploadID;
        s.multipartAbort({
            Bucket: t,
            Region: r,
            Key: c.Key,
            Headers: i.Headers,
            UploadId: d
        }, function(_) {
            var g = {
                Bucket: t,
                Region: r,
                Key: c.Key,
                UploadId: d
            };
            u[f] = {
                error: _,
                task: g
            },
            h(null)
        }),
        l++
    }, function(c) {
        if (c)
            return e(c);
        for (var h = [], f = [], d = 0, _ = u.length; d < _; d++) {
            var g = u[d];
            g.task && (g.error ? f.push(g.task) : h.push(g.task))
        }
        return e(null, {
            successList: h,
            errorList: f
        })
    })
}
function uploadFile(i, e) {
    var t = this
      , r = i.SliceSize === void 0 ? t.options.SliceSize : i.SliceSize
      , n = []
      , o = i.Body
      , a = o.size || o.length || 0
      , s = {
        TaskId: ""
    };
    util$1.each(i, function(d, _) {
        typeof d != "object" && typeof d != "function" && (s[_] = d)
    });
    var l = i.onTaskReady
      , u = function(d) {
        s.TaskId = d,
        l && l(d)
    };
    i.onTaskReady = u;
    var c = i.onFileFinish
      , h = function(d, _) {
        c && c(d, _, s),
        e && e(d, _)
    }
      , f = a > r ? "sliceUploadFile" : "putObject";
    n.push({
        api: f,
        params: i,
        callback: h
    }),
    t._addTasks(n)
}
function uploadFiles(i, e) {
    var t = this
      , r = i.SliceSize === void 0 ? t.options.SliceSize : i.SliceSize
      , n = 0
      , o = 0
      , a = util$1.throttleOnProgress.call(t, o, i.onProgress)
      , s = i.files.length
      , l = i.onFileFinish
      , u = Array(s)
      , c = function(f, d, _) {
        a(null, !0),
        l && l(f, d, _),
        u[_.Index] = {
            options: _,
            error: f,
            data: d
        },
        --s <= 0 && e && e(null, {
            files: u
        })
    }
      , h = [];
    util$1.each(i.files, function(f, d) {
        (function() {
            var _ = f.Body
              , g = _.size || _.length || 0
              , m = {
                Index: d,
                TaskId: ""
            };
            n += g,
            util$1.each(f, function(R, M) {
                typeof R != "object" && typeof R != "function" && (m[M] = R)
            });
            var v = f.onTaskReady
              , y = function(R) {
                m.TaskId = R,
                v && v(R)
            };
            f.onTaskReady = y;
            var b = 0
              , T = f.onProgress
              , C = function(R) {
                o = o - b + R.loaded,
                b = R.loaded,
                T && T(R),
                a({
                    loaded: o,
                    total: n
                })
            };
            f.onProgress = C;
            var A = f.onFileFinish
              , S = function(R, M) {
                A && A(R, M),
                c && c(R, M, m)
            }
              , P = g > r ? "sliceUploadFile" : "putObject";
            h.push({
                api: P,
                params: f,
                callback: S
            })
        }
        )()
    }),
    t._addTasks(h)
}
function sliceCopyFile(i, e) {
    var t = new EventProxy
      , r = this
      , n = i.Bucket
      , o = i.Region
      , a = i.Key
      , s = i.CopySource
      , l = util$1.getSourceParams.call(this, s);
    if (!l) {
        e(util$1.error(new Error("CopySource format error")));
        return
    }
    var u = l.Bucket
      , c = l.Region
      , h = decodeURIComponent(l.Key)
      , f = i.CopySliceSize === void 0 ? r.options.CopySliceSize : i.CopySliceSize;
    f = Math.max(0, f);
    var d = i.CopyChunkSize || this.options.CopyChunkSize, _ = this.options.CopyChunkParallelLimit, g = 0, m, v;
    t.on("copy_slice_complete", function(y) {
        var b = {};
        util$1.each(i.Headers, function(C, A) {
            A.toLowerCase().indexOf("x-cos-meta-") === 0 && (b[A] = C)
        });
        var T = util$1.map(y.PartList, function(C) {
            return {
                PartNumber: C.PartNumber,
                ETag: C.ETag
            }
        });
        r.multipartComplete({
            Bucket: n,
            Region: o,
            Key: a,
            UploadId: y.UploadId,
            Parts: T
        }, function(C, A) {
            if (C)
                return v(null, !0),
                e(C);
            v({
                loaded: m,
                total: m
            }, !0),
            e(null, A)
        })
    }),
    t.on("get_copy_data_finish", function(y) {
        Async.eachLimit(y.PartList, _, function(b, T) {
            var C = b.PartNumber
              , A = b.CopySourceRange
              , S = b.end - b.start;
            copySliceItem.call(r, {
                Bucket: n,
                Region: o,
                Key: a,
                CopySource: s,
                UploadId: y.UploadId,
                PartNumber: C,
                CopySourceRange: A
            }, function(P, R) {
                if (P)
                    return T(P);
                g += S,
                v({
                    loaded: g,
                    total: m
                }),
                b.ETag = R.ETag,
                T(P || null, R)
            })
        }, function(b) {
            if (b)
                return v(null, !0),
                e(b);
            t.emit("copy_slice_complete", y)
        })
    }),
    t.on("get_file_size_finish", function(y) {
        (function() {
            for (var C = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 5120], A = 1024 * 1024, S = 0; S < C.length && (A = C[S] * 1024 * 1024,
            !(m / A <= r.options.MaxPartNumber)); S++)
                ;
            i.ChunkSize = d = Math.max(d, A);
            for (var P = Math.ceil(m / d), R = [], M = 1; M <= P; M++) {
                var x = (M - 1) * d
                  , I = M * d < m ? M * d - 1 : m - 1
                  , w = {
                    PartNumber: M,
                    start: x,
                    end: I,
                    CopySourceRange: "bytes=" + x + "-" + I
                };
                R.push(w)
            }
            i.PartList = R
        }
        )();
        var b;
        if (i.Headers["x-cos-metadata-directive"] === "Replaced" ? b = i.Headers : b = y,
        b["x-cos-storage-class"] = i.Headers["x-cos-storage-class"] || y["x-cos-storage-class"],
        b = util$1.clearKey(b),
        y["x-cos-storage-class"] === "ARCHIVE" || y["x-cos-storage-class"] === "DEEP_ARCHIVE") {
            var T = y["x-cos-restore"];
            if (!T || T === 'ongoing-request="true"') {
                e(util$1.error(new Error("Unrestored archive object is not allowed to be copied")));
                return
            }
        }
        delete b["x-cos-copy-source"],
        delete b["x-cos-metadata-directive"],
        delete b["x-cos-copy-source-If-Modified-Since"],
        delete b["x-cos-copy-source-If-Unmodified-Since"],
        delete b["x-cos-copy-source-If-Match"],
        delete b["x-cos-copy-source-If-None-Match"],
        r.multipartInit({
            Bucket: n,
            Region: o,
            Key: a,
            Headers: b
        }, function(C, A) {
            if (C)
                return e(C);
            i.UploadId = A.UploadId,
            t.emit("get_copy_data_finish", i)
        })
    }),
    r.headObject({
        Bucket: u,
        Region: c,
        Key: h
    }, function(y, b) {
        if (y) {
            y.statusCode && y.statusCode === 404 ? e(util$1.error(y, {
                ErrorStatus: h + " Not Exist"
            })) : e(y);
            return
        }
        if (m = i.FileSize = b.headers["content-length"],
        m === void 0 || !m) {
            e(util$1.error(new Error('get Content-Length error, please add "Content-Length" to CORS ExposeHeader setting.\uFF08 \u83B7\u53D6Content-Length\u5931\u8D25\uFF0C\u8BF7\u5728CORS ExposeHeader\u8BBE\u7F6E\u4E2D\u6DFB\u52A0Content-Length\uFF0C\u8BF7\u53C2\u8003\u6587\u6863\uFF1Ahttps://cloud.tencent.com/document/product/436/13318 \uFF09')));
            return
        }
        if (v = util$1.throttleOnProgress.call(r, m, i.onProgress),
        m <= f)
            i.Headers["x-cos-metadata-directive"] || (i.Headers["x-cos-metadata-directive"] = "Copy"),
            r.putObjectCopy(i, function(A, S) {
                if (A)
                    return v(null, !0),
                    e(A);
                v({
                    loaded: m,
                    total: m
                }, !0),
                e(A, S)
            });
        else {
            var T = b.headers
              , C = {
                "Cache-Control": T["cache-control"],
                "Content-Disposition": T["content-disposition"],
                "Content-Encoding": T["content-encoding"],
                "Content-Type": T["content-type"],
                Expires: T.expires,
                "x-cos-storage-class": T["x-cos-storage-class"]
            };
            util$1.each(T, function(A, S) {
                var P = "x-cos-meta-";
                S.indexOf(P) === 0 && S.length > P.length && (C[S] = A)
            }),
            t.emit("get_file_size_finish", C)
        }
    })
}
function copySliceItem(i, e) {
    var t = i.TaskId
      , r = i.Bucket
      , n = i.Region
      , o = i.Key
      , a = i.CopySource
      , s = i.UploadId
      , l = i.PartNumber * 1
      , u = i.CopySourceRange
      , c = this.options.ChunkRetryTimes + 1
      , h = this;
    Async.retry(c, function(f) {
        h.uploadPartCopy({
            TaskId: t,
            Bucket: r,
            Region: n,
            Key: o,
            CopySource: a,
            UploadId: s,
            PartNumber: l,
            CopySourceRange: u
        }, function(d, _) {
            f(d || null, _)
        })
    }, function(f, d) {
        return e(f, d)
    })
}
var API_MAP = {
    sliceUploadFile,
    abortUploadTask,
    uploadFile,
    uploadFiles,
    sliceCopyFile
};
advance$1.init = function(i, e) {
    e.transferToTaskMethod(API_MAP, "sliceUploadFile"),
    util$1.each(API_MAP, function(t, r) {
        i.prototype[r] = util$1.apiWrapper(r, t)
    })
}
;
var util = util_1
  , event = event$1
  , task = task$1
  , base = base$1
  , advance = advance$1
  , defaultOptions = {
    AppId: "",
    SecretId: "",
    SecretKey: "",
    SecurityToken: "",
    ChunkRetryTimes: 2,
    FileParallelLimit: 3,
    ChunkParallelLimit: 3,
    ChunkSize: 1024 * 1024,
    SliceSize: 1024 * 1024,
    CopyChunkParallelLimit: 20,
    CopyChunkSize: 1024 * 1024 * 10,
    CopySliceSize: 1024 * 1024 * 10,
    MaxPartNumber: 1e4,
    ProgressInterval: 1e3,
    Domain: "",
    ServiceDomain: "",
    Protocol: "",
    CompatibilityMode: !1,
    ForcePathStyle: !1,
    UseRawKey: !1,
    Timeout: 0,
    CorrectClockSkew: !0,
    SystemClockOffset: 0,
    UploadCheckContentMd5: !1,
    UploadQueueSize: 1e4,
    UploadAddMetaMd5: !1,
    UploadIdCacheLimit: 50,
    UseAccelerate: !1
}
  , COS$1 = function(i) {
    this.options = util.extend(util.clone(defaultOptions), i || {}),
    this.options.FileParallelLimit = Math.max(1, this.options.FileParallelLimit),
    this.options.ChunkParallelLimit = Math.max(1, this.options.ChunkParallelLimit),
    this.options.ChunkRetryTimes = Math.max(0, this.options.ChunkRetryTimes),
    this.options.ChunkSize = Math.max(1024 * 1024, this.options.ChunkSize),
    this.options.CopyChunkParallelLimit = Math.max(1, this.options.CopyChunkParallelLimit),
    this.options.CopyChunkSize = Math.max(1024 * 1024, this.options.CopyChunkSize),
    this.options.CopySliceSize = Math.max(0, this.options.CopySliceSize),
    this.options.MaxPartNumber = Math.max(1024, Math.min(1e4, this.options.MaxPartNumber)),
    this.options.Timeout = Math.max(0, this.options.Timeout),
    this.options.AppId && console.warn('warning: AppId has been deprecated, Please put it at the end of parameter Bucket(E.g: "test-1250000000").'),
    this.options.SecretId && this.options.SecretId.indexOf(" ") > -1 && (console.error("error: SecretId\u683C\u5F0F\u9519\u8BEF\uFF0C\u8BF7\u68C0\u67E5"),
    console.error("error: SecretId format is incorrect. Please check")),
    this.options.SecretKey && this.options.SecretKey.indexOf(" ") > -1 && (console.error("error: SecretKey\u683C\u5F0F\u9519\u8BEF\uFF0C\u8BF7\u68C0\u67E5"),
    console.error("error: SecretKey format is incorrect. Please check")),
    util.isNode() && (console.warn("warning: cos-js-sdk-v5 \u4E0D\u652F\u6301 nodejs \u73AF\u5883\u4F7F\u7528\uFF0C\u8BF7\u6539\u7528 cos-nodejs-sdk-v5\uFF0C\u53C2\u8003\u6587\u6863\uFF1A https://cloud.tencent.com/document/product/436/8629"),
    console.warn("warning: cos-js-sdk-v5 does not support nodejs environment. Please use cos-nodejs-sdk-v5 instead. See: https://cloud.tencent.com/document/product/436/8629")),
    event.init(this),
    task.init(this)
};
base.init(COS$1, task);
advance.init(COS$1, task);
COS$1.util = {
    md5: util.md5,
    xml2json: util.xml2json,
    json2xml: util.json2xml
};
COS$1.getAuthorization = util.getAuth;
COS$1.version = "1.3.5";
var cos = COS$1
  , COS = cos
  , cosJsSdkV5 = COS;
const SERVER_URL = "https://cos-auth.xversepro.com/sts"
  , COS_BUCKET = "xvbs-1258211750"
  , COS_REGION = "ap-guangzhou";
var myCos = new cosJsSdkV5({
    getAuthorization: function(i, e) {
        var t = SERVER_URL
          , r = new XMLHttpRequest;
        r.open("GET", t, !0),
        r.onload = function(n) {
            try {
                var o = JSON.parse(n.target.responseText)
                  , a = o.credentials
            } catch (s) {
                console.error(s)
            }
            if (!o || !a)
                return console.error(`credentials invalid:
` + JSON.stringify(o, null, 2));
            e({
                TmpSecretId: a.tmpSecretId,
                TmpSecretKey: a.tmpSecretKey,
                SecurityToken: a.sessionToken,
                StartTime: o.startTime,
                ExpiredTime: o.expiredTime
            })
        }
        ,
        r.send()
    }
});
function uploadStream(i, e) {
    myCos.putObject({
        Bucket: COS_BUCKET,
        Region: COS_REGION,
        Key: i,
        StorageClass: "STANDARD",
        Body: e,
        onProgress: function(t) {
            console.log(JSON.stringify(t))
        }
    }, function(t, r) {
        console.log(t || r)
    })
}
const defaultLogger = {
    info: console.log,
    debug: console.log,
    error: console.error,
    infoAndReportMeasurement: (...i)=>{}
};
let log$m = defaultLogger;
const USER_ID = "987412365"
  , PAGE_SESSION = "aaabbbccc"
  , SERVER_SESSION = "cccbbbaaa"
  , COS_PREFIX = "error-bitstreams-auto-uploaded-from-application/"
  , FRAME_COMPOSE_LENGTH = 5;
class Workers {
    constructor(e, t) {
        this.rtcp = e,
        this.cacheSize = 0,
        this.cacheBuffer = new Uint8Array(262144),
        this.cacheFrameCnt = 0,
        this.startReceiveTime = 0,
        this.cacheFrameComposes = new Array(0),
        this.cacheSizes = new Array(5).fill(0),
        this.cacheFrameCnts = new Array(5).fill(-1),
        this.cacheStartReceiveTimes = new Array(5).fill(0),
        this.cacheBuffers = [new Uint8Array(262144), new Uint8Array(262144), new Uint8Array(262144), new Uint8Array(262144), new Uint8Array(262144)],
        this.panoCacheSize = 0,
        this.panoCacheBuffer = new Uint8Array(2097152),
        this.cachePanoTileID = 0,
        this.receivedMedia = 0,
        this.receivedMedia_worker = 0,
        this.receivedYUV = 0,
        this.receivedEmit = 0,
        this.returnFrames = 0,
        this.lastReturnFrames = 0,
        this.lastReceivedEmit = 0,
        this.mediaBytesReceived = 0,
        this.metaBytesReceived = 0,
        this.noWasmBytesReceived = 0,
        this.rtcBytesReceived = 0,
        this.rtcMessageReceived = 0,
        this.packetsDrop = 0,
        this.framesAwait = 0,
        this.sendOutBuffer = 0,
        this.decodeTimePerFrame = 0,
        this.decodeTimeMaxFrame = 0,
        this.lastRenderTs = 0,
        this.JankTimes = 0,
        this.bigJankTimes = 0,
        this.DecodeJankTimes = 0,
        this.bigDecodeJankTimes = 0,
        this.saveframe = !1,
        this.SaveMediaStream = !1,
        this.packetsLost = 0,
        this.showAllReceivedMetadata = !1,
        this.firstMediaArraval = 0,
        this.firstMediaReceived = !1,
        this.firstYUVDecoded = 0,
        this.firstRender = 0,
        this.firstYUVReceived = !1,
        this.reconnectSignal = !1,
        this.serverFrameSlow = 0,
        this.serverFrameFast = 0,
        this.clientFrameSlow = 0,
        this.clientFrameFast = 0,
        this.lastServerTS = 0,
        this.lastClientTS = 0,
        this.lastSeq = 0,
        this.lastIsPureMeta = !1,
        this.lastHBPacketTs = 0,
        this.HBPacketInterval = 0,
        this.lastHBPacketSrvSentTs = 0,
        this.HBPacketIntervalSrvSent = 0,
        this.cachedLength = 2,
        this.cachedStreams = new Array(this.cachedLength),
        this.cachedMetas = new Array(this.cachedLength),
        this.cachedPtss = new Array(this.cachedLength),
        this.cachedRender = Array(this.cachedLength).fill(!1),
        this.cachedResolution = new Array(this.cachedLength),
        this.getPtr = 0,
        this.setPtr = 0,
        this.receiveIframes = 0,
        this.decodeIframes = 0,
        this.prevSenderTs = -1,
        this.serverSendTimeArray = new CircularArray(120,!1,[]),
        this.inPanoMode = !1,
        this.PanoStatus = {
            x: 0,
            y: 0,
            z: 0,
            tiles: []
        },
        this.DynamicPanoTest = !1,
        this.PanoMask = new ArrayBuffer(8),
        this.PanoView = new DataView(this.PanoMask),
        this.userId_test = "",
        this.PendingMasks = [],
        this.traceIdMap = new Map,
        this.responseTimeArray = [],
        this.processTimeArray = [],
        this.displayTimeArray = [],
        this.overallTimeArray = [],
        this.responseMiss = 0,
        this.processMiss = 0,
        this.displayMiss = 0,
        this.updateYUVCircular = new CircularArray(120,!1,[]),
        this.updateDropFrame = 0,
        this.metaParseAraay = [],
        this.responseMoveMiss = 0,
        this.processMoveMiss = 0,
        this.displayMoveMiss = 0,
        this.MovingTraceId = "",
        this.PendingMovingTraceId = "",
        this.inMovingMode = !1,
        this.StartMovingTs = 0,
        this.PendingStartMovingTs = 0,
        this.moveEvent = "",
        this.MoveToFrameCnt = 0,
        this.lastIsMoving = 0,
        this.MoveResponseDelay = 0,
        this.MoveProcessDelay = 0,
        this.MoveDisplayDelay = 0,
        this.lastMoveResponseTime = 0,
        this.lastMoveProcessTime = 0,
        this.lastMoveDisplayTime = 0,
        this.moveResponseCircular = new CircularArray(120,!0,[STUCK_STAGE_GOOD, STUCK_STAGE_WELL, STUCK_STAGE_FAIR, STUCK_STAGE_BAD]),
        this.moveProcessCircular = new CircularArray(120,!0,[STUCK_STAGE_GOOD, STUCK_STAGE_WELL, STUCK_STAGE_FAIR, STUCK_STAGE_BAD]),
        this.moveDisplayCircular = new CircularArray(120,!0,[STUCK_STAGE_GOOD, STUCK_STAGE_WELL, STUCK_STAGE_FAIR, STUCK_STAGE_BAD]),
        this.moveStartPts = -1,
        this.frameServerCircular = new CircularArray(120,!1,[]),
        this.srvMetaIntervalCircular = new CircularArray(120,!1,[]),
        this.srvMediaIntervalCircular = new CircularArray(120,!1,[]),
        this.srvHBMetaIntervalCircular = new CircularArray(120,!1,[]),
        this.srvHBMetaIntervalSrvSentCircular = new CircularArray(120,!1,[]),
        this.frameClientCircular = new CircularArray(120,!1,[]),
        this.firstUpdateYUV = !0,
        this.functionMap = new Map,
        this.WASM_VERSION = "WASM-1.1",
        this.frameHistory = [],
        this.getVersion = function() {
            return DECODER_VERSION
        }
        ,
        this.downloadBlob = (r,n,o)=>{
            const a = new Blob([r],{
                type: o
            })
              , s = window.URL.createObjectURL(a);
            this.downloadURL(s, n),
            setTimeout(function() {
                return window.URL.revokeObjectURL(s)
            }, 1e3)
        }
        ,
        this.downloadURL = function(r, n) {
            const o = document.createElement("a");
            o.href = r,
            o.download = n,
            document.body.appendChild(o),
            o.style.display = "none",
            o.click(),
            o.remove()
        }
        ,
        this.Stringify = function(r) {
            let n = "";
            for (let a = 0; a < r.length / 8192; a++)
                n += String.fromCharCode.apply(null, r.slice(a * 8192, (a + 1) * 8192));
            return n
        }
        ,
        this._rtcp = e
    }
    registerLogger(e) {
        log$m = e
    }
    registerFunction(e, t) {
        this.functionMap.set(e, t)
    }
    hasFrmCntInCache(e) {
        let t = -1;
        for (let r = 0; r < this.cacheFrameComposes.length; r++)
            this.cacheFrameComposes[r].frameCnt == e && (t = r);
        return t
    }
    requestPanoramaTest(e, t, r, n, o) {
        const a = o
          , s = {
            action_type: 16,
            change_rotation_render_type_action: {
                render_type: 5,
                player: {
                    position: {
                        x: 0,
                        y: 0,
                        z: 0
                    },
                    angle: {
                        yaw: 0,
                        pitch: 0,
                        roll: 0
                    }
                },
                camera: {
                    position: {
                        x: e,
                        y: t,
                        z: r
                    },
                    angle: {
                        yaw: 0,
                        pitch: 0,
                        roll: 0
                    }
                },
                client_pano_titles_bitmap: n
            },
            trace_id: a,
            user_id: this.userId_test,
            packet_id: a
        };
        log$m.debug("send data: ", s),
        this._rtcp.sendData(s)
    }
    onRotateInPanoMode(e) {
        const t = e.traceId
          , r = {};
        r.width = 1280,
        r.height = 720,
        r.horz_fov = 92,
        r.angle = {
            yaw: 100,
            pitch: 30
        };
        const n = new ArrayBuffer(8)
          , o = new DataView(n);
        getTilesInView(r, n);
        const a = n.slice(0);
        this.PendingMasks.unshift({
            buffer: a,
            angle: r.angle
        }),
        MaskSetToOne(18, this.PanoView),
        operateForDataView(o, this.PanoView, o, (s,l)=>s ^ s & l),
        this.requestPanoramaTest(0, 0, 0, [o.getUint8(0), o.getUint8(1), o.getUint8(2), o.getUint8(3), o.getUint8(4), o.getUint8(5), o.getUint8(6), o.getUint8(7)], t)
    }
    processMetaWithTraceId(e) {
        for (const t of e.traceIds) {
            if (this.traceIdMap.has(t)) {
                const r = this.traceIdMap.get(t);
                r != null && (r.receiveTime = Date.now(),
                r.status = 1)
            }
            if (t == this.PendingMovingTraceId) {
                this.inMovingMode = !0,
                this.MovingTraceId = this.PendingMovingTraceId,
                this.StartMovingTs = this.PendingStartMovingTs,
                this.PendingMovingTraceId = "",
                this.PendingStartMovingTs = 0,
                log$m.info("MoveTo TraceId match", this.StartMovingTs, Date.now());
                const r = Date.now();
                this.lastMoveResponseTime = r,
                this.lastMoveProcessTime = r,
                this.lastMoveDisplayTime = r,
                this.frameServerCircular.clear(),
                this.frameClientCircular.clear()
            }
        }
    }
    onTraceId(e, t=this) {
        const r = e.traceId
          , n = e.timestamp
          , o = e.event;
        if (o === "Rotation") {
            const a = {
                traceId: r,
                pts: 0,
                startTime: n,
                receiveTime: 0,
                readyTime: 0,
                displayTime: 0,
                status: 0
            };
            this.traceIdMap.set(r, a);
            const s = setTimeout(()=>{
                if (s && clearTimeout(s),
                this.traceIdMap.has(r)) {
                    const l = this.traceIdMap.get(r);
                    switch (l == null ? void 0 : l.status) {
                    case 0:
                        {
                            this.responseMiss += 1;
                            break
                        }
                    case 1:
                        {
                            this.processMiss += 1;
                            const u = l.receiveTime - l.startTime;
                            this.responseTimeArray.push(u);
                            break
                        }
                    case 2:
                        {
                            this.displayMiss += 1;
                            const u = l.receiveTime - l.startTime
                              , c = l.readyTime - l.receiveTime;
                            this.responseTimeArray.push(u),
                            this.processTimeArray.push(c);
                            break
                        }
                    case 3:
                        log$m.debug("status is 3")
                    }
                }
            }
            , 1e3)
        } else
            o === "MoveTo" ? (log$m.info("receive moveto traceId ", r, " at timestamp", n),
            this.PendingMovingTraceId = r,
            this.PendingStartMovingTs = n,
            this.moveEvent = o,
            this.frameServerCircular.clear()) : o === "GetOnAirship" || o === "GetOnVehicle" ? (log$m.info("receive airship traceId ", r, " at timestamp ", n),
            this.PendingMovingTraceId = r,
            this.PendingStartMovingTs = n,
            this.moveEvent = o,
            this.frameServerCircular.clear()) : (o === "GetOffAirship" || o === "GetOffVehicle") && this.clearMoveArray()
    }
    executeFunction(e, t) {
        if (this.functionMap.has(e)) {
            const r = this.functionMap.get(e);
            r != null && r(t)
        }
    }
    UpdateStats(e) {
        var t;
        (t = this._rtcp.connection) == null || t.getStats(null).then(r=>{
            r.forEach(n=>{
                n.type == "data-channel" && (this.rtcMessageReceived = n.messagesReceived - n.messagesSent,
                this.rtcBytesReceived = n.bytesReceived)
            }
            )
        }
        ),
        this.receivedMedia_worker = e.data.framesReceived,
        this.receivedYUV = e.data.framesDecoded,
        this.receivedEmit = e.data.framesRendered,
        this.mediaBytesReceived = e.data.mediaBytesReceived,
        this.metaBytesReceived = e.data.metaBytesReceived,
        this.packetsLost = e.data.packetsLost,
        this.packetsDrop = e.data.packetsDrop,
        this.framesAwait = e.data.framesAwait,
        this.decodeTimePerFrame = e.data.decodeTimePerFrame,
        this.decodeTimeMaxFrame = e.data.decodeTimeMaxFrame,
        this.returnFrames = e.data.framesReturned,
        this.sendOutBuffer = e.data.sendOutBuffer,
        this.DecodeJankTimes = e.data.JankTimes,
        this.bigDecodeJankTimes = e.data.bigJankTimes,
        this.receiveIframes = e.data.receivedIframe,
        this.decodeIframes = e.data.decodedIframe
    }
    ReceiveDecodeMessage(e) {
        var n;
        if (!this.firstYUVReceived) {
            this.firstYUVDecoded = e.data.yuv_ts;
            const o = this.firstYUVDecoded - this.rtcp.network.room._startTime;
            log$m.infoAndReportMeasurement({
                metric: "firstYUVDecodedAt",
                value: o,
                group: "joinRoom"
            }),
            this.firstRender = Date.now();
            const a = this.firstYUVDecoded - this.rtcp.network.room._startTime;
            log$m.infoAndReportMeasurement({
                metric: "firstRenderAt",
                value: a,
                group: "joinRoom"
            }),
            this.firstYUVReceived = !0,
            this.lastRenderTs = Date.now()
        }
        !this.cachedRender[this.setPtr] && this.cachedMetas[this.setPtr] != null && (this.cachedStreams[this.setPtr] != null && this.cachedStreams[this.setPtr].byteLength != 0 && (e.data.data == null ? (this.executeFunction("stream", {
            stream: this.cachedStreams[this.setPtr],
            width: this.cachedResolution[this.setPtr].width,
            height: this.cachedResolution[this.setPtr].height,
            pts: this.cachedPtss[this.setPtr]
        }),
        this.executeFunction("signal", {
            signal: this.cachedMetas[this.setPtr],
            pts: this.cachedPtss[this.setPtr],
            alreadyUpdateYUV: !0
        })) : this.updateDropFrame += 1,
        this.decoderWorker.postMessage({
            t: 2,
            frameCnt: this.cachedPtss[this.setPtr],
            buffer: this.cachedStreams[this.setPtr]
        }, [this.cachedStreams[this.setPtr].buffer])),
        this.getPtr = (this.getPtr + 1) % this.cachedLength);
        const t = e.data.metadata;
        if ((n = t == null ? void 0 : t.traceIds) != null && n.length) {
            for (const o of t.traceIds)
                if (this.traceIdMap.has(o)) {
                    const a = this.traceIdMap.get(o);
                    a != null && (a.readyTime = Date.now(),
                    a.status = 2)
                }
        }
        if (e.data.pts == this.moveStartPts && (this.MoveProcessDelay = Date.now() - this.StartMovingTs),
        this.userId_test = this.rtcp.network.room.userId,
        this.inMovingMode) {
            const o = Date.now()
              , a = o - this.lastMoveProcessTime;
            this.moveProcessCircular.add(a),
            this.lastMoveProcessTime = o
        }
        const r = this.setPtr;
        this.cachedStreams[r] = e.data.data,
        this.cachedMetas[r] = e.data.metadata,
        this.cachedPtss[r] = e.data.pts,
        this.cachedRender[r] = !1,
        this.cachedResolution[r] = {
            width: e.data.width,
            height: e.data.height
        },
        this.setPtr = (this.setPtr + 1) % this.cachedLength
    }
    SendCacheFrameInfo(e) {
        var h, f, d, _, g, m, v;
        const t = e.data.cachedKey
          , r = e.data.metadata
          , n = t
          , o = r
          , a = (d = (f = (h = o.newUserStates) == null ? void 0 : h.find(y=>y.userId === this.rtcp.network.room.userId)) == null ? void 0 : f.playerState) == null ? void 0 : d.roomTypeId
          , s = this.rtcp.network.room.skinId
          , l = (v = (m = (g = (_ = o.newUserStates) == null ? void 0 : _.find(y=>y.userId === this._rtcp.network.room.userId)) == null ? void 0 : g.playerState) == null ? void 0 : m.player) == null ? void 0 : v.position
          , u = {
            MsgType: 1,
            FrameCacheMsg: {
                FrameIndex: n,
                RoomTypeId: a,
                SkinID: s,
                Position: l
            }
        };
        let c = "";
        try {
            c = JSON.stringify(u)
        } catch (y) {
            log$m.error(y);
            return
        }
    }
    ReceivePanoramaDecodeMessage(e) {
        log$m.info("Receive Panorama Image in Workers.ts"),
        MaskSetToOne(e.data.tileId, this.PanoView);
        let t = 0, r;
        const n = this.PendingMasks.length;
        for (t = 0; t < n; t++) {
            const o = this.PendingMasks[t].buffer
              , a = new DataView(o)
              , s = new ArrayBuffer(8)
              , l = new DataView(s);
            if (operateForDataView(this.PanoView, a, l, (u,c)=>c ^ u & c),
            IsAll0(l)) {
                r = this.PendingMasks[t].angle;
                break
            }
        }
        for (let o = t; o < n; o++)
            this.PendingMasks.pop();
        this.executeFunction("panorama", {
            data: e.data.data,
            tileId: e.data.tileId,
            pos: {
                x: e.data.x,
                y: e.data.y,
                z: e.data.z
            },
            uuid: e.data.uuid,
            finished: !0,
            matchAngle: r
        })
    }
    enable_decoder_queue_logging() {
        this.decoderWorker.postMessage({
            t: 100,
            status: !0
        })
    }
    disable_decoder_queue_logging() {
        this.decoderWorker.postMessage({
            t: 100,
            status: !1
        })
    }
    async init(e={
        width: 1280,
        height: 720
    }) {
        for (let r = 0; r < FRAME_COMPOSE_LENGTH; r++) {
            const n = {
                buffer: new Uint8Array(2621440),
                size: 0,
                startReceiveTime: 0,
                serverTime: 0,
                frameCnt: -1
            };
            this.cacheFrameComposes.push(n)
        }
        const t = new Blob([decoder],{
            type: "application/javascript"
        });
        return this.decoderWorker = new Worker(URL.createObjectURL(t)),
        this.decoderWorker.postMessage({
            t: 9,
            url: WASM_URLS[WASM_Version],
            jitterLength: DECODER_PASSIVE_JITTER
        }),
        this.decoderWorker.postMessage({
            t: 1,
            config: e
        }),
        new Promise(r=>{
            this.decoderWorker.onmessage = n=>{
                switch (n.data.t) {
                case 0:
                    this.ReceiveDecodeMessage(n);
                    break;
                case 1:
                    this.UpdateStats(n);
                    break;
                case 2:
                    r();
                    break;
                case 3:
                    this.SendCacheFrameInfo(n);
                    break;
                case 4:
                    {
                        const o = new Date().toISOString()
                          , a = USER_ID + "-" + PAGE_SESSION + "-" + SERVER_SESSION + "-" + o + ".264";
                        uploadStream(COS_PREFIX + a, n.data.fileObj);
                        break
                    }
                case 5:
                    this.executeFunction("signal", {
                        signal: n.data.metadata,
                        pts: -1,
                        alreadyUpdateYUV: !1
                    });
                    break;
                case 6:
                    log$m.infoAndReportMeasurement(n.data),
                    log$m.debug("WASM Ready Cost");
                    break;
                case 7:
                    this.ReceivePanoramaDecodeMessage(n);
                    break;
                case 8:
                    {
                        const o = {
                            MstType: 0
                        };
                        let a = "";
                        try {
                            a = JSON.stringify(o)
                        } catch (l) {
                            log$m.error(l);
                            return
                        }
                        const s = "wasm:" + a;
                        this._rtcp.sendStringData(s);
                        break
                    }
                case 9:
                    {
                        log$m.info(n.data.printMsg);
                        break
                    }
                case 10:
                    {
                        log$m.error(n.data.printMsg),
                        this.executeFunction("error", {
                            code: n.data.code,
                            message: n.data.printMsg
                        });
                        break
                    }
                default:
                    log$m.error("Receive unknown message event from decoder"),
                    log$m.debug(n.data);
                    break
                }
            }
        }
        )
    }
    UpdateYUV() {
        var t, r;
        const e = this.getPtr;
        if (this.cachedMetas[e] != null && !this.cachedRender[e]) {
            const n = Date.now();
            if (this.firstUpdateYUV) {
                const h = ((t = this.cachedStreams[e]) == null ? void 0 : t.byteLength) || 0;
                log$m.infoAndReportMeasurement({
                    metric: "firstUpdateStreamLength",
                    value: h,
                    group: "joinRoom"
                }),
                this.firstUpdateYUV = !1
            }
            this.cachedStreams[e] != null && this.executeFunction("stream", {
                stream: this.cachedStreams[e],
                width: this.cachedResolution[e].width,
                height: this.cachedResolution[e].height,
                pts: this.cachedPtss[e]
            });
            const o = Date.now();
            this.cachedStreams[e] != null && this.decoderWorker.postMessage({
                t: 2,
                frameCnt: this.cachedPtss[e],
                buffer: this.cachedStreams[e]
            }, [this.cachedStreams[e].buffer]);
            const a = Date.now()
              , s = o - n
              , l = a - o;
            (s > 33 || l > 10) && log$m.debug("[wwwarning] updateYUV takes ", s, " ms, postMessage takes ", l, " ms for index ", this.cachedPtss[e]),
            o - this.lastRenderTs > 84 && this.JankTimes++,
            o - this.lastRenderTs > 125 && this.bigJankTimes++,
            this.lastRenderTs = o;
            const u = o - n;
            this.updateYUVCircular.add(u);
            const c = this.cachedMetas[e];
            if ((r = c == null ? void 0 : c.traceIds) != null && r.length) {
                for (const h of c.traceIds)
                    if (this.traceIdMap.has(h)) {
                        const f = this.traceIdMap.get(h);
                        if (f != null) {
                            f.displayTime = Date.now(),
                            f.status = 3;
                            const d = f.receiveTime - f.startTime
                              , _ = f.readyTime - f.receiveTime
                              , g = f.displayTime - f.readyTime
                              , m = f.displayTime - f.startTime;
                            this.responseTimeArray.push(d),
                            this.processTimeArray.push(_),
                            this.displayTimeArray.push(g),
                            this.overallTimeArray.push(m),
                            this.traceIdMap.delete(h)
                        }
                    }
            }
            if (this.cachedPtss[e] == this.moveStartPts && (this.MoveDisplayDelay = Date.now() - this.StartMovingTs),
            this.inMovingMode) {
                const h = Date.now()
                  , f = h - this.lastMoveDisplayTime;
                this.moveDisplayCircular.add(f),
                this.lastMoveDisplayTime = h
            }
            this.executeFunction("signal", {
                signal: this.cachedMetas[e],
                pts: this.cachedPtss[e],
                alreadyUpdateYUV: !0
            }),
            this.cachedRender[e] = !0,
            this.getPtr = (this.getPtr + 1) % this.cachedLength
        }
    }
    unmarshalPano(e) {
        const t = new DataView(e);
        if (t.getUint32(0) != 1723558763)
            return !1;
        console.log("Receive Pano Message"),
        t.getUint16(4);
        const n = t.getUint16(6)
          , o = t.getUint32(8)
          , a = t.getUint32(12) - (1 << 30) * 2
          , s = t.getUint32(16) - (1 << 30) * 2
          , l = t.getUint32(20) - (1 << 30) * 2
          , u = t.getUint32(24)
          , c = new Uint8Array(e).subarray(28, 64)
          , h = String.fromCharCode.apply(null, c)
          , f = t.getUint32(64)
          , d = e.byteLength - n;
        if (d == u) {
            const g = {
                data: new Uint8Array(e).subarray(n),
                mediaLen: u,
                tileId: o,
                uuid: h,
                x: a,
                y: s,
                z: l
            };
            this.decoderWorker.postMessage({
                t: 8,
                data: g
            })
        } else {
            const _ = new Uint8Array(e,n,d);
            if (this.cachePanoTileID == o) {
                if (this.panoCacheBuffer.set(_, f),
                this.panoCacheSize += d,
                this.panoCacheSize === u) {
                    const m = {
                        data: new Uint8Array(this.panoCacheBuffer).slice(0, u),
                        mediaLen: u,
                        tileId: o,
                        uuid: h,
                        x: a,
                        y: s,
                        z: l
                    };
                    this.decoderWorker.postMessage({
                        t: 8,
                        data: m
                    }),
                    this.panoCacheSize = 0
                }
            } else
                this.panoCacheBuffer.set(_, f),
                this.panoCacheSize = d,
                this.cachePanoTileID = o
        }
        return !0
    }
    clearMoveArray() {
        this.MovingTraceId = "",
        this.inMovingMode = !1,
        this.StartMovingTs = 0,
        this.MoveToFrameCnt = 0,
        this.MoveResponseDelay = 0,
        this.MoveProcessDelay = 0,
        this.MoveDisplayDelay = 0,
        this.moveStartPts = -1,
        this.moveResponseCircular.clear(),
        this.moveProcessCircular.clear(),
        this.moveDisplayCircular.clear(),
        this.moveEvent = ""
    }
    getIsMoving(e) {
        let t;
        if (typeof e.newUserStates != "undefined")
            for (let r = 0; r < e.newUserStates.length; r++) {
                const n = e.newUserStates[r];
                if (n.userId == this.rtcp.network.room.userId) {
                    t = n.renderInfo.isMoving;
                    break
                }
            }
        return t
    }
    isHeartBeatPacket(e, t) {
        return new DataView(e).getUint32(0) == 2009889916
    }
    resetSendTimeDiff() {
        this.prevSenderTs = 0,
        this.serverSendTimeArray.clear()
    }
    calcSendTimeDiff(e) {
        if (this.prevSenderTs == -1) {
            this.prevSenderTs = e;
            return
        }
        const t = e - this.prevSenderTs;
        this.serverSendTimeArray.add(t),
        this.prevSenderTs = e
    }
    unmarshalStream(e) {
        var T, C, A, S, P, R, M, x, I, w;
        const t = new DataView(e);
        if (t.getUint32(0) != 1437227610)
            return !1;
        t.getUint16(4);
        const n = t.getUint16(6)
          , o = t.getUint16(8)
          , a = o
          , s = t.getUint16(10);
        let l = !1;
        s == 1 && (l = !0);
        const u = t.getUint32(12)
          , c = t.getUint32(16)
          , h = t.getUint32(20)
          , f = t.getUint16(24)
          , d = t.getUint16(26)
          , _ = t.getUint32(28)
          , g = t.getUint32(n - 4)
          , m = u + c
          , v = e.byteLength - n
          , y = new Uint8Array(e,n,v);
        this.calcSendTimeDiff(h);
        let b;
        if (this.inPanoMode && (c > 0 || f))
            return log$m.error("Stream Protocal Violation: receive illegal stream in Pano mode"),
            !0;
        if (v === m) {
            this.receivedMedia++;
            const O = new Uint8Array(e).subarray(n);
            h - this.lastServerTS > 60 ? this.serverFrameSlow++ : h - this.lastServerTS < 16 && this.serverFrameFast++;
            const D = Date.now();
            D - this.lastClientTS > 60 ? this.clientFrameSlow++ : D - this.lastClientTS < 16 && this.clientFrameFast++;
            const F = c === 0
              , V = h - this.lastServerTS;
            this.lastServerTS != 0 && ((o + 65536 - this.lastSeq) % 65536 === 1 && this.lastIsPureMeta == F && (F ? this.srvMetaIntervalCircular.add(V) : this.srvMediaIntervalCircular.add(V)),
            this.frameServerCircular.add(V),
            this.frameClientCircular.add(D - this.lastClientTS)),
            this.lastSeq = o,
            this.lastIsPureMeta = F,
            this.lastServerTS = h,
            this.lastClientTS = D;
            const N = O.subarray(0, u)
              , L = Date.now()
              , k = JSON.parse(this.Stringify(N))
              , U = Date.now();
            this.showAllReceivedMetadata && console.log(h, D, k),
            this.metaParseAraay.push(U - L),
            (T = k.traceIds) != null && T.length && this.processMetaWithTraceId(k),
            c != 0 && this.moveStartPts == -1 && this.inMovingMode && (this.moveStartPts = o),
            this.moveStartPts == o && (this.MoveResponseDelay = Date.now() - this.StartMovingTs,
            console.log("move response delay: ", o, this.moveStartPts, this.MoveResponseDelay));
            const z = this.getIsMoving(k);
            if (this.inMovingMode && z == 0 && this.lastIsMoving == 1 && this.clearMoveArray(),
            typeof z != "undefined" && (this.lastIsMoving = z),
            this.inMovingMode) {
                const G = Date.now()
                  , W = G - this.lastMoveResponseTime;
                this.moveResponseCircular.add(W),
                this.lastMoveResponseTime = G
            }
            (f || d) && (b = (P = (S = (A = (C = k.newUserStates) == null ? void 0 : C.find(G=>G.userId === this._rtcp.network.room.userId)) == null ? void 0 : A.playerState) == null ? void 0 : S.player) == null ? void 0 : P.position);
            const H = {
                t: 0,
                data: O,
                mediaLen: c,
                metaLen: u,
                metadata: k,
                frameCnt: a,
                server_ts: h,
                isIDR: l,
                cacheRequest: d,
                cached: f,
                cachedKey: _,
                position: b
            };
            if (this.inPanoMode)
                return this.executeFunction("signal", {
                    signal: k,
                    pts: -1,
                    alreadyUpdateYUV: !0
                }),
                !0;
            if (this.decoderWorker.postMessage(H, [O.buffer]),
            !this.firstMediaReceived) {
                this.firstMediaArraval = Date.now();
                const G = this.firstMediaArraval - this.rtcp.network.room._startTime;
                log$m.infoAndReportMeasurement({
                    metric: "firstMediaArravalAt",
                    value: G,
                    group: "joinRoom"
                }),
                this.firstMediaReceived = !0
            }
        } else {
            const O = this.hasFrmCntInCache(a);
            if (O != -1)
                if (this.cacheFrameComposes[O].buffer.set(y, g),
                this.cacheFrameComposes[O].size += v,
                this.cacheFrameComposes[O].size === m) {
                    const D = new Uint8Array(this.cacheFrameComposes[O].buffer).slice(0, m);
                    this.cacheFrameComposes[O].frameCnt = -1,
                    this.cacheFrameComposes[O].size = 0,
                    this.cacheFrameComposes[O].startReceiveTime = 0,
                    this.cacheFrameComposes[O].serverTime = 0,
                    this.receivedMedia++,
                    h - this.lastServerTS > 60 ? this.serverFrameSlow++ : h - this.lastServerTS < 16 && this.serverFrameFast++;
                    const F = Date.now();
                    F - this.lastClientTS > 60 ? this.clientFrameSlow++ : F - this.lastClientTS < 16 && this.clientFrameFast++,
                    this.lastServerTS != 0 && (this.frameServerCircular.add(h - this.lastServerTS),
                    this.frameClientCircular.add(F - this.lastClientTS)),
                    this.lastServerTS = h,
                    this.lastClientTS = F;
                    const V = D.subarray(0, u)
                      , N = Date.now()
                      , L = JSON.parse(this.Stringify(V))
                      , k = Date.now();
                    this.showAllReceivedMetadata && console.log(h, F, L),
                    this.metaParseAraay.push(k - N),
                    (R = L.traceIds) != null && R.length && this.processMetaWithTraceId(L),
                    c != 0 && this.moveStartPts == -1 && this.inMovingMode && (this.moveStartPts = o),
                    this.moveStartPts == o && (this.MoveResponseDelay = Date.now() - this.StartMovingTs);
                    const U = this.getIsMoving(L);
                    if (this.inMovingMode && U == 0 && this.lastIsMoving == 1 && this.clearMoveArray(),
                    typeof U != "undefined" && (this.lastIsMoving = U),
                    this.inMovingMode) {
                        const H = Date.now()
                          , G = H - this.lastMoveResponseTime;
                        this.moveResponseCircular.add(G),
                        this.lastMoveResponseTime = H
                    }
                    (f || d) && (b = (w = (I = (x = (M = L.newUserStates) == null ? void 0 : M.find(H=>H.userId === this._rtcp.network.room.userId)) == null ? void 0 : x.playerState) == null ? void 0 : I.player) == null ? void 0 : w.position);
                    const z = {
                        t: 0,
                        data: D,
                        mediaLen: c,
                        metaLen: u,
                        metadata: L,
                        frameCnt: a,
                        server_ts: h,
                        isIDR: l,
                        cacheRequest: d,
                        cached: f,
                        cachedKey: _,
                        position: b
                    };
                    if (this.inPanoMode)
                        return this.executeFunction("signal", {
                            signal: L,
                            pts: -1,
                            alreadyUpdateYUV: !0
                        }),
                        !0;
                    if (this.decoderWorker.postMessage(z, [D.buffer]),
                    !this.firstMediaReceived) {
                        this.firstMediaArraval = Date.now();
                        const H = this.firstMediaArraval - this.rtcp.network.room._startTime;
                        log$m.infoAndReportMeasurement({
                            metric: "firstMediaArravalAt",
                            value: H,
                            group: "joinRoom"
                        }),
                        this.firstMediaReceived = !0
                    }
                } else
                    this.cacheFrameComposes[O].size > m && log$m.debug("I frame exceed, cache size is ", this.cacheSize, ", total size is ", m);
            else if (O == -1) {
                let D = this.hasFrmCntInCache(-1);
                if (D == -1) {
                    let F = Date.now() + 1e18
                      , V = -1;
                    for (let N = 0; N < this.cacheFrameComposes.length; N++)
                        this.cacheFrameComposes[N].serverTime < F && (F = this.cacheFrameComposes[N].serverTime,
                        V = N);
                    D = V
                }
                this.cacheFrameComposes[D].buffer.set(y, g),
                this.cacheFrameComposes[D].size = v,
                this.cacheFrameComposes[D].frameCnt = a,
                this.cacheFrameComposes[D].startReceiveTime = Date.now(),
                this.cacheFrameComposes[D].serverTime = h
            }
        }
        return !0
    }
    reset() {
        log$m.debug("Worker reset is called"),
        this.cacheFrameCnt = 0,
        this.receivedMedia = 0,
        this.reconnectSignal = !0,
        this.decoderWorker.postMessage({
            t: 4
        })
    }
    dataHandleOff(e) {
        log$m.debug("hhh")
    }
    dataHandle(e) {
        this.saveframe && (this.decoderWorker.postMessage({
            t: 6
        }),
        this.saveframe = !1),
        this.SaveMediaStream && (this.decoderWorker.postMessage({
            t: 7
        }),
        this.SaveMediaStream = !1);
        const t = new Uint8Array(e);
        if (t.length >= 4 && this.isHeartBeatPacket(t.buffer, t.length) == !0)
            return;
        if (t.length > 36 && this.unmarshalStream(t.buffer) == !0) {
            this.reconnectSignal && (this.executeFunction("reconnectedFrame", {}),
            this.reconnectSignal = !1);
            return
        }
        if (t.length > 20 && this.unmarshalPano(t.buffer) == !0)
            return;
        this.noWasmBytesReceived += e.byteLength;
        const r = JSON.parse(this.Stringify(t));
        this.executeFunction("signal", {
            signal: r,
            pts: -1,
            alreadyUpdateYUV: !0
        })
    }
    changePanoMode(e) {
        this.inPanoMode = e
    }
    uploadDataToServer() {
        this.DynamicPanoTest == !0 && (this.onRotateInPanoMode({
            traceId: "b2e1a296-6438-4371-8a31-687beb724ebe"
        }),
        this.DynamicPanoTest = !1);
        function e(ie, ee) {
            return ee == -1 && (ee = 0),
            ie + ee
        }
        function t(ie, ee) {
            return Math.max(ie, ee)
        }
        const r = this.responseTimeArray.reduce(e, 0) / this.responseTimeArray.length || 0
          , n = this.processTimeArray.reduce(e, 0) / this.processTimeArray.length || 0
          , o = this.displayTimeArray.reduce(e, 0) / this.displayTimeArray.length || 0
          , a = this.overallTimeArray.reduce(e, 0) / this.overallTimeArray.length || 0
          , s = this.overallTimeArray.length;
        this.responseTimeArray = [],
        this.processTimeArray = [],
        this.displayTimeArray = [],
        this.overallTimeArray = [];
        const l = this.moveResponseCircular.getThreshPercent()
          , u = l[0]
          , c = l[1]
          , h = l[2]
          , f = l[3]
          , d = l[4]
          , _ = d - f
          , g = 1 - c / d || 0
          , m = [u, c - u, h - c, f - h, _]
          , v = this.moveProcessCircular.getThreshPercent()
          , y = v[0]
          , b = v[1]
          , T = v[2]
          , C = v[3]
          , A = v[4]
          , S = A - C
          , P = 1 - b / A || 0
          , R = [y, b - y, T - b, C - T, S]
          , M = this.moveDisplayCircular.getThreshPercent()
          , x = M[0]
          , I = M[1]
          , w = M[2]
          , O = M[3]
          , D = M[4]
          , F = D - O
          , V = 1 - I / D || 0
          , N = [x, I - x, w - I, O - w, F]
          , L = x
          , k = I - x
          , U = w - I
          , z = O - w
          , H = F
          , G = this.moveResponseCircular.getAvg()
          , W = this.moveProcessCircular.getAvg()
          , j = this.moveDisplayCircular.getAvg()
          , B = this.moveResponseCircular.getMax()
          , X = this.moveProcessCircular.getMax()
          , $ = this.moveDisplayCircular.getMax()
          , Y = this.moveResponseCircular.getStandardDeviation()
          , K = this.moveProcessCircular.getStandardDeviation()
          , Z = this.moveDisplayCircular.getStandardDeviation();
        this.moveResponseCircular.getIncomingAvg(),
        this.moveProcessCircular.getIncomingAvg(),
        this.moveDisplayCircular.getIncomingAvg(),
        this.moveResponseCircular.getIncomingMax(),
        this.moveProcessCircular.getIncomingMax(),
        this.moveDisplayCircular.getIncomingMax(),
        this.moveResponseCircular.clearIncoming(),
        this.moveProcessCircular.clearIncoming(),
        this.moveDisplayCircular.clearIncoming();
        const q = this.frameServerCircular.getAvg()
          , J = this.frameServerCircular.getMax();
        this.frameClientCircular.getAvg(),
        this.frameClientCircular.getMax();
        const Q = this.metaParseAraay.reduce(e, 0) / this.metaParseAraay.length || 0
          , te = this.metaParseAraay.reduce(t, 0);
        this.metaParseAraay = [];
        const re = {
            mediaBytesReceived: this.mediaBytesReceived,
            metaBytesReceived: this.metaBytesReceived,
            packetsLost: this.packetsLost,
            timestamp: Date.now(),
            frameHeight: 1280,
            frameWidth: 720,
            framesReceived: this.receivedMedia,
            framesReceivedWorker: this.receivedMedia_worker,
            framesDecoded: this.receivedYUV,
            framesEmited: this.receivedEmit,
            decodeTimePerFrame: this.decodeTimePerFrame,
            decodeTimeMaxFrame: this.decodeTimeMaxFrame,
            packetsDrop: this.packetsDrop,
            framesAwait: this.framesAwait,
            firstMediaArraval: this.firstMediaArraval,
            firstYUVDecoded: this.firstYUVDecoded,
            firstRender: this.firstRender,
            returnFrames: this.returnFrames,
            sendOutBuffer: this.sendOutBuffer,
            maxGraphicTime: this.updateYUVCircular.getMax(),
            averageGraphicTime: this.updateYUVCircular.getAvg(),
            jankTimes: this.JankTimes,
            bigJankTimes: this.bigJankTimes,
            decodeJankTimes: this.DecodeJankTimes,
            bigDecodeJankTimes: this.bigDecodeJankTimes,
            serverFrameSlow: this.serverFrameSlow,
            serverFrameFast: this.serverFrameFast,
            clientFrameSlow: this.clientFrameSlow,
            clientFrameFast: this.clientFrameFast,
            rtcMessageReceived: this.rtcMessageReceived,
            rtcBytesReceived: this.rtcBytesReceived - this.noWasmBytesReceived,
            receiveIframes: this.receiveIframes,
            decodeIframes: this.decodeIframes,
            avgResponseTime: r,
            avgProcessTime: n,
            avgDisplayTime: o,
            avgOverallTime: a,
            overallTimeCount: s,
            responseMiss: this.responseMiss,
            processMiss: this.processMiss,
            displayMiss: this.displayMiss,
            updateDropFrame: this.updateDropFrame,
            moveEvent: this.moveEvent,
            avgResponseMoveDiff: this.moveEvent == "MoveTo" ? G : 0,
            avgProcessMoveDiff: this.moveEvent == "MoveTo" ? W : 0,
            avgDisplayMoveDiff: this.moveEvent == "MoveTo" ? j : 0,
            maxResponseMoveDiff: this.moveEvent == "MoveTo" ? B : 0,
            maxProcessMoveDiff: this.moveEvent == "MoveTo" ? X : 0,
            maxDisplayMoveDiff: this.moveEvent == "MoveTo" ? $ : 0,
            moveResponseJank: this.moveEvent == "MoveTo" ? g : 0,
            moveProcessJank: this.moveEvent == "MoveTo" ? P : 0,
            moveDisplayJank: this.moveEvent == "MoveTo" ? V : 0,
            moveResponseCounts: this.moveEvent == "MoveTo" ? m.toString() : "0,0,0,0,0",
            moveProcessCounts: this.moveEvent == "MoveTo" ? R.toString() : "0,0,0,0,0",
            moveDisplayCounts: this.moveEvent == "MoveTo" ? N.toString() : "0,0,0,0,0",
            MoveDisplayCountGood: this.moveEvent == "MoveTo" ? L.toString() : "0",
            MoveDisplayCountWell: this.moveEvent == "MoveTo" ? k.toString() : "0",
            MoveDisplayCountFair: this.moveEvent == "MoveTo" ? U.toString() : "0",
            MoveDisplayCountBad: this.moveEvent == "MoveTo" ? z.toString() : "0",
            MoveDisplayCountRest: this.moveEvent == "MoveTo" ? H.toString() : "0",
            moveResponseDelay: this.moveEvent == "MoveTo" ? this.MoveResponseDelay : 0,
            moveProcessDelay: this.moveEvent == "MoveTo" ? this.MoveProcessDelay : 0,
            moveDisplayDelay: this.moveEvent == "MoveTo" ? this.MoveDisplayDelay : 0,
            sdMoveResponseLongTime: Y,
            sdMoveProcessLongTime: K,
            sdMoveDisplayLongTime: Z,
            avgResponseFlyDiff: this.moveEvent == "GetOnVehicle" || this.moveEvent == "GetOnAirship" ? G : 0,
            avgProcessFlyDiff: this.moveEvent == "GetOnVehicle" || this.moveEvent == "GetOnAirship" ? W : 0,
            avgDisplayFlyDiff: this.moveEvent == "GetOnVehicle" || this.moveEvent == "GetOnAirship" ? j : 0,
            maxResponseFlyDiff: this.moveEvent == "GetOnVehicle" || this.moveEvent == "GetOnAirship" ? B : 0,
            maxProcessFlyDiff: this.moveEvent == "GetOnVehicle" || this.moveEvent == "GetOnAirship" ? X : 0,
            maxDisplayFlyDiff: this.moveEvent == "GetOnVehicle" || this.moveEvent == "GetOnAirship" ? $ : 0,
            flyResponseJank: this.moveEvent == "GetOnVehicle" || this.moveEvent == "GetOnAirship" ? g : 0,
            flyProcessJank: this.moveEvent == "GetOnVehicle" || this.moveEvent == "GetOnAirship" ? P : 0,
            flyDisplayJank: this.moveEvent == "GetOnVehicle" || this.moveEvent == "GetOnAirship" ? V : 0,
            flyResponseCounts: this.moveEvent == "GetOnVehicle" || this.moveEvent == "GetOnAirship" ? m.toString() : "0,0,0,0,0",
            flyProcessCounts: this.moveEvent == "GetOnVehicle" || this.moveEvent == "GetOnAirship" ? R.toString() : "0,0,0,0,0",
            flyDisplayCounts: this.moveEvent == "GetOnVehicle" || this.moveEvent == "GetOnAirship" ? N.toString() : "0,0,0,0,0",
            flyResponseDelay: this.moveEvent == "GetOnVehicle" || this.moveEvent == "GetOnAirship" ? this.MoveResponseDelay : 0,
            flyProcessDelay: this.moveEvent == "GetOnVehicle" || this.moveEvent == "GetOnAirship" ? this.MoveProcessDelay : 0,
            flyDisplayDelay: this.moveEvent == "GetOnVehicle" || this.moveEvent == "GetOnAirship" ? this.MoveDisplayDelay : 0,
            avgMetaParseTime: Q,
            maxMetaParseTime: te,
            avgServerDiff: q,
            maxServerDiff: J,
            streamType: WASM_Version
        };
        return this.lastReturnFrames = this.returnFrames,
        this.lastReceivedEmit = this.receivedEmit,
        re
    }
}
const log$l = new Logger("rtcp");
class Rtcp extends EventEmitter {
    constructor(e) {
        super();
        E(this, "connection", null);
        E(this, "inputChannel", null);
        E(this, "mediaStream");
        E(this, "socket");
        E(this, "connected", !1);
        E(this, "candidates", []);
        E(this, "isAnswered", !1);
        E(this, "isFlushing", !1);
        E(this, "inputReady", !1);
        E(this, "workers");
        E(this, "actived", !0);
        E(this, "heartbeat");
        E(this, "onIcecandidate", e=>{
            if (e.candidate != null) {
                const t = JSON.stringify(e.candidate);
                log$l.debug(`Got ice candidate: ${t}`),
                this.network.socket.send({
                    id: "ice_candidate",
                    data: btoa(t)
                })
            }
        }
        );
        E(this, "onIcecandidateerror", e=>{
            log$l.error("onicecandidateerror", e.errorCode, e.errorText, e)
        }
        );
        E(this, "onIceStateChange", e=>{
            switch (e.target.iceGatheringState) {
            case "gathering":
                log$l.info("ice gathering");
                break;
            case "complete":
                log$l.info("Ice gathering completed")
            }
        }
        );
        E(this, "onIceConnectionStateChange", ()=>{
            if (!!this.connection)
                switch (log$l.info(`iceConnectionState: ${this.connection.iceConnectionState}`),
                this.connection.iceConnectionState) {
                case "connected":
                    {
                        this.connected = !0;
                        break
                    }
                case "disconnected":
                    {
                        this.connected = !1,
                        this.emit("rtcDisconnected");
                        break
                    }
                case "failed":
                    {
                        this.emit("rtcDisconnected"),
                        this.connected = !1;
                        break
                    }
                }
        }
        );
        E(this, "setRemoteDescription", async(e,t)=>{
            var a, s, l;
            if (!this.connection)
                return;
            const r = JSON.parse(atob(e))
              , n = new RTCSessionDescription(r);
            await this.connection.setRemoteDescription(n);
            const o = await this.connection.createAnswer();
            if (o.sdp = (a = o.sdp) == null ? void 0 : a.replace(/(a=fmtp:111 .*)/g, "$1;stereo=1;sprop-stereo=1"),
            ((l = (s = o.sdp) == null ? void 0 : s.match(/a=mid:1/g)) == null ? void 0 : l.length) == 2) {
                const u = o.sdp.lastIndexOf("a=mid:1");
                o.sdp = o.sdp.slice(0, u) + "a=mid:2" + o.sdp.slice(u + 7)
            }
            try {
                await this.connection.setLocalDescription(o)
            } catch (u) {
                log$l.error("error", u)
            }
            this.isAnswered = !0,
            this.network.rtcp.flushCandidate(),
            this.network.socket.send({
                id: "answer",
                data: btoa(JSON.stringify(o))
            }),
            t.srcObject = this.mediaStream
        }
        );
        E(this, "flushCandidate", ()=>{
            this.isFlushing || !this.isAnswered || (this.isFlushing = !0,
            this.candidates.forEach(e=>{
                const t = atob(e)
                  , r = JSON.parse(t);
                if (/172\./.test(r.candidate))
                    return;
                const n = new RTCIceCandidate(r);
                this.connection && this.connection.addIceCandidate(n).then(()=>{}
                , o=>{
                    log$l.info("add candidate failed", o)
                }
                )
            }
            ),
            this.isFlushing = !1)
        }
        );
        E(this, "input", e=>{
            var t;
            !this.actived || !this.inputChannel || this.inputChannel.readyState === "open" && ((t = this.inputChannel) == null || t.send(e))
        }
        );
        this.network = e,
        this.workers = new Workers(this,new Logger("decode")),
        this.workers.registerLogger(new Logger("decode")),
        this.workers.registerFunction("data", t=>{
            this.emit("data", t)
        }
        ),
        this.heartbeat = new Heartbeat({
            ping: t=>{
                e.room.actionsHandler.echo(t)
            }
            ,
            pong(t, r) {
                var n;
                r && t > 500 && log$l.warn(`high hb value ${t}, traceId:` + r),
                (n = e.room.stats) == null || n.assign({
                    hb: t
                })
            }
        })
    }
    start() {
        this.connection = new RTCPeerConnection;
        const e = Date.now();
        this.connection.ondatachannel = t=>{
            log$l.info(`ondatachannel: ${t.channel.label}`),
            this.inputChannel = t.channel,
            this.inputChannel.onopen = ()=>{
                var r;
                log$l.info("The input channel has opened, id:", (r = this.inputChannel) == null ? void 0 : r.id),
                this.inputReady = !0,
                this.emit("rtcConnected"),
                this.network.room.currentNetworkOptions.reconnect || (log$l.infoAndReportMeasurement({
                    metric: "datachannelOpenedAt",
                    startTime: this.network.room._startTime,
                    group: "joinRoom"
                }),
                log$l.infoAndReportMeasurement({
                    metric: "datachannelOpenedCost",
                    startTime: e,
                    group: "joinRoom"
                }))
            }
            ,
            this.inputChannel.onclose = ()=>{
                var r;
                return log$l.info("The input channel has closed, id:", (r = this.inputChannel) == null ? void 0 : r.id)
            }
            ,
            this.inputChannel.onmessage = r=>{
                this.workers.dataHandle(r.data)
            }
        }
        ,
        this.connection.oniceconnectionstatechange = this.onIceConnectionStateChange,
        this.connection.onicegatheringstatechange = this.onIceStateChange,
        this.connection.onicecandidate = this.onIcecandidate,
        this.connection.onicecandidateerror = this.onIcecandidateerror,
        this.network.socket.send({
            id: "init_webrtc",
            data: JSON.stringify({
                is_mobile: !0
            })
        })
    }
    addCandidate(e) {
        e === "" ? this.network.rtcp.flushCandidate() : this.candidates.push(e)
    }
    disconnect() {
        var e, t, r;
        this.heartbeat.stop(),
        log$l.info("ready to close datachannel, id", (e = this.inputChannel) == null ? void 0 : e.id),
        (t = this.inputChannel) == null || t.close(),
        (r = this.connection) == null || r.close(),
        this.connection = null,
        this.inputChannel = null
    }
    sendStringData(e) {
        this.input(e)
    }
    sendData(e) {
        let t = "";
        try {
            t = JSON.stringify(e)
        } catch (r) {
            log$l.error(r);
            return
        }
        this.input(t)
    }
}
class Timeout {
    constructor(e, t, r=!0) {
        E(this, "_fn");
        E(this, "_delay");
        E(this, "_timeout");
        this._fn = e,
        this._delay = t,
        r && this.start()
    }
    get delay() {
        return this._delay
    }
    get isSet() {
        return !!this._timeout
    }
    setDelay(e) {
        this._delay = e
    }
    start() {
        this.isSet || (this._timeout = window.setTimeout(()=>{
            const e = this._fn;
            this.clear(),
            e()
        }
        , this._delay))
    }
    clear() {
        window.clearTimeout(this._timeout),
        this._timeout = void 0
    }
    reset() {
        this.clear(),
        this.start()
    }
}
const log$k = new Logger("ws");
class Socket extends EventEmitter {
    constructor(e) {
        super();
        E(this, "_ws");
        E(this, "_openTimer");
        E(this, "connected", !1);
        E(this, "_hasTimeout", !1);
        E(this, "heartbeat");
        E(this, "latency", (e,t)=>this.send({
            id: "checkLatency",
            data: JSON.stringify(e),
            packet_id: t
        }));
        E(this, "send", e=>{
            if (this.wsNoReady())
                return;
            const t = JSON.stringify(e);
            e.id !== "heartbeat" && log$k.info("send ws frame", t),
            this._ws.send(t)
        }
        );
        E(this, "startGame", ()=>{
            const {roomId: e, userId: t, avatarId: r, skinId: n, role: o, avatarComponents: a, versionId: s, rotationRenderType: l, isAllSync: u, nickname: c, avatarScale: h, appId: f, camera: d, player: _, firends: g, syncByEvent: m, areaName: v, attitude: y, pathName: b, person: T, roomTypeId: C="", syncToOthers: A, hasAvatar: S, prioritySync: P, extra: R={}, removeWhenDisconnected: M} = this.network.room.currentNetworkOptions;
            R.removeWhenDisconnected = M;
            const x = {
                id: "start",
                room_id: e,
                user_id: t,
                trace_id: uuid$1(),
                data: JSON.stringify({
                    avatar_components: JSON.stringify(a),
                    avatar_id: r,
                    skin_id: n,
                    is_host: o ? o == "host" : !0,
                    skin_data_version: n !== void 0 && s !== void 0 ? n + s : void 0,
                    rotation_render_type: l,
                    is_all_sync: u,
                    nick_name: encodeURIComponent(c || ""),
                    app_id: f,
                    camera: d,
                    player: _,
                    person: T,
                    firends: JSON.stringify(g),
                    sync_by_event: m,
                    area_name: v,
                    path_name: b,
                    attitude: y,
                    room_type_id: C,
                    syncToOthers: A,
                    hasAvatar: S,
                    avatarSize: h,
                    prioritySync: P,
                    extra: JSON.stringify(R)
                })
            };
            this.send(x),
            log$k.warn("startGame", le(oe({}, x), {
                data: JSON.parse(x.data)
            }))
        }
        );
        this.network = e,
        this.heartbeat = new Heartbeat({
            ping: t=>{
                var r;
                if (!this.connected) {
                    this.heartbeat.stop(),
                    (r = e.room.stats) == null || r.assign({
                        rtt: 0
                    });
                    return
                }
                this.send({
                    id: "heartbeat",
                    data: t
                })
            }
            ,
            pong(t) {
                var r;
                (r = e.room.stats) == null || r.assign({
                    rtt: t
                })
            }
        })
    }
    get connection() {
        return this._ws
    }
    start() {
        this._hasTimeout = !1;
        const e = this.getAddress();
        log$k.info(`connecting to ${e}`);
        const t = Date.now();
        this._ws = new WebSocket(e),
        this._openTimer = new Timeout(()=>{
            const r = `Failed to open websocket in ${DEFAULT_OPEN_TIMEOUT_MS} ms`;
            this._hasTimeout = !0,
            this.emit("socketClosed", new InitNetworkTimeoutError(r))
        }
        ,DEFAULT_OPEN_TIMEOUT_MS),
        this._ws.onopen = ()=>{
            var r;
            (r = this._openTimer) == null || r.clear(),
            this.connected = !0,
            this.heartbeat.start(),
            this.network.room.currentNetworkOptions.reconnect || (log$k.infoAndReportMeasurement({
                metric: "wsOpenedAt",
                group: "joinRoom",
                startTime: this.network.room._startTime
            }),
            log$k.infoAndReportMeasurement({
                metric: "wsOpenedCost",
                group: "joinRoom",
                startTime: t
            }))
        }
        ,
        this.handleWSEvent()
    }
    getAddress() {
        const {wsServerUrl: e, reconnect: t, sessionId: r, token: n, roomId: o, userId: a, pageSession: s} = this.network.room.currentNetworkOptions
          , l = this.network.room.skinId;
        let u = e;
        t && (u = u + `?reconnect=true&lastSessionID=${r}`);
        const c = `userId=${a}&roomId=${o}&pageSession=${s}` + (this.network.room.isHost ? `&skinId=${l}` : "") + (n ? `&token=${n}` : "");
        return u = u.indexOf("?") > -1 ? u + "&" + c : u + "?" + c,
        u
    }
    handleWSEvent() {
        const e = this._ws;
        e.addEventListener("error", t=>{
            this.connected = !1,
            log$k.error("webscoket error", t),
            this.emit("socketClosed", new InternalError("connect to address error: " + this.network.room.currentNetworkOptions.wsServerUrl))
        }
        ),
        e.addEventListener("close", t=>{
            this.connected = !1,
            this._onClose(t)
        }
        ),
        e.addEventListener("message", t=>{
            if (!t || this._hasTimeout || !this.connected)
                return;
            let r = null;
            try {
                r = JSON.parse(t.data)
            } catch (o) {
                log$k.error(o);
                return
            }
            if (!r)
                return;
            const n = r.id;
            if (!!n)
                switch (n !== "heartbeat" && log$k.info(`receive ws frame: ${t.data}`),
                n) {
                case "fail":
                    break;
                case "init":
                    try {
                        const o = r.data.slice(-37, -1);
                        reporter.updateBody({
                            serverSession: o
                        })
                    } catch (o) {
                        console.error(o)
                    }
                    this.network.rtcp.start();
                    break;
                case "heartbeat":
                    this.heartbeat.pong(r.data);
                    break;
                case "offer":
                    this.network.rtcp.setRemoteDescription(r.data, this.network.stream.el);
                    break;
                case "ice_candidate":
                    this.network.rtcp.addCandidate(r.data);
                    break;
                case "start":
                    this.emit("gameRoomAvailable", r);
                    break;
                case "error":
                    try {
                        const {Code: o, Msg: a} = JSON.parse(r.data);
                        if (o) {
                            if (o == 3003)
                                return this.emit("socketClosed", new TokenExpiredError);
                            if (authenticationErrorCodes.indexOf(o) > -1)
                                return this.emit("socketClosed", new AuthenticationError("\u9274\u6743\u9519\u8BEF:" + a));
                            {
                                const s = getErrorByCode(o);
                                this.emit("socketClosed", new s(a))
                            }
                        }
                    } catch (o) {
                        log$k.error(o),
                        this.emit("socketClosed", new InternalError(r.data))
                    }
                    break;
                case "checkLatency":
                    {
                        const o = r.packet_id
                          , a = r.data.split(",");
                        this.onLatencyCheck({
                            packetId: o,
                            addresses: a
                        });
                        break
                    }
                default:
                    log$k.warn("unkown ws message type", n, r)
                }
        }
        )
    }
    onLatencyCheck(e) {
        const t = [...new Set(e.addresses || [])];
        Promise.all(t.map(r=>({
            [r]: 9999
        }))).then(r=>{
            const n = Object.assign({}, ...r);
            this.latency(n, e.packetId)
        }
        )
    }
    wsNoReady() {
        return this._ws.readyState == WebSocket.CLOSED || this._ws.readyState == WebSocket.CLOSING || this._ws.readyState == WebSocket.CONNECTING
    }
    prepareReconnect() {
        this._close({
            code: WS_CLOSE_RECONNECT,
            reason: "reconnect"
        })
    }
    _onClose({code: e, reason: t}) {
        this._openTimer && this._openTimer.clear(),
        log$k.warn(`ws closed: ${e} ` + t),
        [WS_CLOSE_RECONNECT, WS_CLOSE_NORMAL].includes(e) || this.emit("socketClosed", new InternalError("Websocket error"))
    }
    _close({code: e, reason: t}) {
        var r;
        (r = this._ws) == null || r.close(e, t)
    }
    quit() {
        this._close({
            code: WS_CLOSE_NORMAL,
            reason: "quit"
        })
    }
}
const log$j = new Logger("stream");
class Stream {
    constructor(e) {
        E(this, "el");
        E(this, "_streamPlayTimer", null);
        E(this, "play", ()=>new Promise((e,t)=>{
            this._streamPlayTimer = new Timeout(()=>{
                t(new InternalError("Stream play timeout"))
            }
            ,5e3),
            this.el && this.el.play().then(()=>{
                var r;
                e(),
                log$j.info("Media can autoplay"),
                (r = this._streamPlayTimer) == null || r.clear()
            }
            ).catch(r=>{
                var n;
                log$j.error("Media Failed to autoplay"),
                log$j.error(r),
                t(new InternalError("Media Failed to autoplay")),
                (n = this._streamPlayTimer) == null || n.clear()
            }
            )
        }
        ));
        if (!e) {
            this.el = this.createVideoElement();
            return
        }
        this.el = e
    }
    createVideoElement() {
        const e = document.createElement("video");
        return e.muted = !0,
        e.autoplay = !1,
        e.playsInline = !0,
        e.setAttribute("autostart", "false"),
        e.setAttribute("controls", "controls"),
        e.setAttribute("muted", "true"),
        e.setAttribute("preload", "auto"),
        e.setAttribute("hidden", "hidden"),
        document.body.appendChild(e),
        e
    }
}
const log$i = new Logger("NetworkController");
class NetworkController extends EventEmitter {
    constructor(e) {
        super();
        E(this, "socket");
        E(this, "rtcp");
        E(this, "stream");
        E(this, "_state", "connecting");
        E(this, "_networkMonitor");
        E(this, "blockedActions", []);
        E(this, "reconnectCount", 0);
        E(this, "startGame", ()=>new Promise((e,t)=>{
            if (!this.rtcp.connected)
                return t(new InternalError("Game cannot load. Please refresh"));
            if (!this.rtcp.inputReady)
                return t(new InternalError("Game is not ready yet. Please wait"));
            this.socket.on("gameRoomAvailable", r=>{
                this.setState("connected"),
                e(r),
                this.rtcp.heartbeat.start()
            }
            ),
            this.socket.on("socketClosed", r=>{
                t(r)
            }
            ),
            this.socket.startGame()
        }
        ));
        this.room = e,
        this.socket = new Socket(this),
        this.rtcp = new Rtcp(this),
        this.stream = new Stream,
        this._networkMonitor = new NetworkMonitor(()=>{
            log$i.info("network changed, online:", this._networkMonitor.isOnline),
            this._state === "disconnected" && this._networkMonitor.isOnline && (log$i.info("network back to online, try to reconnect"),
            this.reconnect())
        }
        ),
        checkNetworkQuality(this.room.currentNetworkOptions.wsServerUrl),
        this._networkMonitor.start(),
        new VisibilityChangeHandler().subscribe(r=>{
            var n, o;
            r ? ((o = this.room.stats) == null || o.disable(),
            log$i.infoAndReportMeasurement({
                metric: "pageHide",
                startTime: Date.now()
            })) : ((n = this.room.stats) == null || n.enable(),
            log$i.infoAndReportMeasurement({
                metric: "pageShow",
                startTime: Date.now(),
                extra: {
                    state: this._state
                }
            }),
            this._state === "disconnected" && this.reconnect())
        }
        )
    }
    addBlockedActions(e) {
        this.blockedActions.push(...e)
    }
    removeBlockedActions(e) {
        if (!e) {
            this.blockedActions = [];
            return
        }
        const t = this.blockedActions.indexOf(e);
        this.blockedActions.splice(t, 1)
    }
    setState(e) {
        this._state !== e && (log$i.info("Set network state to ", e),
        this._state = e)
    }
    async connectAndStart(e) {
        return this.connect(e).then(this.startGame)
    }
    async connect(e=!1) {
        return this.room.updateCurrentNetworkOptions({
            reconnect: e
        }),
        new Promise((t,r)=>{
            this.rtcp.on("rtcConnected", ()=>{
                this.setState("connected"),
                t()
            }
            ),
            this.rtcp.on("rtcDisconnected", ()=>{
                log$i.info("rtc disconnected"),
                this._state === "connecting" ? (this.setState("disconnected"),
                r(new InternalError("rtc connect failed"))) : (this.setState("disconnected"),
                log$i.info("rtc disconnected, start to reconnect"),
                this.reconnect())
            }
            ),
            this.socket.on("socketQuit", ()=>{
                log$i.info("socket quit success"),
                this.setState("closed")
            }
            ),
            this.socket.on("socketClosed", n=>{
                this._state === "connecting" && (this.setState("disconnected"),
                r(n)),
                r(n)
            }
            ),
            this.socket.start()
        }
        )
    }
    reconnect() {
        if (this.room.viewMode === "observer")
            return;
        const e = Date.now();
        if (this.reconnectCount++,
        this.reconnectCount > MAX_RECONNECT_COUNT) {
            log$i.error("reconnect failed, reached max reconnect count", MAX_RECONNECT_COUNT),
            this.reconnectCount = 0,
            this.emit("stateChanged", {
                state: "disconnected"
            });
            return
        }
        return log$i.info("start reconnect, count:", this.reconnectCount),
        this._reconnect().then(()=>{
            log$i.infoAndReportMeasurement({
                startTime: e,
                metric: "reconnect"
            })
        }
        ).catch(t=>{
            if (log$i.infoAndReportMeasurement({
                startTime: e,
                metric: "reconnect",
                error: t
            }),
            t.code === Codes$1.RepeatLogin) {
                this.room.handleRepetLogin();
                return
            }
            const r = 1e3;
            log$i.info("reconnect failed, wait " + r + " ms for next reconnect"),
            setTimeout(()=>{
                this.reconnect()
            }
            , r)
        }
        )
    }
    _reconnect() {
        return this._state === "closed" ? (log$i.warn("connection closed already"),
        Promise.reject()) : this._state === "connecting" ? (log$i.warn("connection is already in connecting state"),
        Promise.reject()) : this._state !== "disconnected" ? Promise.reject() : (this.prepareReconnect(),
        this._state = "connecting",
        this.emit("stateChanged", {
            state: "reconnecting",
            count: this.reconnectCount
        }),
        this.socket.off("gameRoomAvailable"),
        this.socket.off("socketClosed"),
        this.rtcp.off("rtcDisconnected"),
        this.rtcp.off("rtcConnected"),
        this.connectAndStart(!0).then(({session_id: e})=>{
            this.room.updateCurrentNetworkOptions({
                sessionId: e
            }),
            reporter.updateBody({
                serverSession: e
            }),
            log$i.info("reconnect success"),
            this.setState("connected"),
            this.reconnectCount = 0,
            this.emit("stateChanged", {
                state: "reconnected"
            })
        }
        ))
    }
    prepareReconnect() {
        this.rtcp.disconnect(),
        this.socket.prepareReconnect(),
        this.prepareReconnectOptions()
    }
    prepareReconnectOptions() {
        const {camera: e, player: t} = this.room.currentClickingState || {};
        e && t && this.room.updateCurrentNetworkOptions({
            camera: e,
            player: t
        })
    }
    sendRtcData(e) {
        if (this.blockedActions.includes(e.action_type)) {
            log$i.info(`action: ${Actions[e.action_type]} was blocked`);
            return
        }
        this.rtcp.sendData(e)
    }
    sendSocketData(e) {
        log$i.debug("ws send ->", e),
        this.socket.send(e)
    }
    quit() {
        const e = uuid$1()
          , t = {
            action_type: Actions.Exit,
            trace_id: e,
            exit_action: {},
            user_id: this.room.options.userId,
            packet_id: e
        };
        this.setState("closed"),
        this.socket.quit(),
        this.sendRtcData(t)
    }
}
const log$h = new Logger("stats")
  , numberFormat = new Intl.NumberFormat(window.navigator.language,{
    maximumFractionDigits: 0
});
class Stats extends EventEmitter {
    constructor(e) {
        super();
        E(this, "_interval", null);
        E(this, "_netInterval", null);
        E(this, "_disabled", !1);
        E(this, "_show", !1);
        E(this, "_aggregatedStats", {});
        E(this, "_displayElement", null);
        E(this, "_extraStats", {});
        E(this, "_networkSamples", []);
        E(this, "externalStats");
        E(this, "constructedTime");
        this.room = e,
        this.constructedTime = Date.now(),
        this._interval = window.setInterval(()=>{
            var t, r, n;
            this._disabled || this.onStats((n = (r = (t = e.networkController) == null ? void 0 : t.rtcp) == null ? void 0 : r.workers) == null ? void 0 : n.uploadDataToServer())
        }
        , 1e3),
        this._netInterval = window.setInterval(()=>{
            this.getIsWeakNet()
        }
        , NET_INTERVAL * 1e3)
    }
    get isShow() {
        return this._show
    }
    assign(e) {
        Object.assign(this._extraStats, e),
        ((e == null ? void 0 : e.hb) || (e == null ? void 0 : e.rtt)) && this.startStatsNetSamples()
    }
    appendExternalStats(e) {
        const t = {};
        if (!e || typeof e != "object") {
            console.warn("appendExternalStats should be plain object");
            return
        }
        Object.keys(e).forEach(r=>{
            Object.prototype.hasOwnProperty.call(this._aggregatedStats, r) ? console.warn(`${r} is duplicate with internal stats`) : t[r] = e[r]
        }
        ),
        !(Object.keys(t).length > 10) && (this.externalStats = t)
    }
    getRtt() {
        const e = this._extraStats.rtt;
        return typeof e != "number" ? 0 : e > 999 ? 999 : e
    }
    enable() {
        this._disabled = !1
    }
    disable() {
        this._disabled = !0
    }
    disableNet() {
        this._netInterval && window.clearInterval(this._netInterval)
    }
    show() {
        this._show = !0,
        this._render()
    }
    hide() {
        this._show = !1,
        this._displayElement && document.body.removeChild(this._displayElement),
        this._displayElement = null
    }
    getIsWeakNet() {
        let e = !1;
        const t = this._networkSamples.length - 1;
        if (t < 0)
            return;
        const r = this._networkSamples[t].time
          , n = this._networkSamples[0].time
          , o = r - n
          , a = 1e3 * (DURATION - 2);
        if (o < a)
            return;
        const s = this._networkSamples.map(g=>this.isNetDelay(g, "rtt"))
          , l = this._networkSamples.map(g=>this.isNetDelay(g, "hb"))
          , u = s.reduce((g,m)=>g + m, 0)
          , c = l.reduce((g,m)=>g + m, 0)
          , h = Math.floor(u / this._networkSamples.length) * 100
          , f = Math.floor(c / this._networkSamples.length) * 100
          , d = 70;
        (h >= d || f >= d) && (e = !0);
        const _ = this.room.viewMode === "observer" || this.room.viewMode === "serverless";
        e && !_ && (log$h.infoAndReportMeasurement({
            metric: "weakNetwork",
            startTime: Date.now(),
            extra: {
                msg: this._networkSamples.slice(20),
                netDelayRTTValues: u,
                netDelayHBValues: c
            }
        }),
        this.emit("weakNetwork"))
    }
    startStatsNetSamples() {
        const {rtt: e, hb: t} = this._extraStats;
        if (e || t) {
            const r = {
                rtt: e,
                hb: t,
                time: new Date().getTime()
            };
            this._networkSamples.push(r);
            const n = this._networkSamples.length - 1;
            if (n < 0)
                return;
            const o = this._networkSamples[n].time
              , a = 1e3 * DURATION;
            this._networkSamples = this._networkSamples.filter(s=>s.time > o - a)
        }
    }
    isNetDelay(e, t) {
        return t === "rtt" ? e.rtt > RTT_MAX_VALUE ? 1 : 0 : t === "hb" && e.hb > HB_MAX_VALUE ? 1 : 0
    }
    getPreciesTimer(e, t) {
        const r = t * 1e3
          , n = new Date().getTime();
        let o = 0;
        o++;
        const a = new Date().getTime() - (n + o * 1e3)
          , s = r - a
          , l = setTimeout(()=>{
            clearTimeout(l),
            e()
        }
        , s)
    }
    _render() {
        var c, h, f, d, _, g, m, v, y, b, T, C, A, S, P, R, M, x, I, w;
        if (!this._aggregatedStats)
            return;
        this._displayElement || (this._displayElement = document.createElement("div"),
        this._displayElement.style.position = "absolute",
        this._displayElement.style.top = "10px",
        this._displayElement.style.left = "200px",
        this._displayElement.style.width = "200px",
        this._displayElement.style.backgroundColor = "rgba(0,0,0,.5)",
        this._displayElement.style.color = "white",
        this._displayElement.style.textAlign = "left",
        this._displayElement.style.fontSize = "8px",
        this._displayElement.style.lineHeight = "10px",
        document.body.appendChild(this._displayElement));
        const e = []
          , t = Date.now() - this.constructedTime
          , r = Math.floor(t / 1e3 % 60)
          , n = Math.floor(t / (1e3 * 60) % 60)
          , o = Math.floor(t / (1e3 * 60 * 60) % 24)
          , a = o < 10 ? "0" + o.toString() : o.toString()
          , s = n < 10 ? "0" + n : n
          , l = r < 10 ? "0" + r : r;
        e.push({
            key: new Date(Math.floor(this._aggregatedStats.timestamp || 0)).toLocaleString("en-GB"),
            value: a + ":" + s + ":" + l
        }),
        e.push({
            key: "rtt: " + this._extraStats.rtt + " hb: " + this._extraStats.hb,
            value: "FPS: " + this._extraStats.fps + " avatar: " + ((c = this.room._userAvatar) == null ? void 0 : c.state)
        }),
        e.push({
            key: "SDK: " + Xverse$1.SUB_PACKAGE_VERSION,
            value: "ENGINE:" + VERSION$1 + " uid:" + this._extraStats.userId
        }),
        e.push({
            key: "\u540C\u6B65/\u6709\u6548/\u663E\u793A\u73A9\u5BB6",
            value: `${this._extraStats.syncUserNum || 0}/${this._extraStats.userNum || 0}/${this._extraStats.renderedUserNum || 0}`
        }),
        e.push({
            key: "media/meta bitrate(kbps)",
            value: numberFormat.format(this._aggregatedStats.mediaBitrate || 0) + "/" + numberFormat.format(this._aggregatedStats.metaBitrate || 0)
        }),
        e.push({
            key: ":----------------Decoding---------------",
            value: ""
        }),
        e.push({
            key: "-max/avg decodeTime(ms)",
            value: numberFormat.format(this._aggregatedStats.decodeTimeMaxFrame || 0) + "/" + numberFormat.format(this._aggregatedStats.decodeTimePerFrame || 0)
        }),
        e.push({
            key: "-frmAwait/Lost/Drop",
            value: numberFormat.format(this._aggregatedStats.framesAwait || 0) + "/" + numberFormat.format(this._aggregatedStats.packetsLost || 0) + "/" + numberFormat.format(this._aggregatedStats.packetsDrop || 0) + "/" + numberFormat.format(this._aggregatedStats.updateDropFrame) || 0
        }),
        e.push({
            key: ":----------------FrameLoop-------------",
            value: ""
        }),
        e.push({
            key: "interval(max/avg/>40)",
            value: (((h = this._extraStats.maxFrameTime) == null ? void 0 : h.toFixed(1)) || 0) + "/" + (((f = this._extraStats.avgFrameTime) == null ? void 0 : f.toFixed(0)) || 0) + "/" + this._extraStats.engineSloppyCnt
        }),
        e.push({
            key: "systemStuck",
            value: this._extraStats.systemStuckCnt
        }),
        e.push({
            key: "--update",
            value: (this._aggregatedStats.maxGraphicTime.toFixed(1) || 0) + "/" + (((d = this._aggregatedStats.averageGraphicTime) == null ? void 0 : d.toFixed(0)) || 0)
        }),
        e.push({
            key: "--timeout",
            value: (((_ = this._extraStats.maxTimeoutTime) == null ? void 0 : _.toFixed(1)) || 0) + "/" + ((g = this._extraStats.avgTimeoutTime) == null ? void 0 : g.toFixed(0)) || 0
        }),
        e.push({
            key: "--render",
            value: (((m = this._extraStats.maxRenderFrameTime) == null ? void 0 : m.toFixed(1)) || 0) + "/" + (((v = this._extraStats.renderFrameTime) == null ? void 0 : v.toFixed(0)) || 0)
        }),
        e.push({
            key: "---anim/regBR/clip(avg ms)",
            value: (this._extraStats.animationTime.toFixed(2) || 0) + " / " + (this._extraStats.registerBeforeRenderTime.toFixed(2) || 0) + " / " + (this._extraStats.meshSelectTime.toFixed(2) || 0)
        }),
        e.push({
            key: "---anim/regBR/clip(max ms)",
            value: (this._extraStats.maxAnimationTime.toFixed(2) || 0) + " / " + (this._extraStats.maxRegisterBeforeRenderTime.toFixed(2) || 0) + " / " + (this._extraStats.maxMeshSelectTime.toFixed(2) || 0)
        }),
        e.push({
            key: "---rTR/drC/regAF(avg ms)",
            value: (this._extraStats.renderTargetRenderTime.toFixed(2) || 0) + " / " + (this._extraStats.drawcallTime.toFixed(2) || 0) + " / " + (this._extraStats.registerAfterRenderTime.toFixed(2) || 0)
        }),
        e.push({
            key: "---rTR/drC/regAF(max ms)",
            value: (this._extraStats.maxRenderTargetRenderTime.toFixed(2) || 0) + " / " + (this._extraStats.maxDrawcallTime.toFixed(2) || 0) + " / " + (this._extraStats.maxRegisterAfterRenderTime.toFixed(2) || 0)
        }),
        e.push({
            key: "--tri/drC/pati/bones/anim(Num)",
            value: (this._extraStats.triangle || 0) + " / " + (this._extraStats.drawcall.toFixed(0) || 0) + " / " + (this._extraStats.activeParticles.toFixed(0) || 0) + " / " + (this._extraStats.activeBones.toFixed(0) || 0) + " / " + (this._extraStats.activeAnimation.toFixed(0) || 0)
        }),
        e.push({
            key: "--rootN/mesh/geo/tex/mat(Num)",
            value: (this._extraStats.totalRootNodes.toFixed(0) || 0) + " / " + (this._extraStats.totalMeshes.toFixed(0) || 0) + " / " + (this._extraStats.totalGeometries.toFixed(0) || 0) + " / " + (this._extraStats.totalTextures.toFixed(0) || 0) + " / " + (this._extraStats.totalMaterials.toFixed(0) || 0)
        }),
        e.push({
            key: "--registerBF/AF(Num)",
            value: (this._extraStats.registerBeforeCount.toFixed(0) || 0) + " / " + (this._extraStats.registerAfterCount.toFixed(0) || 0)
        }),
        e.push({
            key: ":----------------Rotation-------------------",
            value: ""
        }),
        e.push({
            key: "Total(ms/miss)",
            value: (((y = this._aggregatedStats.avgOverallTime) == null ? void 0 : y.toFixed(2)) || 0) + "/" + (this._aggregatedStats.responseMissPs + this._aggregatedStats.processMissPs + this._aggregatedStats.displayMissPs)
        }),
        e.push({
            key: "--rotateRsp",
            value: (((b = this._aggregatedStats.avgResponseTime) == null ? void 0 : b.toFixed(1)) || 0) + "/" + this._aggregatedStats.responseMissPs
        }),
        e.push({
            key: "--rotateProc",
            value: (((T = this._aggregatedStats.avgProcessTime) == null ? void 0 : T.toFixed(1)) || 0) + "/" + this._aggregatedStats.processMissPs
        }),
        e.push({
            key: "--rotateShow",
            value: (((C = this._aggregatedStats.avgDisplayTime) == null ? void 0 : C.toFixed(1)) || 0) + "/" + this._aggregatedStats.displayMissPs
        }),
        ((A = this.room._userAvatar) == null ? void 0 : A.state) == "moving",
        e.push({
            key: ":----------------Move----------------------",
            value: ""
        }),
        e.push({
            key: "-startDelay",
            value: (this._aggregatedStats.moveEvent == "MoveTo" ? this._aggregatedStats.moveResponseDelay || 0 : this._aggregatedStats.flyResponseDelay || 0) + "/" + (this._aggregatedStats.moveEvent == "MoveTo" ? this._aggregatedStats.moveProcessDelay || 0 : this._aggregatedStats.flyProcessDelay || 0) + "/" + (this._aggregatedStats.moveEvent == "MoveTo" ? this._aggregatedStats.moveDisplayDelay || 0 : this._aggregatedStats.flyDisplayDelay || 0)
        }),
        (((S = this.room._userAvatar) == null ? void 0 : S.state) == "moving" || this._aggregatedStats.moveEvent == "GetOnAirship" || this._aggregatedStats.moveEvent == "GetOnVehicle") && e.push({
            key: "-srvInterFrm(max/avg)",
            value: (this._aggregatedStats.maxServerDiff || 0) + "/" + (this._aggregatedStats.avgServerDiff.toFixed(1) || 0)
        }),
        e.push({
            key: "-interFrameDelay",
            value: "(max/avg/jank)"
        }),
        e.push({
            key: "--toDisplay",
            value: (this._aggregatedStats.moveEvent == "MoveTo" ? this._aggregatedStats.maxDisplayMoveDiff || 0 : this._aggregatedStats.maxDisplayFlyDiff || 0) + "/" + (this._aggregatedStats.moveEvent == "MoveTo" ? this._aggregatedStats.avgDisplayMoveDiff.toFixed(1) || 0 : this._aggregatedStats.avgDisplayFlyDiff.toFixed(1) || 0) + "/" + (this._aggregatedStats.moveEvent == "MoveTo" ? ((P = this._aggregatedStats.moveDisplayJank) == null ? void 0 : P.toFixed(3)) || 0 : ((R = this._aggregatedStats.flyDisplayJank) == null ? void 0 : R.toFixed(3)) || 0)
        }),
        e.push({
            key: "--received",
            value: (this._aggregatedStats.moveEvent == "MoveTo" ? this._aggregatedStats.maxResponseMoveDiff || 0 : this._aggregatedStats.maxResponseFlyDiff || 0) + "/" + (this._aggregatedStats.moveEvent == "MoveTo" ? this._aggregatedStats.avgResponseMoveDiff.toFixed(1) || 0 : this._aggregatedStats.avgResponseFlyDiff.toFixed(1) || 0) + "/" + (this._aggregatedStats.moveEvent == "MoveTo" ? ((M = this._aggregatedStats.moveResponseJank) == null ? void 0 : M.toFixed(3)) || 0 : ((x = this._aggregatedStats.flyResponseJank) == null ? void 0 : x.toFixed(3)) || 0)
        }),
        e.push({
            key: "--decoded",
            value: (this._aggregatedStats.moveEvent == "MoveTo" ? this._aggregatedStats.maxProcessMoveDiff || 0 : this._aggregatedStats.maxProcessFlyDiff || 0) + "/" + (this._aggregatedStats.moveEvent == "MoveTo" ? this._aggregatedStats.avgProcessMoveDiff.toFixed(1) || 0 : this._aggregatedStats.avgProcessFlyDiff.toFixed(1) || 0) + "/" + (this._aggregatedStats.moveEvent == "MoveTo" ? ((I = this._aggregatedStats.moveProcessJank) == null ? void 0 : I.toFixed(3)) || 0 : ((w = this._aggregatedStats.flyProcessJank) == null ? void 0 : w.toFixed(3)) || 0)
        }),
        e.push({
            key: ":----------------DevInfo-----------------",
            value: ""
        }),
        e.push({
            key: "sd",
            value: (this._aggregatedStats.sdMoveResponseLongTime.toFixed(1) || 0) + "/" + (this._aggregatedStats.sdMoveProcessLongTime.toFixed(1) || 0) + "/" + (this._aggregatedStats.sdMoveDisplayLongTime.toFixed(1) || 0)
        }),
        e.push({
            key: "----hardwareInfo",
            value: this._extraStats.hardwareInfo
        });
        let u = "";
        for (const O of e)
            u += `<div><span>${O.key}</span>: <span>${O.value}</span> </div>`;
        this._displayElement.innerHTML = u
    }
    onStats(e) {
        var n;
        if (!e)
            return;
        const t = {}
          , r = this;
        r._aggregatedStats || (r._aggregatedStats = {}),
        t.timestamp = e.timestamp,
        t.mediaBytesReceived = e.mediaBytesReceived,
        t.metaBytesReceived = e.metaBytesReceived,
        t.packetsLost = e.packetsLost,
        t.frameHeight = e.frameHeight,
        t.frameWidth = e.frameWidth,
        t.framesReceivedUI = e.framesReceived,
        t.framesReceived = e.framesReceivedWorker,
        t.framesDecoded = e.framesDecoded,
        t.framesEmited = e.framesEmited,
        t.decodeTimePerFrame = e.decodeTimePerFrame,
        t.decodeTimeMaxFrame = e.decodeTimeMaxFrame,
        t.packetsDrop = e.packetsDrop,
        t.framesAwait = e.framesAwait,
        t.updateDropFrame = e.updateDropFrame,
        t.firstMediaArraval = e.firstMediaArraval,
        t.firstYUVDecoded = e.firstYUVDecoded,
        t.firstRender = e.firstRender,
        t.returnFrames = e.returnFrames,
        t.sendOutBuffer = e.sendOutBuffer,
        t.averageGraphicTime = e.averageGraphicTime,
        t.maxGraphicTime = e.maxGraphicTime,
        t.jankTimes = e.jankTimes,
        t.bigJankTimes = e.bigJankTimes,
        t.decodeJankTimes = e.decodeJankTimes,
        t.bigDecodeJankTimes = e.bigDecodeJankTimes,
        t.serverFrameFast = e.serverFrameFast,
        t.serverFrameSlow = e.serverFrameSlow,
        t.clientFrameFast = e.clientFrameFast,
        t.clientFrameSlow = e.clientFrameSlow,
        t.rtcMessageReceived = e.rtcMessageReceived,
        t.rtcBytesReceived = e.rtcBytesReceived,
        t.receiveIframes = e.receiveIframes,
        t.decodeIframes = e.decodeIframes,
        t.avgResponseTime = e.avgResponseTime,
        t.avgProcessTime = e.avgProcessTime,
        t.avgDisplayTime = e.avgDisplayTime,
        t.avgOverallTime = e.avgOverallTime,
        t.overallTimeCount = e.overallTimeCount,
        t.responseMiss = e.responseMiss,
        t.processMiss = e.processMiss,
        t.displayMiss = e.displayMiss,
        t.avgResponseMoveDiff = e.avgResponseMoveDiff,
        t.avgProcessMoveDiff = e.avgProcessMoveDiff,
        t.avgDisplayMoveDiff = e.avgDisplayMoveDiff,
        t.maxResponseMoveDiff = e.maxResponseMoveDiff,
        t.maxProcessMoveDiff = e.maxProcessMoveDiff,
        t.maxDisplayMoveDiff = e.maxDisplayMoveDiff,
        t.moveResponseDelay = e.moveResponseDelay,
        t.moveProcessDelay = e.moveProcessDelay,
        t.moveDisplayDelay = e.moveDisplayDelay,
        t.moveResponseJank = e.moveResponseJank,
        t.moveProcessJank = e.moveProcessJank,
        t.moveDisplayJank = e.moveDisplayJank,
        t.avgMetaParseTime = e.avgMetaParseTime,
        t.maxMetaParseTime = e.maxMetaParseTime,
        t.moveResponseCounts = e.moveResponseCounts,
        t.moveProcessCounts = e.moveProcessCounts,
        t.moveDisplayCounts = e.moveDisplayCounts,
        t.MoveDisplayCountGood = e.MoveDisplayCountGood,
        t.MoveDisplayCountWell = e.MoveDisplayCountWell,
        t.MoveDisplayCountFair = e.MoveDisplayCountFair,
        t.MoveDisplayCountBad = e.MoveDisplayCountBad,
        t.MoveDisplayCountRest = e.MoveDisplayCountRest,
        t.avgServerDiff = e.avgServerDiff,
        t.maxServerDiff = e.maxServerDiff,
        t.avgResponseFlyDiff = e.avgResponseFlyDiff,
        t.avgProcessFlyDiff = e.avgProcessFlyDiff,
        t.avgDisplayFlyDiff = e.avgDisplayFlyDiff,
        t.maxResponseFlyDiff = e.maxResponseFlyDiff,
        t.maxProcessFlyDiff = e.maxProcessFlyDiff,
        t.maxDisplayFlyDiff = e.maxDisplayFlyDiff,
        t.flyResponseCounts = e.flyResponseCounts,
        t.flyProcessCounts = e.flyProcessCounts,
        t.flyDisplayCounts = e.flyDisplayCounts,
        t.flyResponseJank = e.flyResponseJank,
        t.flyProcessJank = e.flyProcessJank,
        t.flyDisplayJank = e.flyDisplayJank,
        t.flyResponseDelay = e.flyResponseDelay,
        t.flyProcessDelay = e.flyProcessDelay,
        t.flyDisplayDelay = e.flyDisplayDelay,
        t.moveEvent = e.moveEvent,
        t.sdMoveResponseLongTime = e.sdMoveResponseLongTime,
        t.sdMoveProcessLongTime = e.sdMoveProcessLongTime,
        t.sdMoveDisplayLongTime = e.sdMoveDisplayLongTime,
        r._aggregatedStats && r._aggregatedStats.timestamp && (t.mediaBitrate = 8 * (t.mediaBytesReceived - r._aggregatedStats.mediaBytesReceived) / 1e3,
        t.mediaBitrate = Math.round(t.mediaBitrate || 0),
        t.metaBitrate = 8 * (t.metaBytesReceived - r._aggregatedStats.metaBytesReceived) / 1e3,
        t.metaBitrate = Math.round(t.metaBitrate || 0),
        t.rtcMessagePs = t.rtcMessageReceived - r._aggregatedStats.rtcMessageReceived,
        t.rtcBitrate = 8 * (t.rtcBytesReceived - r._aggregatedStats.rtcBytesReceived) / 1e3,
        t.rtcBitrate = Math.round(t.rtcBitrate || 0),
        t.framesEmitedPs = t.framesEmited - r._aggregatedStats.framesEmited,
        t.framesEmitedPs = Math.round(t.framesEmitedPs || 0),
        t.framesReceivedPs = t.framesReceived - r._aggregatedStats.framesReceived,
        t.framesReceivedPs = Math.round(t.framesReceivedPs || 0),
        t.framesDecodedPs = t.framesDecoded - r._aggregatedStats.framesDecoded,
        t.framesDecodedPs = Math.round(t.framesDecodedPs || 0),
        t.returnFramesPs = t.returnFrames - r._aggregatedStats.returnFrames,
        t.returnFramesPs = Math.round(t.returnFramesPs || 0),
        t.responseMissPs = t.responseMiss - r._aggregatedStats.responseMiss,
        t.processMissPs = t.processMiss - r._aggregatedStats.processMiss,
        t.displayMissPs = t.displayMiss - r._aggregatedStats.displayMiss,
        t.returnFrames = e.returnFrames),
        this._show && this._render(),
        t.registerBeforeRenderTime = this._extraStats.registerBeforeRenderTime,
        t.registerAfterRenderTime = this._extraStats.registerAfterRenderTime,
        t.renderTargetRenderTime = this._extraStats.renderTargetRenderTime,
        t.renderFrameTime = this._extraStats.renderFrameTime,
        t.maxRenderFrameTime = this._extraStats.maxRenderFrameTime,
        t.interFrameTime = this._extraStats.interFrameTime,
        t.animationTime = this._extraStats.animationTime,
        t.meshSelectTime = this._extraStats.meshSelectTime,
        t.drawcall = this._extraStats.drawcall,
        t.drawcallTime = this._extraStats.drawcallTime,
        t.triangle = this._extraStats.triangle,
        t.registerAfterCount = this._extraStats.registerAfterCount,
        t.registerBeforeCount = this._extraStats.registerBeforeCount,
        t.fps = this._extraStats.fps,
        t.rtt = this._extraStats.rtt,
        t.hb = this._extraStats.hb,
        t.avgFrameTime = this._extraStats.avgFrameTime,
        t.avgTimeoutTime = this._extraStats.avgTimeoutTime,
        t.engineSloppyCnt = this._extraStats.engineSloppyCnt,
        t.systemStuckCnt = this._extraStats.systemStuckCnt,
        t.avatarState = (n = this.room._userAvatar) == null ? void 0 : n.state,
        t.maxFrameTime = this._extraStats.maxFrameTime,
        t.maxTimeoutTime = this._extraStats.maxTimeoutTime,
        t.activeParticles = this._extraStats.activeParticles,
        t.activeBones = this._extraStats.activeBones,
        t.activeAnimation = this._extraStats.activeAnimation,
        t.totalRootNodes = this._extraStats.totalRootNodes,
        t.totalGeometries = this._extraStats.totalGeometries,
        t.totalMeshes = this._extraStats.totalMeshes,
        t.totalTextures = this._extraStats.totalTextures,
        t.totalMaterials = this._extraStats.totalMaterials,
        t.hardwareInfo = this._extraStats.hardwareInfo,
        t.maxInterFrameTime = this._extraStats.maxInterFrameTime,
        t.maxDrawcallTime = this._extraStats.maxDrawcallTime,
        t.maxMeshSelectTime = this._extraStats.maxMeshSelectTime,
        t.maxAnimationTime = this._extraStats.maxAnimationTime,
        t.maxRegisterBeforeRenderTime = this._extraStats.maxRegisterBeforeRenderTime,
        t.maxRegisterAfterRenderTime = this._extraStats.maxRegisterAfterRenderTime,
        t.maxRenderTargetRenderTime = this._extraStats.maxRenderTargetRenderTime,
        this.externalStats && Object.keys(this.externalStats || {}).forEach(o=>{
            t[o] = this.externalStats[o]
        }
        ),
        r._aggregatedStats = t,
        this.emit("stats", {
            stats: t
        })
    }
}
var axios$2 = {
    exports: {}
}
  , bind$2 = function i(e, t) {
    return function() {
        for (var n = new Array(arguments.length), o = 0; o < n.length; o++)
            n[o] = arguments[o];
        return e.apply(t, n)
    }
}
  , bind$1 = bind$2
  , toString = Object.prototype.toString;
function isArray(i) {
    return toString.call(i) === "[object Array]"
}
function isUndefined(i) {
    return typeof i == "undefined"
}
function isBuffer(i) {
    return i !== null && !isUndefined(i) && i.constructor !== null && !isUndefined(i.constructor) && typeof i.constructor.isBuffer == "function" && i.constructor.isBuffer(i)
}
function isArrayBuffer(i) {
    return toString.call(i) === "[object ArrayBuffer]"
}
function isFormData(i) {
    return typeof FormData != "undefined" && i instanceof FormData
}
function isArrayBufferView(i) {
    var e;
    return typeof ArrayBuffer != "undefined" && ArrayBuffer.isView ? e = ArrayBuffer.isView(i) : e = i && i.buffer && i.buffer instanceof ArrayBuffer,
    e
}
function isString(i) {
    return typeof i == "string"
}
function isNumber(i) {
    return typeof i == "number"
}
function isObject(i) {
    return i !== null && typeof i == "object"
}
function isPlainObject(i) {
    if (toString.call(i) !== "[object Object]")
        return !1;
    var e = Object.getPrototypeOf(i);
    return e === null || e === Object.prototype
}
function isDate(i) {
    return toString.call(i) === "[object Date]"
}
function isFile(i) {
    return toString.call(i) === "[object File]"
}
function isBlob(i) {
    return toString.call(i) === "[object Blob]"
}
function isFunction$1(i) {
    return toString.call(i) === "[object Function]"
}
function isStream(i) {
    return isObject(i) && isFunction$1(i.pipe)
}
function isURLSearchParams(i) {
    return typeof URLSearchParams != "undefined" && i instanceof URLSearchParams
}
function trim(i) {
    return i.trim ? i.trim() : i.replace(/^\s+|\s+$/g, "")
}
function isStandardBrowserEnv() {
    return typeof navigator != "undefined" && (navigator.product === "ReactNative" || navigator.product === "NativeScript" || navigator.product === "NS") ? !1 : typeof window != "undefined" && typeof document != "undefined"
}
function forEach(i, e) {
    if (!(i === null || typeof i == "undefined"))
        if (typeof i != "object" && (i = [i]),
        isArray(i))
            for (var t = 0, r = i.length; t < r; t++)
                e.call(null, i[t], t, i);
        else
            for (var n in i)
                Object.prototype.hasOwnProperty.call(i, n) && e.call(null, i[n], n, i)
}
function merge() {
    var i = {};
    function e(n, o) {
        isPlainObject(i[o]) && isPlainObject(n) ? i[o] = merge(i[o], n) : isPlainObject(n) ? i[o] = merge({}, n) : isArray(n) ? i[o] = n.slice() : i[o] = n
    }
    for (var t = 0, r = arguments.length; t < r; t++)
        forEach(arguments[t], e);
    return i
}
function extend(i, e, t) {
    return forEach(e, function(n, o) {
        t && typeof n == "function" ? i[o] = bind$1(n, t) : i[o] = n
    }),
    i
}
function stripBOM(i) {
    return i.charCodeAt(0) === 65279 && (i = i.slice(1)),
    i
}
var utils$d = {
    isArray,
    isArrayBuffer,
    isBuffer,
    isFormData,
    isArrayBufferView,
    isString,
    isNumber,
    isObject,
    isPlainObject,
    isUndefined,
    isDate,
    isFile,
    isBlob,
    isFunction: isFunction$1,
    isStream,
    isURLSearchParams,
    isStandardBrowserEnv,
    forEach,
    merge,
    extend,
    trim,
    stripBOM
}
  , utils$c = utils$d;
function encode(i) {
    return encodeURIComponent(i).replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%20/g, "+").replace(/%5B/gi, "[").replace(/%5D/gi, "]")
}
var buildURL$2 = function i(e, t, r) {
    if (!t)
        return e;
    var n;
    if (r)
        n = r(t);
    else if (utils$c.isURLSearchParams(t))
        n = t.toString();
    else {
        var o = [];
        utils$c.forEach(t, function(l, u) {
            l === null || typeof l == "undefined" || (utils$c.isArray(l) ? u = u + "[]" : l = [l],
            utils$c.forEach(l, function(h) {
                utils$c.isDate(h) ? h = h.toISOString() : utils$c.isObject(h) && (h = JSON.stringify(h)),
                o.push(encode(u) + "=" + encode(h))
            }))
        }),
        n = o.join("&")
    }
    if (n) {
        var a = e.indexOf("#");
        a !== -1 && (e = e.slice(0, a)),
        e += (e.indexOf("?") === -1 ? "?" : "&") + n
    }
    return e
}
  , utils$b = utils$d;
function InterceptorManager$1() {
    this.handlers = []
}
InterceptorManager$1.prototype.use = function i(e, t, r) {
    return this.handlers.push({
        fulfilled: e,
        rejected: t,
        synchronous: r ? r.synchronous : !1,
        runWhen: r ? r.runWhen : null
    }),
    this.handlers.length - 1
}
;
InterceptorManager$1.prototype.eject = function i(e) {
    this.handlers[e] && (this.handlers[e] = null)
}
;
InterceptorManager$1.prototype.forEach = function i(e) {
    utils$b.forEach(this.handlers, function(r) {
        r !== null && e(r)
    })
}
;
var InterceptorManager_1 = InterceptorManager$1
  , utils$a = utils$d
  , normalizeHeaderName$1 = function i(e, t) {
    utils$a.forEach(e, function(n, o) {
        o !== t && o.toUpperCase() === t.toUpperCase() && (e[t] = n,
        delete e[o])
    })
}
  , enhanceError$2 = function i(e, t, r, n, o) {
    return e.config = t,
    r && (e.code = r),
    e.request = n,
    e.response = o,
    e.isAxiosError = !0,
    e.toJSON = function() {
        return {
            message: this.message,
            name: this.name,
            description: this.description,
            number: this.number,
            fileName: this.fileName,
            lineNumber: this.lineNumber,
            columnNumber: this.columnNumber,
            stack: this.stack,
            config: this.config,
            code: this.code,
            status: this.response && this.response.status ? this.response.status : null
        }
    }
    ,
    e
}
  , enhanceError$1 = enhanceError$2
  , createError$2 = function i(e, t, r, n, o) {
    var a = new Error(e);
    return enhanceError$1(a, t, r, n, o)
}
  , createError$1 = createError$2
  , settle$1 = function i(e, t, r) {
    var n = r.config.validateStatus;
    !r.status || !n || n(r.status) ? e(r) : t(createError$1("Request failed with status code " + r.status, r.config, null, r.request, r))
}
  , utils$9 = utils$d
  , cookies$1 = utils$9.isStandardBrowserEnv() ? function i() {
    return {
        write: function(t, r, n, o, a, s) {
            var l = [];
            l.push(t + "=" + encodeURIComponent(r)),
            utils$9.isNumber(n) && l.push("expires=" + new Date(n).toGMTString()),
            utils$9.isString(o) && l.push("path=" + o),
            utils$9.isString(a) && l.push("domain=" + a),
            s === !0 && l.push("secure"),
            document.cookie = l.join("; ")
        },
        read: function(t) {
            var r = document.cookie.match(new RegExp("(^|;\\s*)(" + t + ")=([^;]*)"));
            return r ? decodeURIComponent(r[3]) : null
        },
        remove: function(t) {
            this.write(t, "", Date.now() - 864e5)
        }
    }
}() : function i() {
    return {
        write: function() {},
        read: function() {
            return null
        },
        remove: function() {}
    }
}()
  , isAbsoluteURL$1 = function i(e) {
    return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(e)
}
  , combineURLs$1 = function i(e, t) {
    return t ? e.replace(/\/+$/, "") + "/" + t.replace(/^\/+/, "") : e
}
  , isAbsoluteURL = isAbsoluteURL$1
  , combineURLs = combineURLs$1
  , buildFullPath$1 = function i(e, t) {
    return e && !isAbsoluteURL(t) ? combineURLs(e, t) : t
}
  , utils$8 = utils$d
  , ignoreDuplicateOf = ["age", "authorization", "content-length", "content-type", "etag", "expires", "from", "host", "if-modified-since", "if-unmodified-since", "last-modified", "location", "max-forwards", "proxy-authorization", "referer", "retry-after", "user-agent"]
  , parseHeaders$1 = function i(e) {
    var t = {}, r, n, o;
    return e && utils$8.forEach(e.split(`
`), function(s) {
        if (o = s.indexOf(":"),
        r = utils$8.trim(s.substr(0, o)).toLowerCase(),
        n = utils$8.trim(s.substr(o + 1)),
        r) {
            if (t[r] && ignoreDuplicateOf.indexOf(r) >= 0)
                return;
            r === "set-cookie" ? t[r] = (t[r] ? t[r] : []).concat([n]) : t[r] = t[r] ? t[r] + ", " + n : n
        }
    }),
    t
}
  , utils$7 = utils$d
  , isURLSameOrigin$1 = utils$7.isStandardBrowserEnv() ? function i() {
    var e = /(msie|trident)/i.test(navigator.userAgent), t = document.createElement("a"), r;
    function n(o) {
        var a = o;
        return e && (t.setAttribute("href", a),
        a = t.href),
        t.setAttribute("href", a),
        {
            href: t.href,
            protocol: t.protocol ? t.protocol.replace(/:$/, "") : "",
            host: t.host,
            search: t.search ? t.search.replace(/^\?/, "") : "",
            hash: t.hash ? t.hash.replace(/^#/, "") : "",
            hostname: t.hostname,
            port: t.port,
            pathname: t.pathname.charAt(0) === "/" ? t.pathname : "/" + t.pathname
        }
    }
    return r = n(window.location.href),
    function(a) {
        var s = utils$7.isString(a) ? n(a) : a;
        return s.protocol === r.protocol && s.host === r.host
    }
}() : function i() {
    return function() {
        return !0
    }
}();
function Cancel$3(i) {
    this.message = i
}
Cancel$3.prototype.toString = function i() {
    return "Cancel" + (this.message ? ": " + this.message : "")
}
;
Cancel$3.prototype.__CANCEL__ = !0;
var Cancel_1 = Cancel$3
  , utils$6 = utils$d
  , settle = settle$1
  , cookies = cookies$1
  , buildURL$1 = buildURL$2
  , buildFullPath = buildFullPath$1
  , parseHeaders = parseHeaders$1
  , isURLSameOrigin = isURLSameOrigin$1
  , createError = createError$2
  , defaults$4 = defaults_1
  , Cancel$2 = Cancel_1
  , xhr = function i(e) {
    return new Promise(function(r, n) {
        var o = e.data, a = e.headers, s = e.responseType, l;
        function u() {
            e.cancelToken && e.cancelToken.unsubscribe(l),
            e.signal && e.signal.removeEventListener("abort", l)
        }
        utils$6.isFormData(o) && delete a["Content-Type"];
        var c = new XMLHttpRequest;
        if (e.auth) {
            var h = e.auth.username || ""
              , f = e.auth.password ? unescape(encodeURIComponent(e.auth.password)) : "";
            a.Authorization = "Basic " + btoa(h + ":" + f)
        }
        var d = buildFullPath(e.baseURL, e.url);
        c.open(e.method.toUpperCase(), buildURL$1(d, e.params, e.paramsSerializer), !0),
        c.timeout = e.timeout;
        function _() {
            if (!!c) {
                var m = "getAllResponseHeaders"in c ? parseHeaders(c.getAllResponseHeaders()) : null
                  , v = !s || s === "text" || s === "json" ? c.responseText : c.response
                  , y = {
                    data: v,
                    status: c.status,
                    statusText: c.statusText,
                    headers: m,
                    config: e,
                    request: c
                };
                settle(function(T) {
                    r(T),
                    u()
                }, function(T) {
                    n(T),
                    u()
                }, y),
                c = null
            }
        }
        if ("onloadend"in c ? c.onloadend = _ : c.onreadystatechange = function() {
            !c || c.readyState !== 4 || c.status === 0 && !(c.responseURL && c.responseURL.indexOf("file:") === 0) || setTimeout(_)
        }
        ,
        c.onabort = function() {
            !c || (n(createError("Request aborted", e, "ECONNABORTED", c)),
            c = null)
        }
        ,
        c.onerror = function() {
            n(createError("Network Error", e, null, c)),
            c = null
        }
        ,
        c.ontimeout = function() {
            var v = e.timeout ? "timeout of " + e.timeout + "ms exceeded" : "timeout exceeded"
              , y = e.transitional || defaults$4.transitional;
            e.timeoutErrorMessage && (v = e.timeoutErrorMessage),
            n(createError(v, e, y.clarifyTimeoutError ? "ETIMEDOUT" : "ECONNABORTED", c)),
            c = null
        }
        ,
        utils$6.isStandardBrowserEnv()) {
            var g = (e.withCredentials || isURLSameOrigin(d)) && e.xsrfCookieName ? cookies.read(e.xsrfCookieName) : void 0;
            g && (a[e.xsrfHeaderName] = g)
        }
        "setRequestHeader"in c && utils$6.forEach(a, function(v, y) {
            typeof o == "undefined" && y.toLowerCase() === "content-type" ? delete a[y] : c.setRequestHeader(y, v)
        }),
        utils$6.isUndefined(e.withCredentials) || (c.withCredentials = !!e.withCredentials),
        s && s !== "json" && (c.responseType = e.responseType),
        typeof e.onDownloadProgress == "function" && c.addEventListener("progress", e.onDownloadProgress),
        typeof e.onUploadProgress == "function" && c.upload && c.upload.addEventListener("progress", e.onUploadProgress),
        (e.cancelToken || e.signal) && (l = function(m) {
            !c || (n(!m || m && m.type ? new Cancel$2("canceled") : m),
            c.abort(),
            c = null)
        }
        ,
        e.cancelToken && e.cancelToken.subscribe(l),
        e.signal && (e.signal.aborted ? l() : e.signal.addEventListener("abort", l))),
        o || (o = null),
        c.send(o)
    }
    )
}
  , utils$5 = utils$d
  , normalizeHeaderName = normalizeHeaderName$1
  , enhanceError = enhanceError$2
  , DEFAULT_CONTENT_TYPE = {
    "Content-Type": "application/x-www-form-urlencoded"
};
function setContentTypeIfUnset(i, e) {
    !utils$5.isUndefined(i) && utils$5.isUndefined(i["Content-Type"]) && (i["Content-Type"] = e)
}
function getDefaultAdapter() {
    var i;
    return (typeof XMLHttpRequest != "undefined" || typeof process != "undefined" && Object.prototype.toString.call(process) === "[object process]") && (i = xhr),
    i
}
function stringifySafely(i, e, t) {
    if (utils$5.isString(i))
        try {
            return (e || JSON.parse)(i),
            utils$5.trim(i)
        } catch (r) {
            if (r.name !== "SyntaxError")
                throw r
        }
    return (t || JSON.stringify)(i)
}
var defaults$3 = {
    transitional: {
        silentJSONParsing: !0,
        forcedJSONParsing: !0,
        clarifyTimeoutError: !1
    },
    adapter: getDefaultAdapter(),
    transformRequest: [function i(e, t) {
        return normalizeHeaderName(t, "Accept"),
        normalizeHeaderName(t, "Content-Type"),
        utils$5.isFormData(e) || utils$5.isArrayBuffer(e) || utils$5.isBuffer(e) || utils$5.isStream(e) || utils$5.isFile(e) || utils$5.isBlob(e) ? e : utils$5.isArrayBufferView(e) ? e.buffer : utils$5.isURLSearchParams(e) ? (setContentTypeIfUnset(t, "application/x-www-form-urlencoded;charset=utf-8"),
        e.toString()) : utils$5.isObject(e) || t && t["Content-Type"] === "application/json" ? (setContentTypeIfUnset(t, "application/json"),
        stringifySafely(e)) : e
    }
    ],
    transformResponse: [function i(e) {
        var t = this.transitional || defaults$3.transitional
          , r = t && t.silentJSONParsing
          , n = t && t.forcedJSONParsing
          , o = !r && this.responseType === "json";
        if (o || n && utils$5.isString(e) && e.length)
            try {
                return JSON.parse(e)
            } catch (a) {
                if (o)
                    throw a.name === "SyntaxError" ? enhanceError(a, this, "E_JSON_PARSE") : a
            }
        return e
    }
    ],
    timeout: 0,
    xsrfCookieName: "XSRF-TOKEN",
    xsrfHeaderName: "X-XSRF-TOKEN",
    maxContentLength: -1,
    maxBodyLength: -1,
    validateStatus: function i(e) {
        return e >= 200 && e < 300
    },
    headers: {
        common: {
            Accept: "application/json, text/plain, */*"
        }
    }
};
utils$5.forEach(["delete", "get", "head"], function i(e) {
    defaults$3.headers[e] = {}
});
utils$5.forEach(["post", "put", "patch"], function i(e) {
    defaults$3.headers[e] = utils$5.merge(DEFAULT_CONTENT_TYPE)
});
var defaults_1 = defaults$3
  , utils$4 = utils$d
  , defaults$2 = defaults_1
  , transformData$1 = function i(e, t, r) {
    var n = this || defaults$2;
    return utils$4.forEach(r, function(a) {
        e = a.call(n, e, t)
    }),
    e
}
  , isCancel$1 = function i(e) {
    return !!(e && e.__CANCEL__)
}
  , utils$3 = utils$d
  , transformData = transformData$1
  , isCancel = isCancel$1
  , defaults$1 = defaults_1
  , Cancel$1 = Cancel_1;
function throwIfCancellationRequested(i) {
    if (i.cancelToken && i.cancelToken.throwIfRequested(),
    i.signal && i.signal.aborted)
        throw new Cancel$1("canceled")
}
var dispatchRequest$1 = function i(e) {
    throwIfCancellationRequested(e),
    e.headers = e.headers || {},
    e.data = transformData.call(e, e.data, e.headers, e.transformRequest),
    e.headers = utils$3.merge(e.headers.common || {}, e.headers[e.method] || {}, e.headers),
    utils$3.forEach(["delete", "get", "head", "post", "put", "patch", "common"], function(n) {
        delete e.headers[n]
    });
    var t = e.adapter || defaults$1.adapter;
    return t(e).then(function(n) {
        return throwIfCancellationRequested(e),
        n.data = transformData.call(e, n.data, n.headers, e.transformResponse),
        n
    }, function(n) {
        return isCancel(n) || (throwIfCancellationRequested(e),
        n && n.response && (n.response.data = transformData.call(e, n.response.data, n.response.headers, e.transformResponse))),
        Promise.reject(n)
    })
}
  , utils$2 = utils$d
  , mergeConfig$2 = function i(e, t) {
    t = t || {};
    var r = {};
    function n(c, h) {
        return utils$2.isPlainObject(c) && utils$2.isPlainObject(h) ? utils$2.merge(c, h) : utils$2.isPlainObject(h) ? utils$2.merge({}, h) : utils$2.isArray(h) ? h.slice() : h
    }
    function o(c) {
        if (utils$2.isUndefined(t[c])) {
            if (!utils$2.isUndefined(e[c]))
                return n(void 0, e[c])
        } else
            return n(e[c], t[c])
    }
    function a(c) {
        if (!utils$2.isUndefined(t[c]))
            return n(void 0, t[c])
    }
    function s(c) {
        if (utils$2.isUndefined(t[c])) {
            if (!utils$2.isUndefined(e[c]))
                return n(void 0, e[c])
        } else
            return n(void 0, t[c])
    }
    function l(c) {
        if (c in t)
            return n(e[c], t[c]);
        if (c in e)
            return n(void 0, e[c])
    }
    var u = {
        url: a,
        method: a,
        data: a,
        baseURL: s,
        transformRequest: s,
        transformResponse: s,
        paramsSerializer: s,
        timeout: s,
        timeoutMessage: s,
        withCredentials: s,
        adapter: s,
        responseType: s,
        xsrfCookieName: s,
        xsrfHeaderName: s,
        onUploadProgress: s,
        onDownloadProgress: s,
        decompress: s,
        maxContentLength: s,
        maxBodyLength: s,
        transport: s,
        httpAgent: s,
        httpsAgent: s,
        cancelToken: s,
        socketPath: s,
        responseEncoding: s,
        validateStatus: l
    };
    return utils$2.forEach(Object.keys(e).concat(Object.keys(t)), function(h) {
        var f = u[h] || o
          , d = f(h);
        utils$2.isUndefined(d) && f !== l || (r[h] = d)
    }),
    r
}
  , data = {
    version: "0.24.0"
}
  , VERSION = data.version
  , validators$1 = {};
["object", "boolean", "number", "function", "string", "symbol"].forEach(function(i, e) {
    validators$1[i] = function(r) {
        return typeof r === i || "a" + (e < 1 ? "n " : " ") + i
    }
});
var deprecatedWarnings = {};
validators$1.transitional = function i(e, t, r) {
    function n(o, a) {
        return "[Axios v" + VERSION + "] Transitional option '" + o + "'" + a + (r ? ". " + r : "")
    }
    return function(o, a, s) {
        if (e === !1)
            throw new Error(n(a, " has been removed" + (t ? " in " + t : "")));
        return t && !deprecatedWarnings[a] && (deprecatedWarnings[a] = !0,
        console.warn(n(a, " has been deprecated since v" + t + " and will be removed in the near future"))),
        e ? e(o, a, s) : !0
    }
}
;
function assertOptions(i, e, t) {
    if (typeof i != "object")
        throw new TypeError("options must be an object");
    for (var r = Object.keys(i), n = r.length; n-- > 0; ) {
        var o = r[n]
          , a = e[o];
        if (a) {
            var s = i[o]
              , l = s === void 0 || a(s, o, i);
            if (l !== !0)
                throw new TypeError("option " + o + " must be " + l);
            continue
        }
        if (t !== !0)
            throw Error("Unknown option " + o)
    }
}
var validator$1 = {
    assertOptions,
    validators: validators$1
}
  , utils$1 = utils$d
  , buildURL = buildURL$2
  , InterceptorManager = InterceptorManager_1
  , dispatchRequest = dispatchRequest$1
  , mergeConfig$1 = mergeConfig$2
  , validator = validator$1
  , validators = validator.validators;
function Axios$1(i) {
    this.defaults = i,
    this.interceptors = {
        request: new InterceptorManager,
        response: new InterceptorManager
    }
}
Axios$1.prototype.request = function i(e) {
    typeof e == "string" ? (e = arguments[1] || {},
    e.url = arguments[0]) : e = e || {},
    e = mergeConfig$1(this.defaults, e),
    e.method ? e.method = e.method.toLowerCase() : this.defaults.method ? e.method = this.defaults.method.toLowerCase() : e.method = "get";
    var t = e.transitional;
    t !== void 0 && validator.assertOptions(t, {
        silentJSONParsing: validators.transitional(validators.boolean),
        forcedJSONParsing: validators.transitional(validators.boolean),
        clarifyTimeoutError: validators.transitional(validators.boolean)
    }, !1);
    var r = []
      , n = !0;
    this.interceptors.request.forEach(function(f) {
        typeof f.runWhen == "function" && f.runWhen(e) === !1 || (n = n && f.synchronous,
        r.unshift(f.fulfilled, f.rejected))
    });
    var o = [];
    this.interceptors.response.forEach(function(f) {
        o.push(f.fulfilled, f.rejected)
    });
    var a;
    if (!n) {
        var s = [dispatchRequest, void 0];
        for (Array.prototype.unshift.apply(s, r),
        s = s.concat(o),
        a = Promise.resolve(e); s.length; )
            a = a.then(s.shift(), s.shift());
        return a
    }
    for (var l = e; r.length; ) {
        var u = r.shift()
          , c = r.shift();
        try {
            l = u(l)
        } catch (h) {
            c(h);
            break
        }
    }
    try {
        a = dispatchRequest(l)
    } catch (h) {
        return Promise.reject(h)
    }
    for (; o.length; )
        a = a.then(o.shift(), o.shift());
    return a
}
;
Axios$1.prototype.getUri = function i(e) {
    return e = mergeConfig$1(this.defaults, e),
    buildURL(e.url, e.params, e.paramsSerializer).replace(/^\?/, "")
}
;
utils$1.forEach(["delete", "get", "head", "options"], function i(e) {
    Axios$1.prototype[e] = function(t, r) {
        return this.request(mergeConfig$1(r || {}, {
            method: e,
            url: t,
            data: (r || {}).data
        }))
    }
});
utils$1.forEach(["post", "put", "patch"], function i(e) {
    Axios$1.prototype[e] = function(t, r, n) {
        return this.request(mergeConfig$1(n || {}, {
            method: e,
            url: t,
            data: r
        }))
    }
});
var Axios_1 = Axios$1
  , Cancel = Cancel_1;
function CancelToken(i) {
    if (typeof i != "function")
        throw new TypeError("executor must be a function.");
    var e;
    this.promise = new Promise(function(n) {
        e = n
    }
    );
    var t = this;
    this.promise.then(function(r) {
        if (!!t._listeners) {
            var n, o = t._listeners.length;
            for (n = 0; n < o; n++)
                t._listeners[n](r);
            t._listeners = null
        }
    }),
    this.promise.then = function(r) {
        var n, o = new Promise(function(a) {
            t.subscribe(a),
            n = a
        }
        ).then(r);
        return o.cancel = function() {
            t.unsubscribe(n)
        }
        ,
        o
    }
    ,
    i(function(n) {
        t.reason || (t.reason = new Cancel(n),
        e(t.reason))
    })
}
CancelToken.prototype.throwIfRequested = function i() {
    if (this.reason)
        throw this.reason
}
;
CancelToken.prototype.subscribe = function i(e) {
    if (this.reason) {
        e(this.reason);
        return
    }
    this._listeners ? this._listeners.push(e) : this._listeners = [e]
}
;
CancelToken.prototype.unsubscribe = function i(e) {
    if (!!this._listeners) {
        var t = this._listeners.indexOf(e);
        t !== -1 && this._listeners.splice(t, 1)
    }
}
;
CancelToken.source = function i() {
    var e, t = new CancelToken(function(n) {
        e = n
    }
    );
    return {
        token: t,
        cancel: e
    }
}
;
var CancelToken_1 = CancelToken
  , spread = function i(e) {
    return function(r) {
        return e.apply(null, r)
    }
}
  , isAxiosError = function i(e) {
    return typeof e == "object" && e.isAxiosError === !0
}
  , utils = utils$d
  , bind = bind$2
  , Axios = Axios_1
  , mergeConfig = mergeConfig$2
  , defaults = defaults_1;
function createInstance(i) {
    var e = new Axios(i)
      , t = bind(Axios.prototype.request, e);
    return utils.extend(t, Axios.prototype, e),
    utils.extend(t, e),
    t.create = function(n) {
        return createInstance(mergeConfig(i, n))
    }
    ,
    t
}
var axios$1 = createInstance(defaults);
axios$1.Axios = Axios;
axios$1.Cancel = Cancel_1;
axios$1.CancelToken = CancelToken_1;
axios$1.isCancel = isCancel$1;
axios$1.VERSION = data.version;
axios$1.all = function i(e) {
    return Promise.all(e)
}
;
axios$1.spread = spread;
axios$1.isAxiosError = isAxiosError;
axios$2.exports = axios$1;
axios$2.exports.default = axios$1;
var axios = axios$2.exports;
const isFunction = i=>typeof i == "function";
class AxiosCanceler {
    constructor() {
        E(this, "pendingMap", new Map)
    }
    addPending(e) {
        return new axios.CancelToken(t=>{
            this.pendingMap.has(e) || this.pendingMap.set(e, t)
        }
        )
    }
    removeAllPending() {
        this.pendingMap.forEach(e=>{
            e && isFunction(e) && e()
        }
        ),
        this.pendingMap.clear()
    }
    removePending(e) {
        if (this.pendingMap.has(e)) {
            const t = this.pendingMap.get(e);
            t && t(e),
            this.pendingMap.delete(e)
        }
    }
    removeCancelToken(e) {
        this.pendingMap.has(e) && this.pendingMap.delete(e)
    }
    reset() {
        this.pendingMap = new Map
    }
}
const log$g = new Logger("http");
class Http$1 {
    constructor() {
        E(this, "instatnce");
        E(this, "canceler");
        E(this, "requestParams", e=>oe({}, e.params));
        E(this, "requestConstant", ()=>({
            x_nounce: this.randomString(),
            x_timestamp: new Date().getTime(),
            x_os: "web"
        }));
        this.instatnce = axios.create(),
        this.canceler = new AxiosCanceler
    }
    get(e) {
        return this.request(le(oe({}, e), {
            method: "GET"
        }))
    }
    post(e) {
        return this.request(le(oe({}, e), {
            method: "POST"
        }))
    }
    request(e) {
        const {url: t, timeout: r=1e4, method: n, key: o, beforeRequest: a, responseType: s, data: l} = e;
        let {retry: u=0} = e;
        const c = this.patchUrl(t)
          , h = this.canceler.addPending(t);
        a && isFunction(a) && a(e);
        const f = this.requestParams(e);
        let d = {
            url: c,
            method: n,
            timeout: r,
            cancelToken: h,
            responseType: s,
            params: f
        };
        n === "POST" && (d = oe({
            data: l
        }, d));
        const _ = Date.now()
          , g = ()=>this.instatnce.request(d).then(m=>(o && log$g.infoAndReportMeasurement({
            metric: "http",
            startTime: _,
            extra: t,
            group: "http",
            tag: o
        }),
        this.canceler.removeCancelToken(t),
        m)).catch(m=>{
            const v = axios.isCancel(m);
            return u > 0 && !v ? (u--,
            log$g.warn(`request ${t} retry, left retry count`, u),
            g()) : (log$g.infoAndReportMeasurement({
                metric: "http",
                startTime: _,
                error: m,
                extra: {
                    url: t,
                    isCanceled: v
                },
                tag: o,
                group: "http"
            }),
            this.canceler.removeCancelToken(t),
            Promise.reject(m))
        }
        );
        return g()
    }
    patchUrl(e) {
        return e
    }
    randomString() {
        let e = "";
        const t = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
          , r = t.length;
        for (let n = 0; n < 8; n++)
            e += t.charAt(Math.floor(Math.random() * r));
        return e
    }
}
const http$1 = new Http$1
  , blobToDataURI$1 = async i=>new Promise((e,t)=>{
    const r = new FileReader;
    r.readAsDataURL(i),
    r.onload = function(n) {
        var o;
        e((o = n.target) == null ? void 0 : o.result)
    }
    ,
    r.onerror = function(n) {
        t(n)
    }
}
)
  , objectParseFloat = i=>{
    const e = {};
    return i && Object.keys(i).forEach(t=>{
        e[t] = parseFloat(i[t])
    }
    ),
    e
}
  , log$f = new Logger("model-manager")
  , me = class {
    constructor(e, t) {
        E(this, "avatarModelList", []);
        E(this, "skinList", []);
        E(this, "applicationConfig");
        E(this, "config");
        E(this, "appId");
        E(this, "releaseId");
        this.appId = e,
        this.releaseId = t
    }
    static getInstance(e, t) {
        return me.instance || (me.instance = new me(e,t)),
        me.instance
    }
    static findModels(e, t, r) {
        return e.filter(o=>o.typeName === t && o.className === r)
    }
    static findModel(e, t, r) {
        const n = e.filter(o=>o.typeName === t && o.className === r)[0];
        return n || null
    }
    async findSkinConfig(e) {
        let t = null;
        if (t = (this.skinList = await this.getSkinsList()).find(n=>n.id === e),
        t)
            return t;
        {
            const n = `skin is invalid: skinId: ${e}`;
            return Promise.reject(new ParamError(n))
        }
    }
    async findRoute(e, t) {
        const n = (await this.findSkinConfig(e)).routeList.find(o=>o.pathName === t);
        if (!n) {
            const o = `find path failed: skinId: ${e}, pathName: ${t}`;
            return Promise.reject(new ParamError(o))
        }
        return log$f.debug("find route success", n),
        n
    }
    async findAssetList(e) {
        const r = (await this.findSkinConfig(e)).assetList;
        if (!r) {
            const n = `find path failed: skinId: ${e}`;
            return Promise.reject(new ParamError(n))
        }
        return log$f.debug("find route success", r),
        r
    }
    async findAsset(e, t, r="id") {
        const n = await this.findSkinConfig(e);
        if (Array.isArray(t))
            return t.map(a=>n.models.find(s=>s[r] === a)).filter(Boolean);
        const o = n.models.find(a=>a[r] === t);
        if (!o) {
            const a = `find asset failed: skinId: ${e}, keyValue: ${t}`;
            return Promise.reject(new ParamError(a))
        }
        return log$f.debug("find asset success", o),
        o
    }
    async findPoint(e, t) {
        const n = (await this.findSkinConfig(e)).pointList.find(o=>o.id === t);
        if (!n) {
            const o = `find point failed: skinId: ${e}, id: ${t}`;
            return Promise.reject(new ParamError(o))
        }
        return log$f.debug("find point success", n),
        n
    }
    async requestConfig() {
        if (this.config)
            return this.config;
        let e = `https://static.xverse.cn/console/config/${this.appId}/config.json`;
        this.releaseId && (e = `https://static.xverse.cn/console/config/${this.appId}/${this.releaseId}/config.json`);
        const t = Xverse$1.USE_TME_CDN ? "https://static.xverse.cn/tmeland/config/tme_config.json" : e;
        try {
            const r = await http$1.get({
                url: `${t}?t=${Date.now()}`,
                key: "config",
                timeout: 6e3,
                retry: 2
            })
              , {config: n, preload: o} = r.data.data || {};
            if (!n)
                throw new Error("config data parse error" + r.data);
            return this.config = {
                config: n,
                preload: o
            },
            log$f.debug("get config success", this.config),
            this.config
        } catch (r) {
            return Promise.reject(r)
        }
    }
    async getApplicationConfig() {
        if (this.applicationConfig)
            return this.applicationConfig;
        try {
            const e = await this.requestConfig();
            return this.applicationConfig = e.config,
            this.applicationConfig
        } catch (e) {
            return Promise.reject(e)
        }
    }
    async getAvatarModelList() {
        if (this.avatarModelList.length)
            return this.avatarModelList;
        try {
            const {avatars: e} = await this.getApplicationConfig();
            return this.avatarModelList = e.map(t=>({
                name: t.name,
                id: t.id,
                modelUrl: t.url,
                gender: t.gender,
                components: t.components
            })),
            this.avatarModelList
        } catch (e) {
            return log$f.error(e),
            []
        }
    }
    async getSkinsList() {
        if (this.skinList.length)
            return this.skinList;
        try {
            const {skins: e} = await this.getApplicationConfig();
            return this.skinList = e.map(t=>{
                var r;
                return {
                    name: t.name,
                    dataVersion: t.id + t.versionId,
                    id: t.id,
                    fov: parseInt(t.fov || 90),
                    models: t.assetList.map(n=>{
                        const {assetId: o, url: a, thumbnailUrl: s, typeName: l, className: u} = n;
                        return {
                            id: o,
                            modelUrl: a,
                            name: n.name,
                            thumbnailUrl: s,
                            typeName: l,
                            className: u === "\u4F4E\u6A21" ? "\u7C97\u6A21" : u
                        }
                    }
                    ),
                    routeList: (r = t.routeList) == null ? void 0 : r.map(n=>{
                        const {areaName: o, attitude: a, id: s, pathName: l, step: u, birthPointList: c} = n;
                        return {
                            areaName: o,
                            attitude: a,
                            id: s,
                            pathName: l,
                            step: u,
                            birthPointList: c.map(h=>({
                                camera: h.camera && {
                                    position: objectParseFloat(h.camera.position),
                                    angle: objectParseFloat(h.camera.rotation)
                                },
                                player: h.player && {
                                    position: objectParseFloat(h.player.position),
                                    angle: objectParseFloat(h.player.rotation)
                                }
                            }))
                        }
                    }
                    ),
                    pointList: t.pointList.map(n=>le(oe({}, n), {
                        position: objectParseFloat(n.position),
                        rotation: objectParseFloat(n.rotation)
                    })),
                    versionId: t.versionId,
                    isEnable: t.isEnable,
                    assetList: t.assetList,
                    visibleRules: t.visibleRules,
                    animationList: t.animationList
                }
            }
            ),
            this.skinList
        } catch (e) {
            return log$f.error(e),
            []
        }
    }
    async getBreathPointTextrueList() {
        return [{
            url: TEXTURE_URL
        }]
    }
}
;
let ModelManager = me;
E(ModelManager, "instance");
var AssetTypeName = (i=>(i.Config = "CONFIG",
i.Model = "MODEL",
i.Vedio = "VEDIO",
i.Media = "MEDIA",
i.Effects = "EFFECTS",
i.Gift = "GIFT",
i.Textures = "TEXTURES",
i))(AssetTypeName || {})
  , AssetClassName = (i=>(i.Effects = "\u7279\u6548",
i.Tv = "TV",
i.Lpm = "\u7C97\u6A21",
i.Reward = "\u571F\u8C6A\u699C",
i.Env = "\u73AF\u5883\u5149",
i.Gbq = "\u544A\u767D\u5899",
i.BreathPoint = "\u547C\u5438\u70B9",
i.Gifts = "\u9001\u793C",
i.Panorama = "\u5168\u666F\u56FE",
i.GiftBubble = "\u9001\u793C\u6C14\u6CE1",
i.SayBubble = "\u804A\u5929\u6C14\u6CE1",
i))(AssetClassName || {});
const log$e = new Logger("db");
class BaseTable {
    constructor(e, t) {
        E(this, "db");
        E(this, "isCreatingTable", !1);
        E(this, "hasCleared", !1);
        this.dbName = e,
        this.dbVersion = t
    }
    async clearDataBase(e) {
        return this.hasCleared || (e && (this.hasCleared = !0),
        !window.indexedDB.databases) ? Promise.resolve() : new Promise((t,r)=>{
            const n = window.indexedDB.deleteDatabase(this.dbName);
            n.onsuccess = ()=>{
                t()
            }
            ,
            n.onerror = r
        }
        )
    }
    tableName() {
        throw new Error("Derived class have to override 'tableName', and set a proper table name!")
    }
    keyPath() {
        throw new Error("Derived class have to override 'keyPath', and set a proper index name!")
    }
    index() {
        throw new Error("Derived class have to override 'index', and set a proper index name!")
    }
    async checkAndOpenDatabase() {
        return this.db ? Promise.resolve(this.db) : new Promise((e,t)=>{
            const n = setTimeout(()=>{
                log$e.info("wait db to open for", 200),
                this.db ? e(this.db) : e(this.checkAndOpenDatabase()),
                clearTimeout(n)
            }
            , 200);
            this.openDatabase(this.dbName, this.dbVersion || 1, ()=>{
                this.db && !this.isCreatingTable && e(this.db),
                log$e.info(`successCallback called, this.db: ${!!this.db}, this.isCreatingStore: ${this.isCreatingTable}`),
                clearTimeout(n)
            }
            , ()=>{
                t(new Error("Failed to open database!")),
                clearTimeout(n)
            }
            , ()=>{
                this.db && e(this.db),
                clearTimeout(n),
                log$e.info(`successCallback called, this.db: ${!!this.db}, this.isCreatingStore: ${this.isCreatingTable}`)
            }
            )
        }
        )
    }
    openDatabase(e, t, r, n, o) {
        if (this.isCreatingTable)
            return;
        this.isCreatingTable = !0,
        log$e.info(e, t);
        const a = window.indexedDB.open(e, t)
          , s = this.tableName();
        a.onsuccess = l=>{
            this.db = a.result,
            log$e.info(`IndexedDb ${e} is opened.`),
            this.db.objectStoreNames.contains(s) && (this.isCreatingTable = !1),
            r && r(l)
        }
        ,
        a.onerror = l=>{
            var u;
            log$e.error("Failed to open database", (u = l == null ? void 0 : l.srcElement) == null ? void 0 : u.error),
            this.isCreatingTable = !1,
            n && n(l),
            this.clearDataBase(!0)
        }
        ,
        a.onupgradeneeded = l=>{
            const u = l.target.result
              , c = this.index();
            log$e.info(`Creating table ${s}.`);
            let h = u.objectStoreNames.contains(s);
            if (h)
                h = u.transaction([s], "readwrite").objectStore(s);
            else {
                const f = this.keyPath();
                h = u.createObjectStore(s, {
                    keyPath: f
                })
            }
            c.map(f=>{
                h.createIndex(f, f, {
                    unique: !1
                })
            }
            ),
            this.isCreatingTable = !1,
            log$e.info(`Table ${s} opened`),
            o && o(l)
        }
    }
    async add(e) {
        const t = this.tableName()
          , o = (await this.checkAndOpenDatabase()).transaction([t], "readwrite").objectStore(t).add(e);
        return new Promise(function(a, s) {
            o.onsuccess = l=>{
                a(l)
            }
            ,
            o.onerror = l=>{
                var u;
                log$e.error((u = l.srcElement) == null ? void 0 : u.error),
                s(l)
            }
        }
        )
    }
    async put(e) {
        const t = this.tableName()
          , o = (await this.checkAndOpenDatabase()).transaction([t], "readwrite").objectStore(t).put(e);
        return new Promise(function(a, s) {
            o.onsuccess = l=>{
                a(l)
            }
            ,
            o.onerror = l=>{
                var u;
                log$e.error("db put error", (u = l.srcElement) == null ? void 0 : u.error),
                s(l)
            }
        }
        )
    }
    delete(e, t, r) {
        const n = this.tableName();
        this.checkAndOpenDatabase().then(o=>{
            const s = o.transaction([n], "readwrite").objectStore(n).delete(e);
            s.onsuccess = t,
            s.onerror = r
        }
        )
    }
    update() {
        this.checkAndOpenDatabase().then(e=>{}
        )
    }
    async getAllKeys() {
        const e = this.tableName()
          , t = await this.checkAndOpenDatabase();
        return new Promise((r,n)=>{
            const a = t.transaction([e], "readonly").objectStore(e).getAllKeys();
            a.onsuccess = s=>{
                r(s.target.result)
            }
            ,
            a.onerror = s=>{
                log$e.error("db getAllKeys error", s),
                n(s)
            }
        }
        )
    }
    async query(e, t) {
        const r = this.tableName()
          , n = await this.checkAndOpenDatabase();
        return new Promise((o,a)=>{
            const u = n.transaction([r], "readonly").objectStore(r).index(e).get(t);
            u.onsuccess = function(c) {
                var f;
                const h = (f = c == null ? void 0 : c.target) == null ? void 0 : f.result;
                o && o(h)
            }
            ,
            u.onerror = c=>{
                log$e.error("db query error", c),
                a(c)
            }
        }
        )
    }
    async sleep(e) {
        return new Promise(t=>{
            setTimeout(()=>{
                t("")
            }
            , e)
        }
        )
    }
}
class ModelTable extends BaseTable {
    constructor() {
        super("XverseDatabase", 1)
    }
    tableName() {
        return "models"
    }
    index() {
        return ["url"]
    }
    keyPath() {
        return "url"
    }
}
const modelTable = new ModelTable;
function mapLimit(i, e, t) {
    return new Promise((r,n)=>{
        const o = i.length;
        let a = e - 1
          , s = 0;
        const l = u=>{
            u.forEach(c=>{
                t(c).then(()=>{
                    if (s++,
                    s === o) {
                        r();
                        return
                    }
                    a++;
                    const h = i[a];
                    h && l([h])
                }
                , h=>{
                    n(h)
                }
                )
            }
            )
        }
        ;
        l(i.slice(0, e))
    }
    )
}
const log$d = new Logger("preload");
class Preload {
    constructor(e) {
        E(this, "config");
        E(this, "allKeys", []);
        E(this, "oldResourcesDeleted", !1);
        E(this, "requests", {
            simple: {
                stopped: !0,
                requests: {}
            },
            observer: {
                stopped: !0,
                requests: {}
            },
            full: {
                stopped: !0,
                requests: {}
            }
        });
        this.modelManager = e,
        this.init(e.appId)
    }
    init(e) {
        reporter.updateBody({
            appId: e
        })
    }
    static getTimeoutBySize(e) {
        return e ? e < 500 * 1e3 ? 30 * 1e3 : e < 1e3 * 1e3 ? 60 * 1e3 : 100 * 1e3 : 100 * 1e3
    }
    async getConfig(e) {
        if (this.config)
            return this.config;
        const {preload: t} = await this.modelManager.requestConfig();
        return t ? (this.config = t,
        Promise.resolve(t)) : Promise.reject("no preload config")
    }
    async getAllKeys() {
        if (this.allKeys.length)
            return this.allKeys;
        try {
            const e = await modelTable.getAllKeys();
            return this.allKeys = e,
            e
        } catch {
            const t = "preload getAllKeys error";
            return log$d.error(t),
            Promise.reject(t)
        }
    }
    stop(e) {
        e === "serverless" && (e = "observer"),
        this.requests[e].stopped = !0;
        const t = this.requests[e].requests;
        Object.keys(t).forEach(r=>{
            http$1.canceler.removePending(r),
            delete t[r]
        }
        )
    }
    clearPreload(e) {
        this.requests[e].stopped = !1,
        this.allKeys = []
    }
    async start(e, t, r) {
        let n = Date.now()
          , o = 0;
        try {
            if (e === "serverless" && (e = "observer"),
            !this.requests[e])
                return Promise.reject(new ParamError("invalid stage name: " + e));
            this.clearPreload(e);
            const a = await this.getConfig(e)
              , s = await this.getAllKeys();
            try {
                await this.deleteOldResources(a.assetUrls.map(d=>d.url), s)
            } catch (d) {
                log$d.error(d)
            }
            const {baseUrls: l, assetUrls: u, observeUrls: c} = a;
            let h;
            switch (e) {
            case "simple":
                h = l;
                break;
            case "observer":
                h = u;
                break;
            case "full":
                h = u;
                break;
            default:
                h = u
            }
            let f = h.filter(d=>!s.includes(d.url));
            r && isFunction(r) && (f = f.filter(r)),
            o = f.length,
            log$d.debug("keysNeedToPreload", f),
            f.length || t && t(h.length, h.length),
            n = Date.now(),
            await this._preload(e, f, t),
            log$d.infoAndReportMeasurement({
                tag: e,
                startTime: n,
                metric: "assetsPreload",
                extra: {
                    total: o
                }
            });
            return
        } catch (a) {
            let s = a;
            return (this.requests[e].stopped || axios.isCancel(a)) && (s = new PreloadCanceledError),
            log$d.infoAndReportMeasurement({
                tag: e,
                startTime: n,
                metric: "assetsPreload",
                extra: {
                    total: o
                },
                error: s,
                reportOptions: {
                    immediate: !0
                }
            }),
            Promise.reject(s)
        }
    }
    deleteOldResources(e, t) {
        if (!this.oldResourcesDeleted)
            this.oldResourcesDeleted = !0;
        else
            return Promise.resolve();
        const r = t.filter(n=>!e.includes(n));
        return log$d.debug("keysNeedToDelete", r),
        log$d.warn("keysNeedToDelete", r.length),
        Promise.all(r.map(n=>modelTable.delete(n)))
    }
    async _preload(e, t, r) {
        const n = t.length;
        if (!n)
            return Promise.resolve();
        let o = 0;
        const a = window.setInterval(()=>{
            r && r(o, n),
            o >= n && window.clearInterval(a)
        }
        , 1e3);
        return mapLimit(t, 10, async s=>{
            const {size: l, url: u} = s;
            return this.requests[e].stopped ? Promise.reject(new PreloadCanceledError) : http$1.get({
                url: u,
                timeout: Preload.getTimeoutBySize(l),
                responseType: "blob",
                retry: 2,
                beforeRequest: ()=>{
                    this.requests[e].requests[u] = !0
                }
            }).then(async c=>{
                const h = c.data;
                if (!(h instanceof Blob))
                    return log$d.error("request blob failed, type:", typeof h, u),
                    Promise.reject("request blob failed " + u);
                const f = await blobToDataURI$1(h);
                try {
                    await modelTable.put({
                        url: u,
                        model: f
                    });
                    return
                } catch (d) {
                    return log$d.error("unable to add data to indexedDB", d),
                    Promise.reject(new InternalError("preload db error"))
                }
            }
            ).then(()=>{
                o++,
                delete this.requests[e].requests[u]
            }
            , c=>(delete this.requests[e].requests[u],
            window.clearInterval(a),
            Promise.reject(c)))
        }
        )
    }
}
const log$c = new Logger("xverse")
  , ve = class {
    constructor(e) {
        E(this, "debug", !1);
        E(this, "pageSession");
        E(this, "preload");
        E(this, "appId");
        E(this, "releaseId");
        e || (e = {});
        const {onLog: t, env: r, appId: n, releaseId: o, subPackageVersion: a} = e;
        ve.NO_CACHE = !1,
        ve.env = r || "PROD",
        ve.SUB_PACKAGE_VERSION = a,
        this.debug && Logger.setLevel(LoggerLevels.Debug);
        const s = this.pageSession = uuid$1();
        if (reporter.updateHeader({
            pageSession: s
        }),
        reporter.updateReportUrl(REPORT_URL[ve.env]),
        a && reporter.updateBody({
            sdkVersion: a
        }),
        log$c.infoAndReportMeasurement({
            metric: "sdkInit",
            startTime: Date.now(),
            extra: {
                version: a,
                enviroment: r,
                pageSession: s
            }
        }),
        log$c.debug("debug mode:", this.debug),
        reporter.on("report", l=>{
            t && t(l)
        }
        ),
        n) {
            this.appId = n,
            this.releaseId = o;
            const l = ModelManager.getInstance(n, o);
            this.preload = new Preload(l)
        }
    }
    get isSupported() {
        return isSupported()
    }
    disableLogUpload() {
        reporter.disable(),
        log$c.debug("log upload has been disabled")
    }
    async getSkinList() {
        return []
    }
    async getAvatarList() {
        return []
    }
    async getGiftList() {
        return [{
            id: "hack "
        }]
    }
}
;
let Xverse$1 = ve;
E(Xverse$1, "NO_CACHE"),
E(Xverse$1, "USE_TME_CDN"),
E(Xverse$1, "env"),
E(Xverse$1, "SUB_PACKAGE_VERSION");
const log$b = new Logger("http");
class Http extends EventEmitter {
    async get({url: e, useIndexedDb: t=!1, timeout: r=15e3, key: n, isOutPutObjectURL: o=!0}) {
        if (Xverse$1.NO_CACHE !== void 0 && (t = !Xverse$1.NO_CACHE),
        t)
            if (isIndexedDbSupported()) {
                window.performance.now();
                let a = null;
                try {
                    a = await modelTable.query("url", e)
                } catch (s) {
                    return log$b.debug(s),
                    log$b.warn("cache query error", e),
                    Promise.resolve(e)
                }
                if (a && a.model) {
                    const s = dataURItoBlob(a.model)
                      , l = Promise.resolve(o ? URL.createObjectURL(s) : s);
                    return window.performance.now(),
                    l
                } else
                    return this.request({
                        url: e,
                        timeout: r,
                        contentType: "blob",
                        key: n
                    }).then(async s=>{
                        const l = await blobToDataURI(s.response);
                        try {
                            await modelTable.put({
                                url: e,
                                model: l
                            })
                        } catch (u) {
                            log$b.warn("unable to add data to indexedDB", u)
                        }
                        return Promise.resolve(o ? URL.createObjectURL(s.response) : s.response)
                    }
                    )
            } else
                return this.request({
                    url: e,
                    timeout: r,
                    contentType: "blob",
                    key: n
                }).then(a=>{
                    const s = a.response;
                    return Promise.resolve(o ? URL.createObjectURL(s) : s)
                }
                ).catch(a=>Promise.reject(a));
        else
            return this.request({
                url: e,
                timeout: r,
                key: n
            }).then(a=>a.getResponseHeader("content-type") === "application/json" ? Promise.resolve(JSON.parse(a.responseText)) : Promise.resolve(a.responseText))
    }
    request(e) {
        const {timeout: t=3e4, contentType: r, key: n, onRequestStart: o} = e
          , {url: a} = e;
        return new Promise((s,l)=>{
            window.performance.now();
            const u = new XMLHttpRequest;
            r && (u.responseType = r),
            u.timeout = t,
            u.addEventListener("readystatechange", ()=>{
                if (u.readyState == 4) {
                    if (u.status == 200)
                        return window.performance.now(),
                        this.emit("loadend", {
                            message: `request ${a} load success`
                        }),
                        s(u);
                    {
                        const c = `Unable to load the request ${a}`;
                        return this.emit("error", {
                            message: c
                        }),
                        log$b.error(c),
                        l(c)
                    }
                }
            }
            ),
            o && o(u),
            u.open("GET", a),
            u.send()
        }
        )
    }
}
const http = new Http
  , isIndexedDbSupported = ()=>(window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB) !== void 0
  , blobToDataURI = async i=>new Promise((e,t)=>{
    const r = new FileReader;
    r.readAsDataURL(i),
    r.onload = function(n) {
        var o;
        e((o = n.target) == null ? void 0 : o.result)
    }
    ,
    r.onerror = function(n) {
        t(n)
    }
}
)
  , dataURItoBlob = i=>{
    let e;
    i.split(",")[0].indexOf("base64") >= 0 ? e = atob(i.split(",")[1]) : e = unescape(i.split(",")[1]);
    const t = i.split(",")[0].split(":")[1].split(";")[0]
      , r = new Uint8Array(e.length);
    for (let o = 0; o < e.length; o++)
        r[o] = e.charCodeAt(o);
    return new Blob([r],{
        type: t
    })
}
  , urlMap = new Map
  , urlTransformer = async(i,e=!1)=>typeof i != "string" ? (console.warn("url transformer error", i),
i) : i.startsWith("blob:") ? i : e ? http.get({
    url: i,
    useIndexedDb: !0,
    key: "url",
    isOutPutObjectURL: !1
}) : urlMap.has(i) ? urlMap.get(i) : http.get({
    url: i,
    useIndexedDb: !0,
    key: "url"
}).then(t=>(urlMap.set(i, t),
t));
let sceneManager;
function getSceneManager(i, e) {
    return sceneManager || (sceneManager = new XSceneManager(i,e)),
    sceneManager
}
class TV extends XTelevision {
    constructor(e, t, r, n) {
        super(r.scene, t, r.sceneManager, n);
        E(this, "decal");
        E(this, "id");
        E(this, "imageUrl");
        E(this, "mode", "video");
        E(this, "room");
        E(this, "setVideo", (e,t=!1,r=!0)=>super.setVideo(e, t, r).then(()=>this));
        this.id = e,
        this.room = r,
        this.decal = new XDecalManager(r.sceneManager)
    }
    show() {
        this.mode === "video" ? this.toggle(!0) : this.mode === "poster" && this.showPoster()
    }
    hide() {
        this.mode === "video" ? this.toggle(!1) : this.mode === "poster" && this.hidePoster()
    }
    showVideo() {
        this.mode = "video",
        this.toggle(!0)
    }
    hideVideo() {
        this.toggle(!1)
    }
    showPoster() {
        const e = this.imageUrl;
        if (!e)
            return Promise.reject("set poster url before show it");
        if (!this.decal)
            return Promise.reject("decal was not found");
        const t = this.id;
        return this.decal.addDecal({
            id: t,
            meshPath: this.meshPath
        }).then(()=>{
            var r;
            this.mode = "poster",
            (r = this.decal) == null || r.setDecalTexture({
                id: t,
                buffer: e
            }).then(()=>{
                var n;
                (n = this.decal) == null || n.toggle(t, !0)
            }
            )
        }
        )
    }
    setPoster(e) {
        return this.imageUrl = e,
        this.showPoster()
    }
    hidePoster() {
        return this.decal ? this.decal.toggle(this.id, !1) : Promise.reject("decal was not found")
    }
    setUrl(e) {
        const {url: t, loop: r, muted: n} = e || {};
        return t ? super.setUrl({
            url: t,
            bLoop: r,
            bMuted: n
        }).then(()=>(this.videoElement && (this.videoElement.crossOrigin = "anonymous",
        this.videoElement.playsInline = !0,
        this.videoElement.load()),
        this.mode = "video",
        this)) : Promise.reject("tv url is required")
    }
    mirrorFrom(e) {
        const t = e.getVideoMat();
        return this.setSameVideo(t).then(()=>{
            this.toggle(!0)
        }
        )
    }
    clean() {
        var e;
        this.cleanTv(!1, !0),
        (e = this.decal) == null || e.deleteDecal(this.id)
    }
}
const log$a = new Logger("xverse-bus")
  , ye = class {
    constructor(e) {
        E(this, "_tvs", []);
        E(this, "isRenderFirstFrame", !1);
        E(this, "_idleTime", 0);
        E(this, "renderTimer");
        E(this, "lightManager");
        E(this, "_checkSceneNotReadyCount", 0);
        E(this, "_checkSceneDurationFrameNum", 0);
        E(this, "_checkSceneFrameCount", 0);
        E(this, "timeoutCircularArray", new CircularArray(120,!1,[]));
        E(this, "frameCircularArray", new CircularArray(120,!1,[]));
        E(this, "interFrameCircularArray", new CircularArray(120,!1,[]));
        E(this, "drawCallCntCircularArray", new CircularArray(120,!1,[]));
        E(this, "activeFacesCircularArray", new CircularArray(120,!1,[]));
        E(this, "renderTimeCircularArray", new CircularArray(120,!1,[]));
        E(this, "drawCallTimeCircularArray", new CircularArray(120,!1,[]));
        E(this, "animationCircularArray", new CircularArray(120,!1,[]));
        E(this, "meshSelectCircularArray", new CircularArray(120,!1,[]));
        E(this, "renderTargetCircularArray", new CircularArray(120,!1,[]));
        E(this, "regBeforeRenderCircularArray", new CircularArray(120,!1,[]));
        E(this, "regAfterRenderCircularArray", new CircularArray(120,!1,[]));
        E(this, "renderCnt", 0);
        E(this, "renderErrorCount", 0);
        E(this, "engineSloppyCnt", 0);
        E(this, "systemStuckCnt", 0);
        E(this, "frameRenderNumber", 0);
        E(this, "_setFPS", (e,t=25)=>{
            log$a.info("Set fps to", t);
            const r = t > 60 ? 60 : t < 24 ? 24 : t;
            e.Engine.stopRenderLoop();
            const n = 1e3 / r;
            let o = Date.now()
              , a = Date.now()
              , s = n
              , l = 1;
            const u = ()=>{
                var T;
                const c = Date.now()
                  , h = c - o
                  , f = c - a;
                a = c,
                this.frameCircularArray.add(f),
                h - s > n && (this.systemStuckCnt += 1);
                const d = h / s;
                l = .9 * l + .1 * d;
                const _ = Date.now();
                let g = 0
                  , m = 0;
                if (this.room.isUpdatedRawYUVData || this.room.isPano) {
                    if (this.isRenderFirstFrame = !0,
                    this._checkSceneDurationFrameNum > 0)
                        this._checkSceneFrameCount++,
                        this.room.sceneManager.isReadyToRender({}) && this._checkSceneDurationFrameNum--,
                        this._checkSceneFrameCount > ye._CHECK_DURATION && (this._checkSceneDurationFrameNum = ye._CHECK_DURATION,
                        this._checkSceneFrameCount = 0,
                        this._checkSceneNotReadyCount++,
                        (this._checkSceneNotReadyCount == 1 || this._checkSceneNotReadyCount % 100 == 0) && log$a.error(`[SDK] Scene not ready, skip render. loop: ${this._checkSceneNotReadyCount}`),
                        this._checkSceneNotReadyCount > 10 && (log$a.error("[SDK] Scene not ready, reload later"),
                        this.room.proxyEvents("renderError", {
                            error: new Error("[SDK] Scene not ready, skip render and reload.")
                        })),
                        this.room.stats.assign({
                            renderErrorCount: this._checkSceneNotReadyCount
                        }),
                        log$a.infoAndReportMeasurement({
                            value: 0,
                            startTime: Date.now(),
                            metric: "renderError",
                            error: new Error("[SDK] Scene not ready, skip render and reload."),
                            reportOptions: {
                                sampleRate: .1
                            }
                        }));
                    else
                        try {
                            e.render()
                        } catch (C) {
                            this.renderErrorCount++,
                            this.renderErrorCount > 10 && this.room.proxyEvents("renderError", {
                                error: C
                            }),
                            this.room.stats.assign({
                                renderErrorCount: this.renderErrorCount
                            }),
                            log$a.infoAndReportMeasurement({
                                value: 0,
                                startTime: Date.now(),
                                metric: "renderError",
                                error: C,
                                reportOptions: {
                                    sampleRate: .1
                                }
                            })
                        }
                    g = Date.now() - _,
                    this.frameRenderNumber < 1e3 && this.frameRenderNumber++,
                    this.room.networkController.rtcp.workers.UpdateYUV(),
                    m = Date.now() - _ - g
                }
                this.isRenderFirstFrame || this.room.networkController.rtcp.workers.UpdateYUV();
                const y = Date.now() - _;
                o = c + y,
                s = Math.min(Math.max((n - y) / l, 5), 200),
                y > n && (s = 10,
                this.engineSloppyCnt += 1),
                this._idleTime = s;
                const b = s;
                if (s > 150 && console.log("lastGap is ", s, ", ratio is ", l, ", usedTimeMs is ", y, ", cpuRenderTime is ", g, ", cpuUpdateYUVTime is ", m),
                this.timeoutCircularArray.add(b),
                this.renderCnt % 25 == 0) {
                    const C = this.frameCircularArray.getAvg()
                      , A = this.timeoutCircularArray.getAvg()
                      , S = this.frameCircularArray.getMax()
                      , P = this.timeoutCircularArray.getMax();
                    (T = this.room.stats) == null || T.assign({
                        avgFrameTime: C,
                        avgTimeoutTime: A,
                        maxFrameTime: S,
                        maxTimeoutTime: P,
                        systemStuckCnt: this.systemStuckCnt
                    })
                }
                this.renderTimer = window.setTimeout(u, s)
            }
            ;
            this.renderTimer = window.setTimeout(u, n / l)
        }
        );
        E(this, "updateStats", ()=>{
            var e;
            (e = this.room.stats) == null || e.assign({
                renderFrameTime: this.renderTimeCircularArray.getAvg(),
                maxRenderFrameTime: this.renderTimeCircularArray.getMax(),
                interFrameTime: this.interFrameCircularArray.getAvg(),
                animationTime: this.animationCircularArray.getAvg(),
                meshSelectTime: this.meshSelectCircularArray.getAvg(),
                drawcallTime: this.drawCallTimeCircularArray.getAvg(),
                idleTime: this._idleTime,
                registerBeforeRenderTime: this.regBeforeRenderCircularArray.getAvg(),
                registerAfterRenderTime: this.regAfterRenderCircularArray.getAvg(),
                renderTargetRenderTime: this.renderTargetCircularArray.getAvg(),
                fps: (1e3 / (this.renderTimeCircularArray.getAvg() + this.interFrameCircularArray.getAvg())).toFixed(2),
                drawcall: this.drawCallCntCircularArray.getAvg(),
                engineSloppyCnt: this.engineSloppyCnt,
                maxInterFrameTime: this.interFrameCircularArray.getMax(),
                maxDrawcallTime: this.drawCallTimeCircularArray.getMax(),
                maxMeshSelectTime: this.meshSelectCircularArray.getMax(),
                maxAnimationTime: this.animationCircularArray.getMax(),
                maxRegisterBeforeRenderTime: this.regBeforeRenderCircularArray.getMax(),
                maxRegisterAfterRenderTime: this.regAfterRenderCircularArray.getMax(),
                maxRenderTargetRenderTime: this.renderTargetCircularArray.getMax(),
                avgFrameTime: this.frameCircularArray.getAvg(),
                avgTimeoutTime: this.timeoutCircularArray.getAvg(),
                maxFrameTime: this.frameCircularArray.getMax(),
                maxTimeoutTime: this.timeoutCircularArray.getMax()
            })
        }
        );
        this.room = e
    }
    async initEngine(e) {
        await this.updateBillboard(),
        log$a.info("engine version:", VERSION$1);
        const t = new Logger("engine");
        t.setLevel(LoggerLevels.Warn);
        const r = {
            videoResOriArray: [{
                width: 720,
                height: 1280
            }, {
                width: 1280,
                height: 720
            }, {
                width: 480,
                height: 654
            }, {
                width: 654,
                height: 480
            }, {
                width: 1920,
                height: 1080
            }, {
                width: 1080,
                height: 1920
            }, {
                width: 414,
                height: 896
            }],
            forceKeepVertical: this.room.options.objectFit !== "cover",
            panoInfo: {
                dynamicRange: 1,
                width: 4096,
                height: 2048
            },
            shaderMode: EShaderMode.videoAndPano,
            yuvInfo: {
                width: 1280,
                height: 720,
                fov: e.fov || DEFAULT_MAIN_CAMERA_FOV
            },
            cameraParam: {
                maxZ: 1e4
            },
            urlTransformer,
            logger: t,
            disableWebGL2: this.room.options.disableWebGL2 || !1
        }
          , n = this.room.options.resolution;
        n && (r.videoResOriArray.some(l=>l.width === n.width && l.height === n.height) || r.videoResOriArray.push(n));
        const o = this.room.sceneManager = getSceneManager(this.room.canvas, r);
        this.room.setPictureQualityLevel(this.room.options.pictureQualityLevel || "high"),
        this.room.sceneManager.staticmeshComponent.setRegionLodRule([2, 2, -1, -1, -1]),
        this.room.scene = o.Scene,
        this.room.breathPointManager = o.breathPointComponent,
        this.lightManager = o.lightComponent,
        this.registerStats(),
        this.setEnv(e),
        await this.room.avatarManager.init();
        const a = this._createAssetList(e);
        await this.loadAssets(a, ""),
        this._setFPS(o)
    }
    pause() {
        clearTimeout(this.renderTimer),
        log$a.info("Invoke room.pause to pause render");
        const e = {
            roomId: this.room.id,
            effects: [],
            lowPolyModels: [],
            breathPointsConfig: [],
            skinId: this.room.skinId
        };
        return this.loadAssets(e, this.room.skinId)
    }
    async resume() {
        this._setFPS(this.room.sceneManager),
        this.room.sceneManager.cameraComponent.cameraFovChange(this.room.sceneManager.yuvInfo),
        log$a.info("Invoke room.resume to render");
        const e = this._createAssetList(this.room.skin);
        await this.loadAssets(e, "")
    }
    setEnv(e) {
        var r;
        this.lightManager || (this.lightManager = this.room.sceneManager.lightComponent),
        e = e || this.room.skin;
        const t = ModelManager.findModel(e.models, AssetTypeName.Config, AssetClassName.Env);
        return t ? (r = this.lightManager) == null ? void 0 : r.setIBL(t.modelUrl) : (log$a.error("env file not found"),
        Promise.resolve())
    }
    async _parseModelsAndLoad(e, t, r) {
        log$a.info("Invoke _parseModelsAndLoad start", t);
        const n = ["airship", "balloon", "default", "ground_feiting", "ground_reqiqiu"]
          , o = new Map;
        r == null && (r = "xxxx");
        let a = !0;
        for (let u = 0; u < e.length; ++u) {
            a = !0;
            for (let c = 0; c < n.length; ++c)
                if (e[u].modelUrl.toLowerCase().indexOf(n[c]) >= 0) {
                    const h = o.get(n[c]);
                    h ? (h.push(e[u]),
                    o.set(n[c], h)) : o.set(n[c], [e[u]]),
                    a = !1;
                    break
                }
            if (a) {
                const c = o.get("default");
                c ? (c.push(e[u]),
                o.set("default", c)) : o.set("default", [e[u]])
            }
        }
        let s = o.get(t) || [];
        if (this.room.viewMode === "simple" && (s = s.filter(u=>!u.modelUrl.endsWith("zip"))),
        !s)
            return Promise.reject(`no invalid scene model with group name: ${t}`);
        const l = [];
        for (let u = 0; u < s.length; ++u) {
            const c = s[u];
            if (c.modelUrl.toLowerCase().endsWith("zip"))
                c.modelUrl.toLowerCase().endsWith("zip") && l.push(this.room.sceneManager.addNewLowPolyMesh({
                    url: c.modelUrl,
                    skinInfo: r
                }));
            else {
                const h = t;
                l.push(this.room.sceneManager.addNewLowPolyMesh({
                    url: c.modelUrl,
                    group: h,
                    pick: !0,
                    skinInfo: r
                }))
            }
        }
        return Promise.all(l)
    }
    async _deleteAssetsLowpolyModel(e) {
        this.room.sceneManager.staticmeshComponent.deleteMeshesBySkinInfo(e),
        this.room.sceneManager.breathPointComponent.clearBreathPointsBySkinInfo(e),
        this.room.sceneManager.decalComponent.deleteDecalBySkinInfo(e);
        const t = [];
        this.room.sceneManager.Scene.meshes.forEach(r=>{
            r.xskinInfo == e && t.push(r)
        }
        ),
        t.forEach(r=>{
            r.dispose(!1, !1)
        }
        )
    }
    async loadLandAssets() {
        const e = this._createAssetList(this.room.skin);
        return this.loadAssets(e, this.room.skinId).catch(()=>this.loadAssets(e, this.room.skinId))
    }
    async loadAssets(e, t="", r=8e3) {
        const n = Date.now();
        return this._loadAssets(e, t)._timeout(r, new InitEngineTimeoutError(`loadAssets timeout(${r}ms)`)).then(o=>(log$a.infoAndReportMeasurement({
            tag: "loadAssets",
            startTime: n,
            metric: "loadAssets"
        }),
        o)).catch(o=>(log$a.infoAndReportMeasurement({
            tag: "loadAssets",
            startTime: n,
            metric: "loadAssets",
            error: o
        }),
        Promise.reject(o)))
    }
    async _loadAssets(e, t="") {
        try {
            const r = [];
            r.push(this._loadAssetsLowpolyModel(e, t)),
            await Promise.all(r),
            await this.setEnv(),
            this._checkSceneDurationFrameNum = ye._CHECK_DURATION,
            this._checkSceneNotReadyCount = 0,
            this._checkSceneFrameCount = 0,
            this.updateAnimationList(),
            this.room.loadAssetsHook()
        } catch (r) {
            return Promise.reject(r)
        }
    }
    updateAnimationList() {
        if (this.room.avatarManager && this.room.avatarManager.xAvatarManager) {
            const e = this.room.skin.animationList;
            if (!e)
                return;
            e.forEach(t=>{
                this.room.avatarManager.xAvatarManager.updateAnimationLists(t.animations, t.avatarId)
            }
            )
        }
    }
    async _loadAssetsLowpolyModel(e, t="") {
        const r = []
          , n = []
          , o = [];
        e.lowPolyModels.forEach(f=>{
            f.group === "TV" ? n.push({
                id: "",
                name: "",
                thumbnailUrl: "",
                typeName: AssetTypeName.Model,
                className: AssetClassName.Tv,
                modelUrl: f.url
            }) : f.group === "\u544A\u767D\u5899" ? o.push({
                id: "",
                name: "",
                thumbnailUrl: "",
                typeName: AssetTypeName.Model,
                className: AssetClassName.Lpm,
                modelUrl: f.url
            }) : r.push({
                id: "",
                name: "",
                thumbnailUrl: "",
                typeName: AssetTypeName.Model,
                className: AssetClassName.Lpm,
                modelUrl: f.url
            })
        }
        ),
        t != "" && t != null && this._deleteAssetsLowpolyModel(t);
        const a = e.skinId;
        log$a.info("====> from ", t, "  to  ", a),
        this._tvs.forEach(f=>f.clean()),
        this._tvs = [];
        let s = EFitMode.cover;
        a == "10048" && (s = EFitMode.contain),
        Array.isArray(n) && n.forEach((f,d)=>{
            this._tvs.push(new TV("squareTv" + d,f.modelUrl,this.room,{
                fitMode: s
            }))
        }
        ),
        e.breathPointsConfig.forEach(async f=>{
            let d;
            try {
                d = await urlTransformer(f.imageUrl)
            } catch (_) {
                d = f.imageUrl,
                log$a.error("urlTransformer error", _)
            }
            this.room.breathPointManager.addBreathPoint({
                id: f.id,
                position: f.position,
                spriteSheet: d,
                rotation: f.rotation || {
                    pitch: 0,
                    yaw: 270,
                    roll: 0
                },
                billboardMode: !0,
                type: f.type || "no_type",
                spriteWidthNumber: f.spriteWidthNum || 1,
                spriteHeightNumber: f.spriteHeightNum || 1,
                maxVisibleRegion: f.maxVisibleRegion || 150,
                width: f.width,
                height: f.height,
                skinInfo: f.skinId
            })
        }
        ),
        o.forEach(f=>{
            this.room.sceneManager.decalComponent.addDecal({
                id: f.id || "gbq",
                meshPath: f.modelUrl,
                skinInfo: a
            })
        }
        );
        const u = this.room.sceneManager.staticmeshComponent.lowModel_group
          , c = Array.from(u.keys()).filter(f=>!f.startsWith("region_"))
          , h = ["airship", "balloon", "ground_feiting", "ground_reqiqiu", "default"];
        return new Promise((f,d)=>{
            Promise.all(h.map(_=>this._parseModelsAndLoad(r, _, a))).then(()=>{
                let _ = !1;
                r.forEach(v=>{
                    v.modelUrl.endsWith("zip") && (_ = !0)
                }
                ),
                _ == !1 && this.room.sceneManager.staticmeshComponent.deleteLastRegionMesh(),
                this.room.sceneManager.staticmeshComponent.lowModel_group;
                const g = Array.from(u.keys()).filter(v=>!v.startsWith("region_"))
                  , m = c.filter(v=>g.indexOf(v) < 0);
                m.length > 0 && m.forEach(v=>{
                    this.room.sceneManager.staticmeshComponent.deleteMeshesByGroup(v)
                }
                ),
                f(!0)
            }
            ).catch(_=>{
                d(_)
            }
            )
        }
        )
    }
    async _updateSkinAssets(e) {
        const t = this.room.lastSkinId
          , r = await this.room.getSkin(e)
          , n = this._createAssetList(r);
        try {
            await this.loadAssets(n, t),
            this.room.updateCurrentState({
                versionId: r.versionId,
                skinId: r.id,
                skin: r
            })
        } catch {
            await this.loadAssets(n, t),
            this.room.updateCurrentState({
                versionId: r.versionId,
                skinId: r.id,
                skin: r
            })
        }
        this.setEnv(r)
    }
    _createAssetList(e) {
        const t = []
          , r = []
          , n = [];
        let o = e.models;
        const a = this.room.modelManager.config.preload;
        return this.room.viewMode === "simple" ? a && (o = a.baseUrls.map(l=>(l.modelUrl = l.url,
        l))) : this.room.viewMode,
        ModelManager.findModels(o, AssetTypeName.Effects, AssetClassName.Effects).forEach(l=>{
            t.push({
                url: l.modelUrl,
                group: l.className,
                name: l.name
            })
        }
        ),
        ModelManager.findModels(o, AssetTypeName.Model, AssetClassName.Lpm).forEach(l=>{
            r.push({
                url: l.modelUrl,
                group: l.className
            })
        }
        ),
        ModelManager.findModels(o, AssetTypeName.Model, AssetClassName.Gbq).forEach(l=>{
            r.push({
                url: l.modelUrl,
                group: l.className
            })
        }
        ),
        ModelManager.findModels(o, AssetTypeName.Model, AssetClassName.Tv).forEach(l=>{
            r.push({
                url: l.modelUrl,
                group: l.className
            })
        }
        ),
        [].forEach(l=>{
            l.skinId == e.id && n.push(l)
        }
        ),
        {
            roomId: this.room.id,
            effects: t,
            lowPolyModels: r,
            breathPointsConfig: n,
            skinId: e.id
        }
    }
    registerStats() {
        const e = this.room.sceneManager;
        this.room.scene.registerAfterRender(()=>{
            var I;
            const t = e.statisticComponent.getInterFrameTimeCounter()
              , r = e.statisticComponent.getDrawCall()
              , n = e.statisticComponent.getActiveFaces()
              , o = e.statisticComponent.getFrameTimeCounter()
              , a = e.statisticComponent.getDrawCallTime()
              , s = e.statisticComponent.getAnimationTime()
              , l = e.statisticComponent.getActiveMeshEvaluationTime()
              , u = e.statisticComponent.getRenderTargetRenderTime()
              , c = e.statisticComponent.getRegisterBeforeRenderTime()
              , h = e.statisticComponent.getRegisterAfterRenderTime()
              , f = e.statisticComponent.getActiveParticles()
              , d = e.statisticComponent.getActiveBones()
              , _ = e.Scene._activeAnimatables.length
              , g = e.statisticComponent.getTotalRootNodes()
              , m = e.Scene.geometries.length
              , v = e.Scene.onBeforeRenderObservable.observers.length
              , y = e.Scene.onAfterRenderObservable.observers.length
              , b = e.statisticComponent.getTotalMeshes()
              , T = e.statisticComponent.getTotalTextures()
              , C = e.statisticComponent.getTotalMaterials()
              , A = e.statisticComponent.getSystemInfo()
              , S = A.resolution
              , P = A.driver;
            A.vender;
            const R = A.version
              , M = A.hardwareScalingLevel
              , x = S + "_" + P + "_" + R + "_" + M;
            this.interFrameCircularArray.add(t),
            this.renderTimeCircularArray.add(o),
            this.animationCircularArray.add(s),
            this.meshSelectCircularArray.add(l),
            this.drawCallTimeCircularArray.add(a),
            this.regAfterRenderCircularArray.add(h),
            this.regBeforeRenderCircularArray.add(c),
            this.renderTargetCircularArray.add(u),
            this.drawCallCntCircularArray.add(r),
            this.renderCnt += 1,
            this.renderCnt % 25 == 0 && ((I = this.room.stats) == null || I.assign({
                renderFrameTime: this.renderTimeCircularArray.getAvg(),
                maxRenderFrameTime: this.renderTimeCircularArray.getMax(),
                interFrameTime: this.interFrameCircularArray.getAvg(),
                animationTime: this.animationCircularArray.getAvg(),
                meshSelectTime: this.meshSelectCircularArray.getAvg(),
                drawcallTime: this.drawCallTimeCircularArray.getAvg(),
                idleTime: this._idleTime,
                registerBeforeRenderTime: this.regBeforeRenderCircularArray.getAvg(),
                registerAfterRenderTime: this.regAfterRenderCircularArray.getAvg(),
                renderTargetRenderTime: this.renderTargetCircularArray.getAvg(),
                fps: (1e3 / (this.renderTimeCircularArray.getAvg() + this.interFrameCircularArray.getAvg())).toFixed(2),
                drawcall: this.drawCallCntCircularArray.getAvg(),
                triangle: n.toString(),
                engineSloppyCnt: this.engineSloppyCnt,
                maxInterFrameTime: this.interFrameCircularArray.getMax(),
                maxDrawcallTime: this.drawCallTimeCircularArray.getMax(),
                maxMeshSelectTime: this.meshSelectCircularArray.getMax(),
                maxAnimationTime: this.animationCircularArray.getMax(),
                maxRegisterBeforeRenderTime: this.regBeforeRenderCircularArray.getMax(),
                maxRegisterAfterRenderTime: this.regAfterRenderCircularArray.getMax(),
                maxRenderTargetRenderTime: this.renderTargetCircularArray.getMax(),
                activeParticles: f,
                activeBones: d,
                activeAnimation: _,
                totalMeshes: b,
                totalRootNodes: g,
                totalGeometries: m,
                totalTextures: T,
                totalMaterials: C,
                registerBeforeCount: v,
                registerAfterCount: y,
                hardwareInfo: x
            }))
        }
        )
    }
    async updateBillboard() {
        const {options: {skinId: e}} = this.room
          , r = (await this.room.modelManager.findAssetList(e)).filter(a=>a.typeName === AssetTypeName.Textures && a.className === AssetClassName.SayBubble)
          , n = ["bubble01", "bubble02", "bubble03"]
          , o = ["bubble01_npc", "bubble02_npc", "bubble03_npc"];
        if (r.length) {
            const a = r.filter(l=>n.includes(l.name)).map(l=>l.url)
              , s = r.filter(l=>o.includes(l.name)).map(l=>l.url);
            a.length && (XBillboardManager.userBubbleUrls = a),
            s.length && (XBillboardManager.npcBubbleUrls = s)
        }
    }
}
;
let EngineProxy = ye;
E(EngineProxy, "_CHECK_DURATION", 2);
var CameraStates = (i=>(i[i.Normal = 0] = "Normal",
i[i.ItemView = 1] = "ItemView",
i[i.CGView = 2] = "CGView",
i[i.PathView = 3] = "PathView",
i))(CameraStates || {})
  , Direction = (i=>(i.Left = "left",
i.Right = "right",
i))(Direction || {});
const calNormVector = (i,e)=>{
    let t = 0;
    for (let n = 0; n < 3; ++n)
        t = t + (e[n] - i[n]) * (e[n] - i[n]);
    return t = Math.sqrt(t),
    [(e[0] - i[0]) / t, (e[1] - i[1]) / t, (e[2] - i[2]) / t]
}
  , vectorCrossMulti = (i,e)=>{
    const t = i[0]
      , r = i[2]
      , n = e[0]
      , o = e[2];
    return t * o - r * n
}
  , log$9 = new Logger("camera");
class Camera extends EventEmitter {
    constructor(e) {
        super();
        E(this, "initialFov", 0);
        E(this, "_state", CameraStates.Normal);
        E(this, "_person", Person.Third);
        E(this, "_room");
        E(this, "_cameraFollowing", !0);
        E(this, "checkPointOnLeftOrRight", e=>{
            const t = ue4Position2Xverse(e);
            if (!t || this.checkPointInView(e))
                return;
            const o = this._room.scene.activeCamera;
            if (!o)
                return;
            const a = [o.target.x, o.target.y, o.target.z]
              , s = [o.position.x, o.position.y, o.position.z]
              , {x: l, y: u, z: c} = t
              , h = calNormVector(s, a)
              , f = calNormVector(s, [l, u, c]);
            return vectorCrossMulti(h, f) < 0 ? Direction.Right : Direction.Left
        }
        );
        E(this, "checkPointInView", ({x: e, y: t, z: r})=>{
            const n = ue4Position2Xverse({
                x: e,
                y: t,
                z: r
            });
            if (!n)
                return !1;
            for (let o = 0; o < 6; o++)
                if (this._room.scene.frustumPlanes[o].dotCoordinate(n) < 0)
                    return !1;
            return !0
        }
        );
        this._room = e
    }
    get person() {
        return this._person
    }
    get state() {
        return this._state
    }
    get pose() {
        return this._room.currentClickingState.camera
    }
    set cameraFollowing(e) {
        log$9.info("cameraFollowing setter", e),
        this.setCameraFollowing({
            isFollowHost: e
        })
    }
    get cameraFollowing() {
        return this._cameraFollowing
    }
    setCameraFollowing({isFollowHost: e}) {}
    handleRenderInfo(e) {
        const {cameraStateType: t} = e.renderInfo
          , r = this._room.sceneManager;
        if (t !== this._state && (this._state = t,
        log$9.debug("camera._state changed to", CameraStates[t]),
        t === CameraStates.CGView ? (r.cameraComponent.switchToCgCamera(),
        r.staticmeshComponent.getCgMesh().show()) : (r.cameraComponent.switchToMainCamera(),
        r.staticmeshComponent.getCgMesh().hide()),
        this.emit("stateChanged", {
            state: t
        })),
        this._room.isHost)
            return;
        const {isFollowHost: n} = e.playerState;
        !!n !== this._cameraFollowing && (this._cameraFollowing = !!n,
        this.emit("cameraFollowingChanged", {
            cameraFollowing: !!n
        }))
    }
    setCameraState({state: e}) {
        if (this._state === e) {
            log$9.warn(`You are already in ${CameraStates[e]} camera state`);
            return
        }
        e === CameraStates.Normal || this._state === CameraStates.ItemView && log$9.warn("CloseUp camera state can only be triggerd by room internally")
    }
    turnToFace({extra: e="", offset: t=0}) {
        const r = {
            action_type: Actions.TurnToFace,
            turn_to_face_action: {
                offset: t
            }
        };
        return this.emit("viewChanged", {
            extra: e
        }),
        this._room.actionsHandler.sendData({
            data: r
        })
    }
    isInDefaultView() {
        if (!this._room.isHost) {
            log$9.warn("It is recommended to call the function on the host side");
            return
        }
        if (!this._room._currentClickingState)
            return log$9.error("CurrentState should not be empty"),
            !1;
        const {camera: e, player: t} = this._room._currentClickingState;
        return Math.abs(t.angle.yaw - 180 - e.angle.yaw) % 360 <= 4
    }
    async screenShot({name: e, autoSave: t=!1}) {
        const r = this._room.scene.getEngine()
          , n = this._room.scene.activeCamera;
        try {
            this._room.sceneManager.setImageQuality(EImageQuality.high);
            const o = await CreateScreenshotAsync(r, n, {
                precision: 1
            });
            return this._room.sceneManager.setImageQuality(EImageQuality.low),
            t === !0 && downloadFileByBase64(o, e),
            Promise.resolve(o)
        } catch (o) {
            return this._room.sceneManager.setImageQuality(EImageQuality.low),
            Promise.reject(o)
        }
    }
    changeToFirstPerson(e, t, r) {
        const {camera: n, player: o, attitude: a, areaName: s, pathName: l} = e;
        return this._room.actionsHandler.requestPanorama({
            camera: n,
            player: o,
            attitude: a,
            areaName: s,
            pathName: l
        }, t, r).then(()=>{
            this._room.networkController.rtcp.workers.changePanoMode(!0);
            const {position: u, angle: c} = o || {};
            this._room.sceneManager.cameraComponent.changeToFirstPersonView({
                position: u,
                rotation: c
            })
        }
        )
    }
    setPerson(e, t={
        camera: this._room._currentClickingState.camera,
        player: this._room._currentClickingState.player
    }) {
        const r = Date.now();
        return this._setPerson(e, t).then(n=>(log$9.infoAndReportMeasurement({
            tag: Person[e],
            startTime: r,
            metric: "setPerson"
        }),
        n)).catch(n=>(log$9.infoAndReportMeasurement({
            tag: Person[e],
            startTime: r,
            metric: "setPerson",
            error: n
        }),
        Promise.reject(n)))
    }
    _setPerson(e, t={
        camera: this._room._currentClickingState.camera,
        player: this._room._currentClickingState.player
    }) {
        return e !== Person.First && e !== Person.Third ? Promise.reject("invalid person " + e) : !t.camera || !t.player ? Promise.reject(new ParamError("wrong camera or player")) : e === Person.First ? this._room.panorama.access({
            camera: t.camera,
            player: t.player,
            tag: "setPerson"
        }).then(()=>{
            var o, a;
            this._person = e,
            (o = this._room._userAvatar) == null || o.hide();
            const {position: r, angle: n} = ((a = this._room.currentClickingState) == null ? void 0 : a.camera) || {};
            !r || !n || this._room.sceneManager.cameraComponent.changeToFirstPersonView({
                position: r,
                rotation: n
            })
        }
        ) : this._room.panorama.exit({
            camera: t.camera,
            player: t.player
        }).then(()=>{
            var r, n;
            this._person = e,
            (r = this._room._userAvatar) != null && r.xAvatar && ((n = this._room._userAvatar) == null || n.xAvatar.show())
        }
        )
    }
    setCameraPose(e) {
        this._room.sceneManager.cameraComponent.setCameraPose({
            position: e.position,
            rotation: e.angle
        })
    }
    setMainCameraRotationLimit(e) {
        const {limitAxis: t, limitRotation: r} = e;
        this._room.sceneManager.cameraComponent.setMainCameraRotationLimit(t, r)
    }
}
var IEffectType = (i=>(i.Sequence = "sequence",
i.SubSequence = "subSequence",
i))(IEffectType || {});
const log$8 = new Logger("effectManager");
class XverseEffect extends EventEmitter {
    constructor({id: e, jsonPath: t, type: r, room: n, scale: o=1}) {
        super();
        E(this, "_id");
        E(this, "type");
        E(this, "effect");
        E(this, "avatarEffect");
        E(this, "_room");
        E(this, "_isLoading", !0);
        E(this, "_failed", !1);
        E(this, "_scale", 1);
        this._room = n,
        this._id = e,
        this.type = r,
        this._scale = o,
        this.effect = e === "Rain" || e === "Boom" ? new XRain(this._room.scene,t,urlTransformer) : r === IEffectType.Sequence ? new XSequence(this._room.scene,t,"",urlTransformer) : new XSubSequence(this._room.scene,t,urlTransformer),
        this.avatarEffect = new XSubSequence(this._room.scene,t,urlTransformer)
    }
    get failed() {
        return this._failed
    }
    get position() {
        if (this.type !== IEffectType.Sequence)
            return this.effect.position
    }
    get rotation() {
        if (this.type !== IEffectType.Sequence)
            return this.effect.rotation
    }
    get isLoading() {
        return this._isLoading
    }
    get id() {
        return this._id
    }
    get name() {
        return this.effect.name
    }
    get isPlaying() {
        var e;
        return !!((e = this.effect) != null && e.isPlaying)
    }
    async init() {
        try {
            await this.effect.init()._timeout(1e4, new TimeoutError("effect init timeout(10s)")),
            this._isLoading = !1,
            this._failed = !1
        } catch (e) {
            throw this._isLoading = !1,
            this._failed = !0,
            log$8.error(`effect: ${this.id} init error`, e),
            e
        }
    }
    play(e=!1) {
        return new Promise((t,r)=>{
            this.effect.play(e),
            this.isPlaying ? t() : r(`play effect: ${this.name} failed`)
        }
        )
    }
    hide() {
        return this.effect.hide()
    }
    show() {
        return this.effect.show()
    }
    setRotation(e) {
        var t;
        return this.type === IEffectType.Sequence ? Promise.reject("setRotation failed, sequence unSuported") : (t = this.effect) == null ? void 0 : t.setRotation(e)
    }
    setPosition(e) {
        var t;
        return this.type === IEffectType.Sequence ? Promise.reject("setPosition failed, sequence unSuported") : (t = this.effect) == null ? void 0 : t.setPosition(e)
    }
    setScaling(e) {
        var t;
        return this.type === IEffectType.Sequence ? Promise.reject("setScaling failed, sequence unSuported") : (this._scale = e,
        (t = this.effect) == null ? void 0 : t.setScaling({
            x: e,
            y: e,
            z: e
        }))
    }
    dispose() {
        this.effect.dispose()
    }
}
const log$7 = new Logger("xverse-effect-manager")
  , Ae = class extends EventEmitter {
    constructor(e) {
        super();
        E(this, "effects", new Map);
        E(this, "room");
        this.room = e
    }
    async addEffect(e) {
        var o;
        const {jsonPath: t, id: r, type: n=IEffectType.SubSequence} = e;
        try {
            this.effects.get(r) && ((o = this.effects.get(r)) == null || o.dispose());
            const a = new Ae.subEffect({
                id: r,
                jsonPath: t,
                type: n,
                room: this.room
            });
            return this.effects.set(r, a),
            await a.init(),
            a
        } catch (a) {
            return this.effects.delete(r),
            log$7.error(a),
            Promise.reject(a)
        }
    }
    clearEffects() {
        this.effects.forEach(e=>{
            e.dispose(),
            this.effects.delete(e.id)
        }
        )
    }
    removeEffect(e) {
        const t = this.effects.get(e);
        t == null || t.dispose(),
        t && this.effects.delete(t.id)
    }
}
;
let XverseEffectManager = Ae;
E(XverseEffectManager, "subEffect", XverseEffect);
Scene.DoubleClickDelay = 500;
const LongPressMesh = [EMeshType.XAvatar];
class StaticMeshEvent extends EventEmitter {
    constructor(e) {
        super();
        E(this, "scene");
        E(this, "_staringPointerTime", -1);
        E(this, "_pickedMeshID", "0");
        E(this, "_pointerDownTime", -1);
        E(this, "_currentPickPoint");
        E(this, "_longPressDelay", 500);
        E(this, "_pointerTapDelay", 200);
        E(this, "_pickedMeshType");
        E(this, "registerEvent", ()=>{
            this.scene.onPrePointerObservable.add(this.onDown, PointerEventTypes.POINTERDOWN),
            this.scene.onPrePointerObservable.add(this.onUp, PointerEventTypes.POINTERUP),
            this.scene.onPrePointerObservable.add(this.onDoubleTap, PointerEventTypes.POINTERDOUBLETAP),
            this.scene.onDispose = ()=>{
                this.scene.onPrePointerObservable.removeCallback(this.onUp),
                this.scene.onPrePointerObservable.removeCallback(this.onDown),
                this.scene.onPrePointerObservable.removeCallback(this.onDoubleTap)
            }
        }
        );
        E(this, "onUp", ()=>{
            if (Date.now() - this._pointerDownTime < this._pointerTapDelay && !this.scene._inputManager._isPointerSwiping()) {
                this.scene._inputManager._totalPointersPressed = 0;
                let e = this._currentPickPoint;
                e != null && LongPressMesh.indexOf(e.type) == -1 && this.scene._inputManager._totalPointersPressed == 0 && this.emit("pointTap", e),
                e != null && LongPressMesh.indexOf(e.type) != -1 && (e = this.onPointerTap(t=>t.isPickable && LongPressMesh.indexOf(t.xtype) == -1),
                e != null && this.emit("pointTap", e))
            }
        }
        );
        E(this, "onDown", ()=>{
            let e = this.onPointerTap(t=>t.isPickable);
            this._currentPickPoint = e,
            this._pointerDownTime = Date.now(),
            e != null && LongPressMesh.indexOf(e.type) != -1 && (this._staringPointerTime = Date.now(),
            this._pickedMeshID = e.id,
            this._pickedMeshType = e.type,
            window.setTimeout(()=>{
                e = this.onPointerTap(t=>t.isPickable && t.xtype == this._pickedMeshType && t.xid == this._pickedMeshID),
                e !== null && Date.now() - this._staringPointerTime > this._longPressDelay && !this.scene._inputManager._isPointerSwiping() && this.scene._inputManager._totalPointersPressed !== 0 && (this._staringPointerTime = 0,
                this.emit("longPress", e))
            }
            , this._longPressDelay))
        }
        );
        E(this, "onDoubleTap", ()=>{
            const e = this.onPointerTap(void 0);
            e != null && this.emit("pointDoubleTap", e)
        }
        );
        this.manager = e,
        this.scene = e.Scene,
        this.registerEvent(),
        this._currentPickPoint = null,
        this._pickedMeshType = null
    }
    onPointerTap(e, t=!1) {
        var n, o;
        let r = new PickingInfo;
        if (t) {
            const a = this.scene.multiPick(this.scene.pointerX, this.scene.pointerY, e, void 0, void 0);
            a && a.length > 1 ? r = a[1] : a && (r = a[0])
        } else
            r = this.scene.pick(this.scene.pointerX, this.scene.pointerY, e, !1, null);
        if (r.hit) {
            const a = (n = r == null ? void 0 : r.pickedPoint) == null ? void 0 : n.asArray();
            if (a) {
                const [s,l,u] = a
                  , c = xversePosition2Ue4({
                    x: s,
                    y: l,
                    z: u
                });
                return {
                    name: (o = r.pickedMesh) == null ? void 0 : o.name,
                    type: r.pickedMesh.xtype,
                    id: r.pickedMesh.xid,
                    point: c
                }
            }
        }
        return null
    }
}
class RotationEvent {
    constructor(e) {
        E(this, "touchStartX");
        E(this, "touchStartY");
        E(this, "handelResize");
        E(this, "_room");
        E(this, "_canvas");
        E(this, "handleTouchStart", e=>{
            const t = e.touches[0];
            this.touchStartX = t.pageX,
            this.touchStartY = t.pageY,
            this._room.emit("touchStart", {
                event: e
            })
        }
        );
        E(this, "handleMouseDown", e=>{
            this.touchStartX = e.pageX,
            this.touchStartY = e.pageY
        }
        );
        E(this, "handleMouseMove", e=>{
            if (!this.touchStartX || !this.touchStartY)
                return;
            const t = e.pageX
              , r = e.pageY
              , n = t - this.touchStartX
              , o = r - this.touchStartY
              , a = this._room.options.canvas.offsetHeight
              , s = this._room.options.canvas.offsetWidth;
            let l = 2 * o / a
              , u = 2 * n / s;
            l > 1 && (l = 1),
            u > 1 && (u = 1),
            this._room.actionsHandler.rotate({
                pitch: l,
                yaw: u
            }),
            this.touchStartX = t,
            this.touchStartY = r
        }
        );
        E(this, "handleMouseUp", ()=>{
            this.touchStartX = void 0,
            this.touchStartY = void 0
        }
        );
        E(this, "handleTouchMove", e=>{
            if (!this.touchStartX || !this.touchStartY)
                return;
            const t = e.touches[0]
              , r = t.pageX
              , n = t.pageY
              , o = r - this.touchStartX
              , a = n - this.touchStartY
              , s = this._room.options.canvas.offsetHeight
              , l = this._room.options.canvas.offsetWidth;
            let u = 2 * a / s
              , c = 2 * o / l;
            u > 1 && (u = 1),
            c > 1 && (c = 1),
            this._room.actionsHandler.rotate({
                pitch: u,
                yaw: c
            }),
            this.touchStartX = r,
            this.touchStartY = n,
            this._room.emit("touchMove", {
                pitch: u,
                yaw: c,
                event: e
            })
        }
        );
        E(this, "handleTouchEnd", e=>{
            this._room.emit("touchEnd", {
                event: e
            })
        }
        );
        this._room = e,
        this._canvas = e.canvas,
        this.handelResize = this.reiszeChange()
    }
    init() {
        this._canvas.addEventListener("touchstart", this.handleTouchStart),
        this._canvas.addEventListener("touchmove", this.handleTouchMove),
        this._canvas.addEventListener("touchend", this.handleTouchEnd),
        this._room.scene.preventDefaultOnPointerDown = !1,
        this._room.scene.preventDefaultOnPointerUp = !1,
        this._canvas.addEventListener("mousedown", this.handleMouseDown),
        this._canvas.addEventListener("mousemove", this.handleMouseMove),
        this._canvas.addEventListener("mouseup", this.handleMouseUp)
    }
    clear() {
        this._canvas.removeEventListener("touchstart", this.handleTouchStart),
        this._canvas.removeEventListener("touchmove", this.handleTouchMove),
        this._canvas.removeEventListener("touchend", this.handleTouchEnd),
        this._canvas.removeEventListener("mousedown", this.handleMouseDown),
        this._canvas.removeEventListener("mousemove", this.handleMouseMove),
        this._canvas.removeEventListener("mouseup", this.handleMouseUp)
    }
    reiszeChange() {
        window.addEventListener("resize", ()=>{}
        )
    }
}
const log$6 = new Logger("eventsController");
class EventsController {
    constructor(e) {
        E(this, "staticmeshEvent");
        E(this, "rotationEvent");
        E(this, "resize", ()=>{
            this.room.sceneManager.cameraComponent.cameraFovChange(this.room.sceneManager.yuvInfo)
        }
        );
        E(this, "clickEvent", e=>{
            const {point: t, name: r, type: n, id: o} = e;
            log$6.debug("pointEvent", e),
            this.room.proxyEvents("pointTap", {
                point: t,
                meshName: r,
                type: n,
                id: o
            }),
            this.room.proxyEvents("_coreClick", e)
        }
        );
        E(this, "longPressEvent", e=>{
            this.room.proxyEvents("_corePress", e)
        }
        );
        E(this, "handleActionResponseTimeout", ({error: e, event: t})=>{
            this.room.proxyEvents("actionResponseTimeout", {
                error: e,
                event: t
            })
        }
        );
        E(this, "handleNetworkStateChange", e=>{
            const {state: t, count: r} = e;
            t == "reconnecting" ? this.room.proxyEvents("reconnecting", {
                count: r || 1
            }) : t === "reconnected" ? (this.room.networkController.rtcp.workers.reset(),
            this.room.proxyEvents("reconnected"),
            this.room.afterReconnected()) : t === "disconnected" && this.room.proxyEvents("disconnected")
        }
        );
        this.room = e,
        this.staticmeshEvent = new StaticMeshEvent(this.room.sceneManager),
        this.rotationEvent = new RotationEvent(e)
    }
    bindEvents() {
        window.addEventListener("orientationchange"in window ? "orientationchange" : "resize", this.resize),
        this.staticmeshEvent.on("pointTap", this.clickEvent),
        this.staticmeshEvent.on("longPress", this.longPressEvent),
        this.rotationEvent.init(),
        eventsManager.on("actionResponseTimeout", this.handleActionResponseTimeout),
        this.room.networkController.on("stateChanged", this.handleNetworkStateChange)
    }
    clearEvents() {
        window.removeEventListener("orientationchange"in window ? "orientationchange" : "resize", this.resize),
        this.staticmeshEvent.off("pointTap", this.clickEvent),
        this.staticmeshEvent.off("longPress", this.longPressEvent),
        eventsManager.off("actionResponseTimeout", this.handleActionResponseTimeout),
        this.room.networkController.off("stateChanged", this.handleNetworkStateChange),
        this.rotationEvent.clear()
    }
}
const log$5 = new Logger("panorama");
class Panorama {
    constructor(e) {
        E(this, "_actived", !1);
        E(this, "handleReceivePanorama", async(e,t)=>{
            log$5.warn("handle panorama", e.uuid, e.pos, e.finished);
            const r = {
                data: e.data,
                pose: {
                    position: e.pos
                }
            }
              , n = this.room.sceneManager;
            if (this.room.networkController.rtcp.workers.changePanoMode(!0),
            await n.materialComponent.changePanoImg(0, r),
            !!e.finished)
                if (await n.changePanoShaderForLowModel(0),
                this.room.isPano = !0,
                this._actived = !0,
                t)
                    this.room.sceneManager.cameraComponent.changeToFirstPersonView({
                        position: t.position,
                        rotation: t.angle
                    });
                else {
                    const {skinId: o, pathName: a} = this.room.currentState;
                    if (!o || !a)
                        return;
                    const s = await this.room.modelManager.findRoute(o, a)
                      , {camera: l} = getRandomItem(s.birthPointList) || {};
                    l && this.room.sceneManager.cameraComponent.changeToFirstPersonView(le(oe({}, l), {
                        rotation: l.angle
                    }))
                }
        }
        );
        this.room = e
    }
    get actived() {
        return this._actived
    }
    bindListener(e) {
        this.room.networkController.rtcp.workers.registerFunction("panorama", r=>{
            log$5.warn("receive panorama", r.uuid, r.pos),
            r.uuid && eventsManager.remove(r.uuid, Codes$1.Success, r, !0),
            this.room.isFirstDataUsed || (this.room.isFirstDataUsed = !0,
            this.handleReceivePanorama(r, this.room.options.camera).then(e))
        }
        )
    }
    access(e, t, r) {
        const {camera: n, player: o, attitude: a, areaName: s, pathName: l, tag: u} = e;
        return this.room.actionsHandler.requestPanorama({
            camera: n,
            player: o,
            attitude: a,
            areaName: s,
            pathName: l,
            tag: u
        }, t, r).then(c=>this.handleReceivePanorama(c, o))
    }
    exit(e) {
        const {camera: t, player: r, attitude: n, areaName: o, pathName: a} = e;
        return this.room.networkController.rtcp.workers.changePanoMode(!1),
        this.room.actionsHandler.changeRotationRenderType({
            renderType: RenderType.RotationVideo,
            player: r,
            camera: t,
            attitude: n,
            areaName: o,
            pathName: a
        }).then(()=>this.handleExitPanorama()).catch(s=>(this.room.networkController.rtcp.workers.changePanoMode(!0),
        Promise.reject(s)))
    }
    handleExitPanorama() {
        var e, t, r, n, o, a;
        this.room.isPano = !1,
        this._actived = !1,
        (n = (e = this.room.sceneManager) == null ? void 0 : e.cameraComponent) == null || n.forceChangeSavedCameraPose({
            position: (t = this.room._currentClickingState) == null ? void 0 : t.camera.position,
            rotation: (r = this.room._currentClickingState) == null ? void 0 : r.camera.angle
        }),
        this.room.sceneManager.changeVideoShaderForLowModel(),
        (a = (o = this.room.sceneManager) == null ? void 0 : o.cameraComponent) == null || a.changeToThirdPersonView()
    }
}
class PathManager {
    constructor() {
        E(this, "currentArea", "");
        E(this, "currentPathName", "");
        E(this, "currentAttitude", "");
        E(this, "speed", 0)
    }
    getSpeed(e) {
        const t = {
            guangchang: {
                [MotionType.Walk]: 17,
                [MotionType.Run]: 51
            },
            tower: {
                [MotionType.Walk]: 12.5,
                [MotionType.Run]: 25
            },
            zhiboting: {
                [MotionType.Walk]: 12.5,
                [MotionType.Run]: 25
            },
            youxiting: {
                [MotionType.Walk]: 12.5,
                [MotionType.Run]: 25
            },
            diqing: {
                [MotionType.Walk]: 12.5,
                [MotionType.Run]: 25
            }
        }
          , r = t[this.currentArea] || t.guangchang;
        return this.speed = r[e] * 30,
        this.speed
    }
}
const log$4 = new Logger("xverse-signal");
class Signal {
    constructor(e) {
        E(this, "_room");
        E(this, "signalHandleActived", !0);
        E(this, "isUpdatedYUV", !0);
        this._room = e
    }
    handleSignal(e) {
        var a, s, l;
        if (!this.signalHandleActived)
            return;
        const {signal: t, alreadyUpdateYUV: r} = e;
        if (this.handleActionResponses(t),
        this._room.handleSignalHook(t),
        !r) {
            const u = (a = t.newUserStates) == null ? void 0 : a.find(c=>c.userId === this._room.userId);
            if ((u == null ? void 0 : u.renderInfo) && ((s = this._room._userAvatar) == null ? void 0 : s.isMoving)) {
                log$4.debug("stream stoped, make avatar to stop");
                const {isMoving: c, isRotating: h} = u.renderInfo;
                this._room.avatarManager._updateAvatarMovingStatus({
                    id: u.userId,
                    isMoving: !!c,
                    isRotating: !!h
                })
            }
            return
        }
        this.isUpdatedYUV = r;
        const n = t;
        if (!t) {
            log$4.warn("metadata signal is empty");
            return
        }
        if (n.code === Codes$1.RepeatLogin) {
            this._room.handleRepetLogin();
            return
        }
        n.code !== void 0 && n.code !== Codes$1.Success && n.code !== Codes$1.ActionMaybeDelay && n.code !== Codes$1.DoActionBlocked && n.code !== Codes$1.GetOnVehicle && (log$4.error("signal errcode: ", n),
        this._room.emit("error", n));
        const o = (l = n.newUserStates) == null ? void 0 : l.find(u=>u.userId === this._room.userId);
        if (n.broadcastAction)
            try {
                const u = JSON.parse(n.broadcastAction.data);
                Broadcast.handlers.forEach(c=>c(u))
            } catch (u) {
                log$4.error(u)
            }
        if (n.newUserStates && n.newUserStates.length > 0 && this._room.avatarManager.handleAvatar(n),
        o != null && o.playerState) {
            this._room._currentClickingState = o.playerState;
            const {pathName: u, attitude: c, areaName: h, skinId: f} = o.playerState;
            if (u && (this._room.pathManager.currentPathName = u,
            this._room.updateCurrentState({
                pathName: u
            })),
            f && this.udpateSkinInfo(f),
            h && this._room.updateCurrentState({
                areaName: h
            }),
            c) {
                const d = this._room.skin.routeList.find(g=>g.areaName === this._room.currentState.areaName)
                  , _ = ((d == null ? void 0 : d.step) || 7.5) * 30;
                this._room.updateCurrentState({
                    speed: _,
                    attitude: c
                }),
                this._room.pathManager.currentAttitude = c,
                this._room._userAvatar && (this._room._userAvatar.motionType = c)
            }
            this._room.sceneManager.getCurrentShaderMode() !== ECurrentShaderMode.pano && !this._room.isPano && o.playerState.camera && this._room.camera.setCameraPose(o.playerState.camera)
        }
        if (o != null && o.renderInfo && this._room.camera.handleRenderInfo(o),
        n.actionType !== void 0) {
            const {actionType: u, code: c, echoMsg: h, traceId: f} = n;
            u === Actions.Echo && c === Codes$1.Success && this._room.networkController.rtcp.heartbeat.pong(h, f),
            c !== Codes$1.Success ? eventsManager.remove(f, c) : [Actions.GetReserveStatus, Actions.Broadcast, Actions.ChangeNickname, Actions.ConfirmEvent, Actions.ReserveSeat, Actions.Rotation, Actions.TurnTo, Actions.RotateTo, Actions.SetPlayerState, Actions.GetNeighborPoints, Actions.TurnToFace, Actions.AudienceChangeToVisitor, Actions.RemoveVisitor, Actions.GetUserWithAvatar].includes(u) && eventsManager.remove(f, c, n)
        }
    }
    handleActionResponses(e) {
        !(e != null && e.actionResponses) || e.actionResponses.length === 0 || e.actionResponses.forEach(t=>{
            if (t.actionType == null)
                return;
            const {pointType: r, extra: n, actionType: o, traceId: a, code: s, msg: l} = t;
            o === Actions.GetNeighborPoints ? eventsManager.remove(a, s, t.nps) : o === Actions.GetUserWithAvatar ? eventsManager.remove(a, s, t.userWithAvatarList) : eventsManager.remove(a, s, l),
            r === PointType.Path && o === Actions.Clicking && (this._room.moveToExtra = decodeURIComponent(n))
        }
        )
    }
    async udpateSkinInfo(e) {
        this._room.updateCurrentState({
            skinId: e
        });
        const t = await this._room.skinList.find(r=>r.id === e);
        t && this._room.updateCurrentState({
            skin: t
        })
    }
}
const BREATH_POINT_TYPE = "debugBreathPoint"
  , TAP_BREATH_POINT_TYPE = "debugTapBreathPoint"
  , DEFAULT_SEARCH_RANGE = 1e3;
class Debug {
    constructor(e) {
        E(this, "isShowNearbyBreathPoints", !1);
        E(this, "isShowTapBreathPoints", !1);
        E(this, "isSceneShading", !0);
        E(this, "searchRange", DEFAULT_SEARCH_RANGE);
        E(this, "nearbyBreathPointListening", !1);
        E(this, "tapBreathPointListening", !1);
        E(this, "dumpStreamTimer", 0);
        this.room = e
    }
    toggleStats() {
        return this.room.stats.isShow ? this.room.stats.hide() : this.room.stats.show()
    }
    toggleNearbyBreathPoint(e=DEFAULT_SEARCH_RANGE) {
        this.searchRange = e,
        this.isShowNearbyBreathPoints = !this.isShowNearbyBreathPoints,
        this.isShowNearbyBreathPoints ? (this.getPointsAndRender(),
        this.setupNearbyBreathPointListener()) : this.room.breathPointManager.clearBreathPoints(BREATH_POINT_TYPE)
    }
    toggleTapBreathPoint() {
        this.isShowTapBreathPoints = !this.isShowTapBreathPoints,
        this.isShowTapBreathPoints ? this.setupTapPointListener() : this.room.breathPointManager.clearBreathPoints(TAP_BREATH_POINT_TYPE)
    }
    dumpStream(e, t=10 * 1e3) {
        if (this.dumpStreamTimer)
            throw new Error("dumpStream running");
        this.room.networkController.rtcp.workers.saveframe = !0,
        this.dumpStreamTimer = window.setTimeout(()=>{
            this.room.networkController.rtcp.workers.SaveMediaStream = !0,
            this.dumpStreamTimer = 0,
            e && e()
        }
        , t)
    }
    toggleSceneshading() {
        this.isSceneShading = !this.isSceneShading,
        this.isSceneShading ? this.room.sceneManager.changeVideoShaderForLowModel() : this.room.sceneManager.changeDefaultShaderForLowModel()
    }
    setupTapPointListener() {
        this.tapBreathPointListening || (this.tapBreathPointListening = !0,
        this.room.on("_coreClick", ({point: e})=>{
            this.isShowTapBreathPoints && this.renderTapBreathPoint({
                id: "tapToint",
                position: e
            })
        }
        ))
    }
    renderTapBreathPoint({position: e, id: t}) {
        let r;
        if (r = this.room.breathPointManager.breathPoints.get(t)) {
            r.position = e;
            return
        }
        this.room.breathPointManager.addBreathPoint({
            id: t,
            position: e,
            type: TAP_BREATH_POINT_TYPE,
            size: .8,
            forceLeaveGround: !0,
            billboardMode: !0,
            rotation: Math.abs(e.z) < 20 ? {
                pitch: 90,
                yaw: 0,
                roll: 0
            } : {
                pitch: 0,
                yaw: 270,
                roll: 0
            }
        })
    }
    setupNearbyBreathPointListener() {
        var e;
        this.nearbyBreathPointListening || (this.nearbyBreathPointListening = !0,
        (e = this.room._userAvatar) == null || e.on("stopMoving", ()=>{
            this.isShowNearbyBreathPoints && this.getPointsAndRender()
        }
        ))
    }
    async getPointsAndRender() {
        var r, n;
        const e = this.searchRange
          , t = ((r = this.room._userAvatar) == null ? void 0 : r.position) && await this.getNeighborPoints({
            point: (n = this.room._userAvatar) == null ? void 0 : n.position,
            containSelf: !0,
            searchRange: e
        }) || [];
        this.room.breathPointManager.breathPoints.forEach(o=>{
            !!t.find(s=>JSON.stringify(s) === o._id) || this.room.breathPointManager.clearBreathPoints(o._id)
        }
        ),
        t.forEach(o=>{
            const a = JSON.stringify(o);
            this.room.breathPointManager.breathPoints.get(a) || this.room.breathPointManager.addBreathPoint({
                id: a,
                position: o,
                type: BREATH_POINT_TYPE,
                rotation: {
                    pitch: 90,
                    yaw: 0,
                    roll: 0
                },
                forceLeaveGround: !0
            })
        }
        )
    }
    getNeighborPoints(e) {
        const {point: t, containSelf: r=!1, searchRange: n=500} = e;
        return this.room.actionsHandler.getNeighborPoints({
            point: t,
            containSelf: r,
            searchRange: n
        })
    }
}
const log$3 = new Logger("xverse-room");
class XverseRoom$1 extends EventEmitter {
    constructor(e) {
        super();
        E(this, "disableAutoTurn", !1);
        E(this, "options");
        E(this, "_currentNetworkOptions");
        E(this, "lastSkinId");
        E(this, "debug");
        E(this, "isFirstDataUsed", !1);
        E(this, "userId", null);
        E(this, "pathManager", new PathManager);
        E(this, "networkController");
        E(this, "_startTime", Date.now());
        E(this, "canvas");
        E(this, "modelManager");
        E(this, "eventsController");
        E(this, "panorama");
        E(this, "engineProxy");
        E(this, "_id");
        E(this, "skinList", []);
        E(this, "isHost", !1);
        E(this, "avatarManager", new XverseAvatarManager(this));
        E(this, "effectManager", new XverseEffectManager(this));
        E(this, "sceneManager");
        E(this, "scene");
        E(this, "breathPointManager");
        E(this, "_currentState");
        E(this, "joined", !1);
        E(this, "disableRotate", !1);
        E(this, "isPano", !1);
        E(this, "movingByClick", !0);
        E(this, "camera", new Camera(this));
        E(this, "stats", new Stats(this));
        E(this, "isUpdatedRawYUVData", !1);
        E(this, "actionsHandler", new ActionsHandler(this));
        E(this, "_currentClickingState", null);
        E(this, "signal", new Signal(this));
        E(this, "firstFrameTimestamp");
        E(this, "receiveRtcData", async()=>{
            log$3.info("Invoke receiveRtcData");
            let e = !1
              , t = !1
              , r = !1
              , n = !1;
            return this.viewMode === "serverless" ? (log$3.warn("set view mode to serverless"),
            this.setViewMode("observer").then(()=>this, ()=>this)) : new Promise(o=>{
                const a = this.networkController.rtcp.workers;
                a.registerFunction("signal", s=>{
                    this.signal.handleSignal(s)
                }
                ),
                a.registerFunction("stream", s=>{
                    var l;
                    if (this.emit("streamTimestamp", {
                        timestamp: Date.now()
                    }),
                    t || (t = !0,
                    log$3.info("Invoke stream event")),
                    s.stream) {
                        r || (r = !0,
                        log$3.info("Invoke updateRawYUVData")),
                        this.isUpdatedRawYUVData = !1;
                        const u = (l = this._currentState.skin) == null ? void 0 : l.fov;
                        this.sceneManager.materialComponent.updateRawYUVData(s.stream, s.width, s.height, u),
                        this.isUpdatedRawYUVData = !0
                    }
                    e || (log$3.info("Invoke isAfterRenderRegistered"),
                    e = !0,
                    this.scene.registerAfterRender(()=>{
                        this.engineProxy.frameRenderNumber >= 2 && (n || (n = !0,
                        log$3.info("Invoke registerAfterRender")),
                        this.isFirstDataUsed || (log$3.info("Invoke isStreamAvailable"),
                        this.isFirstDataUsed = !0,
                        this.firstFrameTimestamp = Date.now(),
                        o(this),
                        this.afterJoinRoom()))
                    }
                    ))
                }
                ),
                this.panorama.bindListener(()=>{
                    o(this),
                    this.afterJoinRoom()
                }
                ),
                a.registerFunction("reconnectedFrame", ()=>{}
                ),
                log$3.info("Invoke decoderWorker.postMessage"),
                a.decoderWorker.postMessage({
                    t: 5
                })
            }
            )
        }
        );
        E(this, "moveToExtra", "");
        this.options = e,
        this.options.wsServerUrl || (this.options.wsServerUrl = SERVER_URLS.DEV),
        this.modelManager = ModelManager.getInstance(e.appId, e.releaseId),
        this.updateReporter();
        const n = e
          , {canvas: t} = n
          , r = Oe(n, ["canvas"]);
        log$3.infoAndReportMeasurement({
            metric: "startJoinRoomAt",
            startTime: Date.now(),
            group: "joinRoom",
            extra: r,
            value: 0
        })
    }
    get currentNetworkOptions() {
        return this._currentNetworkOptions
    }
    get viewMode() {
        var e;
        return ((e = this._currentState) == null ? void 0 : e.viewMode) || "full"
    }
    get id() {
        return this._id
    }
    get skinId() {
        return this._currentState.skinId
    }
    get skin() {
        return this._currentState.skin
    }
    get sessionId() {
        return this.currentNetworkOptions.sessionId
    }
    get pictureQualityLevel() {
        return this.currentState.pictureQualityLevel
    }
    get avatars() {
        return Array.from(this.avatarManager.avatars.values())
    }
    get currentState() {
        var e;
        return le(oe({}, this._currentState), {
            state: (e = this.networkController) == null ? void 0 : e._state
        })
    }
    get _userAvatar() {
        return this.avatars.find(e=>e.userId === this.userId)
    }
    get tvs() {
        return this.engineProxy._tvs
    }
    get tv() {
        return this.tvs[0]
    }
    get currentClickingState() {
        return this._currentClickingState
    }
    afterJoinRoomHook() {}
    beforeJoinRoomResolveHook() {}
    afterReconnectedHook() {}
    handleSignalHook(e) {}
    skinChangedHook() {}
    async beforeStartGameHook(e) {}
    loadAssetsHook() {}
    afterUserAvatarLoadedHook() {}
    audienceViewModeHook() {}
    setViewModeToObserver() {}
    handleVehicleHook(e) {}
    updateReporter() {
        const {avatarId: e, skinId: t, userId: r, roomId: n, role: o, appId: a, wsServerUrl: s} = this.options;
        reporter.updateHeader({
            userId: r
        }),
        reporter.updateBody({
            roomId: n,
            role: o,
            skinId: t,
            avatarId: e,
            appId: a,
            wsServerUrl: s
        })
    }
    async initRoom() {
        const {timeout: e=DEFAULT_JOINROOM_TIMEOUT} = this.options;
        return isSupported() ? this._initRoom()._timeout(e, new TimeoutError("initRoom timeout")) : Promise.reject(new UnsupportedError)
    }
    async _initRoom() {
        const e = this.validateOptions(this.options);
        if (e)
            return log$3.error("initRoom param error", e),
            Promise.reject(e);
        const {canvas: t, avatarId: r, skinId: n, userId: o, wsServerUrl: a, role: s, token: l, pageSession: u, rotationRenderType: c, isAllSync: h=!1, appId: f, camera: d, player: _, avatarComponents: g, nickname: m, avatarScale: v, firends: y=[], syncByEvent: b=!1, areaName: T, attitude: C=MotionType.Walk, pathName: A, viewMode: S="full", person: P, roomId: R, roomTypeId: M, hasAvatar: x=!1, syncToOthers: I=!1, prioritySync: w=!1, removeWhenDisconnected: O=!0, extra: D} = this.options;
        this.setCurrentNetworkOptions({
            avatarId: r,
            skinId: n,
            roomId: R,
            userId: o,
            wsServerUrl: a,
            role: s,
            token: l,
            pageSession: u,
            rotationRenderType: c,
            isAllSync: h,
            appId: f,
            camera: d,
            player: _,
            avatarComponents: g,
            nickname: m,
            avatarScale: v,
            firends: y,
            syncByEvent: b,
            areaName: T,
            attitude: C,
            pathName: A,
            person: P,
            roomTypeId: M,
            hasAvatar: x,
            syncToOthers: I,
            prioritySync: w,
            extra: D,
            removeWhenDisconnected: O
        }),
        this.userId = o,
        this.canvas = t,
        T && (this.pathManager.currentArea = T),
        this.networkController = new NetworkController(this),
        this.setCurrentState({
            areaName: T,
            pathName: A,
            attitude: C,
            speed: 0,
            viewMode: S,
            state: this.networkController._state,
            skinId: n
        });
        try {
            await Promise.all([this.initNetwork(), this.initConfig(), this.initWasm()]),
            log$3.info("network config wasm all ready, start to create game");
            const F = await this.requestCreateRoom({
                skinId: n
            })
              , V = F.routeList.find(L=>L.areaName === T)
              , N = ((V == null ? void 0 : V.step) || 7.5) * 30;
            this.updateCurrentState({
                skin: F,
                skinId: F.id,
                versionId: F.versionId,
                speed: N
            }),
            await this.initEngine(F)
        } catch (F) {
            return Promise.reject(F)
        }
        return this.beforeJoinRoomResolve(),
        this.receiveRtcData()
    }
    beforeJoinRoomResolve() {
        this.setupStats(),
        this.eventsController = new EventsController(this),
        this.eventsController.bindEvents(),
        this.panorama = new Panorama(this),
        this.beforeJoinRoomResolveHook()
    }
    afterJoinRoom() {
        this.joined = !0,
        this.viewMode === "observer" && this.setViewModeToObserver(),
        log$3.infoAndReportMeasurement({
            tag: this.viewMode,
            value: this.firstFrameTimestamp - this._startTime,
            startTime: Date.now(),
            metric: "joinRoom"
        }),
        this.camera.initialFov = this.sceneManager.cameraComponent.getCameraFov(),
        this.stats.on("stats", ({stats: e})=>{
            reporter.report("stats", oe({}, e))
        }
        ),
        this.debug = new Debug(this),
        this.afterJoinRoomHook()
    }
    afterReconnected() {
        this.avatarManager.clearOtherUsers(),
        this.afterReconnectedHook()
    }
    leave() {
        var e, t;
        return log$3.info("Invoke room.leave"),
        (e = this.eventsController) == null || e.clearEvents(),
        (t = this.networkController) == null || t.quit(),
        this
    }
    validateOptions(e) {
        const {canvas: t, avatarId: r, skinId: n, userId: o, role: a, roomId: s, token: l, appId: u, avatarComponents: c} = e || {}
          , h = [];
        return t instanceof HTMLCanvasElement || h.push(new ParamError("`canvas` must be instanceof of HTMLCanvasElement")),
        (!o || typeof o != "string") && h.push(new ParamError("`userId` must be string")),
        (!l || typeof l != "string") && h.push(new ParamError("`token` must be string")),
        (!u || typeof u != "string") && h.push(new ParamError("`appId` must be string")),
        a == "audience" || (!r || !n) && h.push(new ParamError("`avatarId` and `skinId` is required when create room")),
        h[0]
    }
    async initNetwork() {
        if (this.viewMode === "serverless")
            return Promise.resolve();
        const e = Date.now();
        try {
            await this.networkController.connect()._timeout(8e3, new InitNetworkTimeoutError),
            log$3.infoAndReportMeasurement({
                metric: "networkInitAt",
                startTime: this._startTime,
                group: "joinRoom"
            }),
            log$3.infoAndReportMeasurement({
                metric: "networkInitCost",
                startTime: e,
                group: "joinRoom"
            })
        } catch (t) {
            throw log$3.infoAndReportMeasurement({
                metric: "networkInitAt",
                startTime: e,
                group: "joinRoom",
                error: t
            }),
            t
        }
    }
    async initConfig() {
        const e = Date.now();
        try {
            await this.modelManager.getApplicationConfig()._timeout(8e3, new InitConfigTimeoutError),
            log$3.infoAndReportMeasurement({
                metric: "configInitAt",
                startTime: this._startTime,
                group: "joinRoom"
            }),
            log$3.infoAndReportMeasurement({
                metric: "configInitCost",
                startTime: e,
                group: "joinRoom"
            })
        } catch (t) {
            throw log$3.infoAndReportMeasurement({
                metric: "configInitAt",
                startTime: e,
                group: "joinRoom",
                error: t
            }),
            t
        }
    }
    async initEngine(e) {
        const t = Date.now();
        try {
            this.engineProxy = new EngineProxy(this),
            await this.engineProxy.initEngine(e),
            log$3.infoAndReportMeasurement({
                metric: "webglInitAt",
                startTime: this._startTime,
                group: "joinRoom"
            }),
            log$3.infoAndReportMeasurement({
                metric: "webglInitCost",
                startTime: t,
                group: "joinRoom"
            });
            return
        } catch (r) {
            let n = r;
            return r.code !== Codes$1.InitEngineTimeout && (n = new InitEngineError),
            log$3.error(r),
            log$3.infoAndReportMeasurement({
                metric: "webglInitAt",
                startTime: t,
                group: "joinRoom",
                error: n
            }),
            Promise.reject(n)
        }
    }
    async initWasm() {
        if (this.viewMode === "serverless")
            return Promise.resolve();
        const e = Date.now();
        try {
            await this.networkController.rtcp.workers.init(this.options.resolution)._timeout(8e3, new InitDecoderTimeoutError),
            this.networkController.rtcp.workers.registerFunction("error", t=>{
                log$3.error("decode error", t);
                const {code: r, message: n} = t;
                this.emit("error", {
                    code: r,
                    msg: n
                })
            }
            ),
            log$3.infoAndReportMeasurement({
                metric: "wasmInitAt",
                group: "joinRoom",
                startTime: this._startTime
            }),
            log$3.infoAndReportMeasurement({
                metric: "wasmInitCost",
                group: "joinRoom",
                startTime: e
            }),
            eventsManager.on("traceId", t=>{
                this.networkController.rtcp.workers.onTraceId(t)
            }
            )
        } catch (t) {
            throw log$3.infoAndReportMeasurement({
                metric: "wasmInitAt",
                group: "joinRoom",
                startTime: e,
                error: t
            }),
            t
        }
    }
    async requestCreateRoom({skinId: e}) {
        let t;
        if (e) {
            t = await this.getSkin(e);
            const r = await this.modelManager.findRoute(e, this.options.pathName);
            this.updateCurrentNetworkOptions({
                areaName: r.areaName,
                attitude: r.attitude,
                versionId: t.versionId
            });
            const {camera: n, player: o} = getRandomItem(r.birthPointList) || this.options;
            this.options.camera || this.updateCurrentNetworkOptions({
                camera: n
            }),
            this.options.player || this.updateCurrentNetworkOptions({
                player: o
            })
        }
        if (this.viewMode === "serverless")
            return t;
        try {
            await this.beforeStartGameHook(this.options);
            const {room_id: r, data: n, session_id: o} = await this.networkController.startGame();
            this._id = r;
            const a = JSON.parse(n);
            this.isHost = a.IsHost,
            e = a.SkinID || e;
            const s = await this.getSkin(e);
            return this.updateCurrentNetworkOptions({
                roomId: r,
                sessionId: o
            }),
            reporter.updateBody({
                roomId: r,
                skinId: e,
                serverSession: o
            }),
            s
        } catch (r) {
            throw log$3.error("Request create room error", r),
            r
        }
    }
    pause() {
        return this.engineProxy.pause()
    }
    resume() {
        return this.engineProxy.resume()
    }
    reconnect() {
        this.networkController.reconnect()
    }
    async setViewMode(e) {}
    handleRepetLogin() {
        log$3.warn("receive " + Codes$1.RepeatLogin + " for repeat login"),
        this.emit("repeatLogin"),
        reporter.disable(),
        this.networkController.quit()
    }
    setPictureQualityLevel(e) {
        const t = {
            high: EImageQuality.high,
            low: EImageQuality.low,
            average: EImageQuality.mid
        };
        return this.updateCurrentState({
            pictureQualityLevel: e
        }),
        this.sceneManager.setImageQuality(t[e])
    }
    async getSkin(e) {
        let t = null;
        if (t = (this.skinList = await this.modelManager.getSkinsList()).find(n=>n.id === e || n.id === e),
        t)
            return t;
        {
            const n = `skin is invalid: skinId: ${e}`;
            return Promise.reject(new ParamError(n))
        }
    }
    setupStats() {
        this.stats.assign({
            roomId: this.id,
            userId: this.userId
        }),
        setInterval(this.engineProxy.updateStats, 1e3)
    }
    proxyEvents(e, t) {
        this.emit(e, t)
    }
    setCurrentNetworkOptions(e) {
        this._currentNetworkOptions = e
    }
    updateCurrentNetworkOptions(e) {
        Object.assign(this._currentNetworkOptions, e),
        Object.assign(this.options, e)
    }
    setCurrentState(e) {
        this._currentState = e
    }
    updateCurrentState(e) {
        e.skinId && (this.lastSkinId = this.currentState.skinId,
        this.updateCurrentNetworkOptions({
            skinId: e.skinId
        })),
        e.versionId && this.updateCurrentNetworkOptions({
            versionId: e.versionId
        }),
        Object.assign(this._currentState, e)
    }
}
var RenderType = (i=>(i[i.PathVideo = 0] = "PathVideo",
i[i.RotationVideo = 1] = "RotationVideo",
i[i.RotationImage = 2] = "RotationImage",
i[i.PanoramaImage = 3] = "PanoramaImage",
i[i.CGVideo = 4] = "CGVideo",
i[i.ClientRotationPano = 5] = "ClientRotationPano",
i[i.CloudRotationPano = 6] = "CloudRotationPano",
i))(RenderType || {})
  , Person = (i=>(i[i.Third = 0] = "Third",
i[i.First = 1] = "First",
i))(Person || {})
  , LandingType = (i=>(i[i.Stay = 0] = "Stay",
i[i.InitPoint = 1] = "InitPoint",
i[i.NewPoint = 2] = "NewPoint",
i))(LandingType || {})
  , ClickType = (i=>(i[i.Screen = 0] = "Screen",
i[i.ThreeDimension = 1] = "ThreeDimension",
i[i.ThreeDimensionQuick = 2] = "ThreeDimensionQuick",
i[i.IgnoreView = 3] = "IgnoreView",
i))(ClickType || {})
  , ChangeMode = (i=>(i[i.Preview = 0] = "Preview",
i[i.Confirm = 1] = "Confirm",
i[i.Cancel = 2] = "Cancel",
i))(ChangeMode || {})
  , PointType = (i=>(i[i.Path = 0] = "Path",
i[i.Item = 1] = "Item",
i[i.Closeup = 2] = "Closeup",
i[i.NoValidMatched = 3] = "NoValidMatched",
i))(PointType || {});
const log$2 = new Logger("xverse-avatar-tools")
  , isSuit = i=>i === "suit"
  , avatarComponentsParser = async(i=null,e,t=[])=>new Promise(async(r,n)=>{
    var u, c;
    if (e.find(h=>isSuit(h.type))) {
        const h = (c = (u = i == null ? void 0 : i.components) == null ? void 0 : u.find(f=>isSuit(f.type))) == null ? void 0 : c.suitComb;
        e = e.filter(f=>(h == null ? void 0 : h.indexOf(f.type)) === -1)
    }
    const a = e.filter(h=>!t.some(f=>f.id === h.id));
    a.length === 0 && r([]);
    const s = [];
    a.forEach(async h=>{
        var _;
        let f = (_ = i == null ? void 0 : i.components) == null ? void 0 : _.find(g=>g.type === h.type);
        if (!f) {
            const g = `changeComponents, no such component with type: ${h.type}`;
            log$2.error(g),
            n(g)
        }
        f = JSON.parse(JSON.stringify(f));
        let d = f == null ? void 0 : f.units.find(g=>g.id === h.id);
        d || (log$2.warn(`changeComponents, no unit with type: ${h.type}, id: ${h.id}`),
        d = f == null ? void 0 : f.units.find(g=>g.isDefault),
        !d && log$2.warn(`changeComponents, no default unit with type: ${h.type}`)),
        d && s.push({
            id: d.id,
            url: d.url,
            suitComb: (f == null ? void 0 : f.suitComb) || [],
            type: h.type
        })
    }
    );
    const l = [];
    Promise.all(l).then(h=>{
        s.forEach((f,d)=>{
            var _, g;
            if (!isSuit(f.type)) {
                const m = ((g = (_ = i == null ? void 0 : i.components) == null ? void 0 : _.find(v=>isSuit(v.type))) == null ? void 0 : g.suitComb) || [];
                m.length > 0 && (m == null ? void 0 : m.indexOf(f.type)) !== -1 && (f.suitComb = ["suit"])
            }
            f.url = h[d]
        }
        ),
        r(s)
    }
    ).catch(h=>{
        n(h)
    }
    )
}
)
  , avatarComponentsModify = (i,e)=>new Promise((t,r)=>{
    var l;
    let n = [];
    const o = []
      , a = [];
    let s = e.some(u=>isSuit(u.type));
    if ((l = i == null ? void 0 : i.components) == null || l.forEach(u=>{
        var f;
        const c = e.find(d=>d.type === u.type)
          , h = c && ((f = i == null ? void 0 : i.components) == null ? void 0 : f.find(d=>d.type === c.type && d.units.some(_=>_.id === c.id))) !== void 0;
        if (c)
            if (h)
                n.push(c);
            else {
                const d = u.units.find(_=>_.isDefault) || u.units[0];
                d ? n.push({
                    type: u.type,
                    id: d.id
                }) : o.push(`component with type: ${u.type} without default and available unit`)
            }
        else if (isSuit(u.type)) {
            const d = u.units.find(_=>_.isDefault);
            d && n.push({
                type: u.type,
                id: d.id
            })
        } else {
            const d = u.units.find(_=>_.isDefault) || u.units[0];
            d ? n.push({
                type: u.type,
                id: d.id
            }) : o.push(`component with type: ${u.type} without default and available unit`)
        }
    }
    ),
    s = n.some(u=>isSuit(u.type)),
    s) {
        const u = i == null ? void 0 : i.components.find(c=>isSuit(c.type));
        n = n.filter(c=>(u == null ? void 0 : u.suitComb.indexOf(c.type)) === -1)
    }
    o.length > 0 && (log$2.error(o.join(", ")),
    r(o.join(", "))),
    a.length > 0 && log$2.warn(a.join(", ")),
    t(n)
}
)
  , positionPrecisionProtect = i=>{
    const {x: e, y: t, z: r} = i;
    return {
        x: +e.toFixed(2),
        y: +t.toFixed(2),
        z: +r.toFixed(2)
    }
}
  , rotationPrecisionProtect = i=>{
    const {pitch: e, yaw: t, roll: r} = i;
    return {
        pitch: +e.toFixed(2),
        yaw: +t.toFixed(2),
        roll: +r.toFixed(2)
    }
}
  , avatarComponentsValidate = (i,e)=>{
    const t = []
      , r = {};
    return Array.isArray(i) ? (i.forEach(n=>{
        r[n.type] ? r[n.type].num++ : r[n.type] = {
            num: 1,
            isSuit: isSuit(n.type)
        }
    }
    ),
    Object.keys(r).forEach(n=>{
        if (r[n].num > 1 && t.push(new ParamError(`avatarComponent with type: ${n} repeated`)),
        r[n].isSuit) {
            const o = e.components.find(a=>isSuit(a.type));
            o == null || o.suitComb.forEach(a=>{
                Object.keys(r).indexOf(a) > -1 && t.push(new ParamError(`suit already contains: ${a},  ${a} repeated`))
            }
            )
        }
    }
    ),
    t[0]) : (t.push(new ParamError("avatarComponents must be array")),
    t[0])
}
  , safeParseComponents = i=>{
    let e = [];
    try {
        e = JSON.parse(i || "[]")
    } catch {
        e = [],
        log$2.error(`avatarComponents parse error: ${i}`)
    }
    return e
}
;
var QueueType = (i=>(i.Move = "Move",
i.Rotate = "Rotate",
i))(QueueType || {});
class Queue {
    constructor() {
        E(this, "queue", []);
        E(this, "currentAction")
    }
    async append(e) {
        var t, r;
        this.queue.length === 0 || ((t = this.currentAction) == null ? void 0 : t.type) === e.type && this.queue.length === 1 ? (this.queue = [],
        this.queue.push(e),
        await this.go()) : (((r = this.queue[this.queue.length - 1]) == null ? void 0 : r.type) === e.type && this.queue.pop(),
        this.queue.push(e))
    }
    async go() {
        if (this.queue.length !== 0) {
            const e = this.queue[0];
            this.currentAction = e,
            await e.action(),
            this.currentAction = void 0,
            this.queue.splice(0, 1),
            await this.go()
        }
    }
    async reject() {
        this.queue = []
    }
}
const log$1 = new Logger("xverse-avatar");
class XverseAvatar extends EventEmitter {
    constructor({userId: e, isHost: t, room: r, avatarId: n, isSelf: o, group: a=AvatarGroup.Npc}) {
        super();
        E(this, "xAvatar");
        E(this, "_isHost", !1);
        E(this, "_room");
        E(this, "_withModel", !1);
        E(this, "_userId");
        E(this, "group", AvatarGroup.User);
        E(this, "state", "idle");
        E(this, "isLoading", !0);
        E(this, "_isMoving", !1);
        E(this, "_isRotating", !1);
        E(this, "_failed", !1);
        E(this, "disconnected", !1);
        E(this, "_avatarId");
        E(this, "prioritySync", !1);
        E(this, "priority", EAvatarRelationRank.Stranger);
        E(this, "_avatarModel");
        E(this, "_motionType", MotionType.Walk);
        E(this, "isSelf", !1);
        E(this, "_lastAnimTraceId", "");
        E(this, "statusSyncQueue", new Queue);
        E(this, "extraInfo", {});
        E(this, "setPosition", e=>{
            var t;
            !this._room.signal.isUpdatedYUV || (t = this.xAvatar) == null || t.setPosition(positionPrecisionProtect(e))
        }
        );
        E(this, "setRotation", e=>{
            var t;
            !this._room.signal.isUpdatedYUV || (t = this.xAvatar) == null || t.setRotation(rotationPrecisionProtect(e))
        }
        );
        E(this, "stopAnimation", ()=>{
            var e, t;
            (t = (e = this.xAvatar) == null ? void 0 : e.controller) == null || t.stopAnimation()
        }
        );
        E(this, "_playAnimation", async(e,t=!0,r=!1)=>{
            var o;
            if (!this._room.signal.isUpdatedYUV)
                return;
            if (this.state !== "idle" && !r)
                return log$1.debug("_playAnimation", "state is not idle"),
                Promise.resolve("_playAnimation, state is not idle");
            const n = Date.now();
            try {
                if (!((o = this.xAvatar) != null && o.controller))
                    return Promise.reject(new InternalError(`[avatar: ${this.userId}] Play animation failed: ${e}, no controller`));
                this.isSelf && setTimeout(()=>{
                    log$1.infoAndReportMeasurement({
                        tag: e,
                        startTime: n,
                        value: 0,
                        metric: "playAnimationStart"
                    })
                }
                );
                const a = uuid$1();
                this._lastAnimTraceId = a,
                await this.xAvatar.controller.playAnimation(e, t),
                a === this._lastAnimTraceId && !this.isMoving && !t && e !== "Idle" && this.xAvatar.controller.playAnimation("Idle", t).catch(s=>{
                    log$1.error(`[avatar: ${this.userId}] Play animation failed [force idle]`, s)
                }
                ),
                this.isSelf && log$1.infoAndReportMeasurement({
                    tag: e,
                    startTime: n,
                    extra: {
                        loop: t
                    },
                    metric: "playAnimationEnd"
                })
            } catch (a) {
                return log$1.error(`[avatar: ${this.userId}] Play animation failed: ${e}`, a),
                this.isSelf && log$1.infoAndReportMeasurement({
                    tag: e,
                    startTime: n,
                    metric: "playAnimationEnd",
                    error: a,
                    extra: {
                        loop: t
                    }
                }),
                Promise.reject(a)
            }
        }
        );
        E(this, "changeComponents", async e=>{
            const {mode: t, endAnimation: r=""} = e || {}
              , n = JSON.parse(JSON.stringify(e.avatarComponents));
            let o = avatarComponentsValidate(n, this._avatarModel);
            return !ChangeComponentsMode[t] && !o && (o = new ParamError(`changeComponents failed, mode: ${t} is invalid`)),
            o ? (log$1.error(o),
            Promise.reject(o)) : this._changeComponents({
                avatarComponents: n,
                mode: t,
                endAnimation: r
            }).then(()=>{
                this.isSelf && t !== ChangeComponentsMode.Preview && this.avatarComponentsSync(this.avatarComponents)
            }
            )
        }
        );
        E(this, "_changeComponents", async e=>{
            var o;
            const {avatarComponents: t=[], mode: r} = e || {}
              , n = Date.now();
            try {
                if (!this.xAvatar)
                    return Promise.reject(new InternalError("changeComponents failed, without instance: xAvatar"));
                const a = await avatarComponentsModify(this._avatarModel, t)
                  , s = []
                  , l = await avatarComponentsParser(this._avatarModel, a, this.avatarComponents);
                if (l.length === 0)
                    return this.avatarComponents;
                await this.beforeChangeComponentsHook(e);
                for (const u of l) {
                    const {id: c, type: h, url: f, suitComb: d} = u;
                    s.push((o = this.xAvatar) == null ? void 0 : o.addComponent(c, h, f, d))
                }
                return await Promise.all(s),
                this.emit("componentsChanged", {
                    components: this.avatarComponents,
                    mode: r
                }),
                this.isSelf && log$1.infoAndReportMeasurement({
                    tag: "changeComponents",
                    startTime: n,
                    metric: "changeComponents",
                    extra: {
                        inputComponents: t,
                        finalComponents: this.avatarComponents,
                        mode: ChangeComponentsMode[r]
                    }
                }),
                this.avatarComponents
            } catch (a) {
                return this.isSelf && log$1.infoAndReportMeasurement({
                    tag: "changeComponents",
                    startTime: n,
                    metric: "changeComponents",
                    error: a,
                    extra: {
                        inputComponents: t,
                        finalComponents: this.avatarComponents,
                        mode: ChangeComponentsMode[r]
                    }
                }),
                Promise.reject(a)
            }
        }
        );
        E(this, "avatarComponentsSync", e=>{
            e = e.map(t=>({
                type: t.type,
                id: t.id
            })),
            this._room.actionsHandler.avatarComponentsSync(e)
        }
        );
        E(this, "hide", ()=>{
            var e;
            if ((e = this.xAvatar) != null && e.hide())
                return Promise.resolve(`avatar: ${this.userId} hide success`);
            {
                const t = `avatar: ${this.userId} hide failed ${!this.xAvatar && "without instance: xAvatar"}`;
                return log$1.warn(t),
                Promise.reject(t)
            }
        }
        );
        E(this, "show", ()=>{
            var e;
            if ((e = this.xAvatar) != null && e.show())
                return Promise.resolve(`avatar: ${this.userId} show success`);
            {
                const t = `avatar: ${this.userId} show failed ${!this.xAvatar && "without instance: xAvatar"}`;
                return log$1.warn(t),
                Promise.reject(t)
            }
        }
        );
        E(this, "sayTimer");
        this._userId = e,
        this._room = r,
        this.isSelf = o || !1,
        this._withModel = !!n,
        this._isHost = t || !1,
        this._avatarId = n,
        this.group = a,
        this._room.modelManager.getAvatarModelList().then(s=>{
            const l = s.find(u=>u.id === n);
            l && (this._avatarModel = l)
        }
        )
    }
    get avatarId() {
        return this._avatarId
    }
    get isRender() {
        var e;
        return !!((e = this.xAvatar) != null && e.isRender)
    }
    get isHidden() {
        var e;
        return !!((e = this.xAvatar) != null && e.isHide)
    }
    get motionType() {
        return this._motionType
    }
    set motionType(e) {
        this._motionType = e
    }
    get nickname() {
        var e;
        return (e = this.xAvatar) == null ? void 0 : e.nickName
    }
    get words() {
        var e;
        return (e = this.xAvatar) == null ? void 0 : e.words
    }
    get isHost() {
        return this._isHost
    }
    get failed() {
        return this._failed
    }
    get scale() {
        var e;
        return (e = this.xAvatar) == null ? void 0 : e.scale
    }
    get animations() {
        var e;
        return !this.xAvatar || !this.xAvatar.controller ? [] : ((e = this.xAvatar) == null ? void 0 : e.getAvaliableAnimations()) || []
    }
    get position() {
        var e;
        return (e = this.xAvatar) == null ? void 0 : e.position
    }
    get rotation() {
        var e;
        return (e = this.xAvatar) == null ? void 0 : e.rotation
    }
    get pose() {
        return {
            position: this.position,
            angle: this.rotation
        }
    }
    get id() {
        return this.userId
    }
    get isMoving() {
        return this._isMoving
    }
    set isMoving(e) {
        this._isMoving = e,
        this.state = e ? "moving" : "idle"
    }
    get isRotating() {
        return this._isRotating
    }
    set isRotating(e) {
        this._isRotating = e,
        this.state = e ? "rotating" : "idle"
    }
    get withModel() {
        return this._withModel
    }
    get avatarComponents() {
        var e;
        return JSON.parse(JSON.stringify(((e = this.xAvatar) == null ? void 0 : e.clothesList) || []))
    }
    get userId() {
        return this._userId
    }
    get removeWhenDisconnected() {
        return this.extraInfo && this.extraInfo.removeWhenDisconnected !== void 0 ? this.extraInfo.removeWhenDisconnected : !0
    }
    setConnectionStatus(e) {
        this.disconnected !== e && (this.disconnected = e,
        e ? this.emit("disconnected") : this.emit("reconnected"),
        log$1.warn(`avatar ${this.userId} status changed, disconnected:`, e))
    }
    setScale(e) {
        var t;
        (t = this.xAvatar) == null || t.setScale(e > 0 ? e : 1)
    }
    async playAnimation(e) {
        const {animationName: t, loop: r, extra: n} = e || {};
        if (this.isSelf) {
            if (this.isMoving)
                try {
                    await this.stopMoving()
                } catch (a) {
                    return log$1.error(`stopMoving error before playAnimation ${t}`, a),
                    Promise.reject(`stopMoving error before playAnimation ${t}`)
                }
            const o = {
                info: {
                    userId: this.userId,
                    animation: t,
                    loop: r,
                    extra: encodeURIComponent(n || "")
                },
                broadcastType: CoreBroadcastType.PlayAnimation
            };
            this._room.avatarManager.broadcast.broadcast({
                data: o
            })
        }
        return this.emit("animationStart", {
            animationName: t,
            extra: safeDecodeURIComponent(n || "")
        }),
        this._playAnimation(t, r).then(()=>{
            this.emit("animationEnd", {
                animationName: t,
                extra: safeDecodeURIComponent(n || "")
            })
        }
        )
    }
    async beforeChangeComponentsHook(e) {}
    turnTo(e) {
        if (this._room.viewMode === "observer") {
            this._room.sceneManager.cameraComponent.MainCamera.setTarget(ue4Position2Xverse(e.point));
            return
        }
        return this._room.actionsHandler.turnTo(e).then(()=>{
            this.emit("viewChanged", {
                extra: (e == null ? void 0 : e.extra) || ""
            })
        }
        )
    }
    async moveTo(e) {
        const {point: t, extra: r=""} = e || {};
        if (!this.position)
            return Promise.reject(new ParamError("avatar position is empty"));
        if (typeof r != "string" || typeof r == "string" && r.length > 64) {
            const a = "extra shoud be string which length less than 64";
            return log$1.warn(a),
            Promise.reject(new ParamError(a))
        }
        const o = getDistance(this.position, t) / 100 > 100 ? MotionType.Run : MotionType.Walk;
        return this._room.actionsHandler.moveTo({
            point: t,
            motionType: o,
            extra: r
        })
    }
    async stopMoving() {
        return this._room.actionsHandler.stopMoving()
    }
    rotateTo(e) {
        return this._room.actionsHandler.rotateTo(e)
    }
    setRayCast(e) {
        this.xAvatar && (this.xAvatar.isRayCastEnable = e)
    }
    say(e, t) {
        if (this.sayTimer && window.clearTimeout(this.sayTimer),
        !this.xAvatar) {
            log$1.error("say failed, without instance: xAvatar");
            return
        }
        this.xAvatar.say(e, {
            scale: this.xAvatar.scale,
            isUser: this.group === AvatarGroup.User
        }),
        !(t === void 0 || t <= 0) && (this.sayTimer = window.setTimeout(()=>{
            this.silent()
        }
        , t))
    }
    silent() {
        var e;
        if (!this.xAvatar) {
            log$1.error("silent failed, without instance: xAvatar");
            return
        }
        (e = this.xAvatar) == null || e.silent()
    }
    setMotionType({type: e=MotionType.Walk}) {
        return this.motionType === e ? Promise.resolve() : this._room.actionsHandler.setMotionType(e).then(()=>{
            this._motionType = e
        }
        )
    }
    setNickname(e) {
        return this._room.actionsHandler.setNickName(encodeURIComponent(e))
    }
    _setNickname(e) {
        var r, n;
        if (!e)
            return;
        const t = safeDecodeURIComponent(e);
        ((r = this.xAvatar) == null ? void 0 : r.nickName) !== t && (this.isSelf && (this._room.updateCurrentNetworkOptions({
            nickname: t
        }),
        this._room.options.nickname = t),
        (n = this.xAvatar) == null || n.setNickName(t, {
            scale: this.xAvatar.scale
        }))
    }
    _move(e) {
        var s;
        const {start: t, end: r, walkSpeed: n, moveAnimation: o="Walking", inter: a=[]} = e || {};
        return (s = this.xAvatar) == null ? void 0 : s.move(t, r, n, o, a)
    }
    setPickBoxScale(e=1) {
        return this.xAvatar ? (this.xAvatar.setPickBoxScale(e),
        !0) : (log$1.error("setPickBoxScale failed, without instance: xAvatar"),
        !1)
    }
    transfer(e) {
        const {player: t, camera: r, areaName: n, attitude: o, pathName: a} = e;
        return this._room.actionsHandler.transfer({
            renderType: RenderType.RotationVideo,
            player: t,
            camera: r,
            areaName: n,
            attitude: o,
            pathName: a,
            tag: "transfer"
        })
    }
    avatarLoadedHook() {}
    avatarStartMovingHook() {}
    avatarStopMovingHook() {}
    async statusSync(e) {
        var t, r, n;
        try {
            if ((t = e.event) != null && t.rotateEvent) {
                const {angle: o, speed: a} = e.event.rotateEvent
                  , s = this.motionType === MotionType.Run ? "Running" : "Walking";
                this.rotation && (this.rotation.yaw = this.rotation.yaw % 360,
                o.yaw - this.rotation.yaw > 180 && (o.yaw = 180 - o.yaw),
                this.isRotating = !0,
                await this.xAvatar.rotateTo(o, this.rotation, s).then(()=>{
                    this._playAnimation("Idle", !0),
                    this.isRotating = !1
                }
                ))
            }
            if (e.event && (((r = e.event) == null ? void 0 : r.points.length) || 0) > 1 && !this.isSelf) {
                this.isMoving = !0,
                e.playerState.attitude && (this._motionType = e.playerState.attitude);
                const o = this.motionType === MotionType.Run ? "Running" : "Walking"
                  , a = this._room.skin.routeList.find(l=>l.areaName === this._room.currentState.areaName)
                  , s = ((a == null ? void 0 : a.step) || 7.5) * 30 * (25 / 30);
                this.position && await this._move({
                    start: this.position,
                    end: e.event.points[e.event.points.length - 1],
                    walkSpeed: s,
                    moveAnimation: o,
                    inter: (n = e.event) == null ? void 0 : n.points.slice(0, -1)
                }).then(()=>{
                    this.isMoving = !1
                }
                )
            }
        } catch {
            return
        }
    }
}
var SyncEventType = (i=>(i[i.Reset = 0] = "Reset",
i[i.Appear = 1] = "Appear",
i[i.Disappear = 2] = "Disappear",
i[i.Move = 3] = "Move",
i[i.ChangeRenderInfo = 4] = "ChangeRenderInfo",
i[i.KeepAlive = 5] = "KeepAlive",
i[i.Rotate = 6] = "Rotate",
i[i.ET_RemoveVisitor = 7] = "ET_RemoveVisitor",
i))(SyncEventType || {})
  , GetStateTypes = (i=>(i[i.Default = 0] = "Default",
i[i.Event = 1] = "Event",
i))(GetStateTypes || {});
const log = new Logger("xverse-avatar-manager")
  , xe = class extends EventEmitter {
    constructor(e) {
        super();
        E(this, "xAvatarManager");
        E(this, "_room");
        E(this, "avatars", new Map);
        E(this, "syncAvatarsLength", 0);
        E(this, "broadcast");
        this._room = e,
        this._usersStatistics(),
        this.broadcast = this.setupBroadcast(),
        e.on("skinChanged", ()=>{
            this.avatars.forEach(t=>{
                t.disconnected && this.removeAvatar(t.userId, !0)
            }
            )
        }
        )
    }
    setupBroadcast() {
        return new Broadcast(this._room,async e=>{
            const {broadcastType: t, info: r} = e;
            if (t !== CoreBroadcastType.PlayAnimation)
                return;
            const {userId: n, animation: o, extra: a, loop: s=!1} = r
              , l = this.avatars.get(n);
            l && !l.isSelf && (l.emit("animationStart", {
                animationName: o,
                extra: decodeURIComponent(a)
            }),
            await (l == null ? void 0 : l._playAnimation(o, s)),
            l.emit("animationEnd", {
                animationName: o,
                extra: decodeURIComponent(a)
            }))
        }
        )
    }
    hideAll(e=!0) {
        this.xAvatarManager.hideAll(e)
    }
    showAll(e=!0) {
        this.xAvatarManager.showAll(e)
    }
    async init() {
        this.xAvatarManager = this._room.sceneManager.avatarComponent;
        try {
            const e = await this._room.modelManager.getApplicationConfig()
              , {avatars: t} = e;
            if (t) {
                await avatarLoader.parse(this._room.sceneManager, t);
                return
            }
            return Promise.reject("cannot find avatar config list")
        } catch (e) {
            return log.error(e),
            Promise.reject("avatar mananger init error!")
        }
    }
    async handleAvatar(e) {
        var r;
        if (this._room.viewMode === "simple" || !this._room.joined || !e.newUserStates)
            return;
        let t = e.newUserStates;
        if (((r = this._room._userAvatar) == null ? void 0 : r.isMoving) && this._room._userAvatar.motionType === MotionType.Run) {
            const n = t.filter(a=>a.userId === this._room.userId)
              , o = t.filter(a=>a.userId !== this._room.userId).slice(0, 2);
            t = n.concat(o)
        }
        if (e.getStateType === GetStateTypes.Event) {
            this.syncAvatarsLength = (t || []).length;
            const n = this._room.avatars.filter(s=>s.group == AvatarGroup.User);
            n.filter(s=>!(t != null && t.find(l=>l.userId == s.userId))).forEach(s=>{
                this.removeAvatar(s.userId)
            }
            );
            const a = t.filter(s=>!n.find(l=>l.userId == s.userId));
            this._handleAvatar(a)
        }
        this._handleAvatar(t)
    }
    async _handleAvatar(e) {
        e == null || e.forEach(t=>{
            var n, o, a, s, l, u, c, h, f;
            const r = this._room.userId === t.userId;
            if (((n = t.event) == null ? void 0 : n.type) === SyncEventType.ET_RemoveVisitor) {
                const d = (a = (o = t.event) == null ? void 0 : o.removeVisitorEvent) == null ? void 0 : a.removeVisitorEvent
                  , _ = JSON.parse(safeDecodeURIComponent(((l = (s = t.event) == null ? void 0 : s.removeVisitorEvent) == null ? void 0 : l.extraInfo) || ""))
                  , {code: g, msg: m} = _;
                d === RemoveVisitorType.RVT_ChangeToObserver ? this._room.audienceViewModeHook() : d === RemoveVisitorType.RVT_MoveOutOfTheRoom && this._room.leave(),
                this._room.emit("visitorStatusChanged", {
                    code: g,
                    msg: m
                })
            }
            if (t.event && [SyncEventType.Appear, SyncEventType.Reset].includes(t.event.type) || !t.event) {
                let d = this.avatars.get(t.userId);
                if (t.playerState.avatarId && (d == null ? void 0 : d.avatarId) !== t.playerState.avatarId && (d = void 0,
                this.removeAvatar(t.userId)),
                d) {
                    if (d.disconnected && d.setConnectionStatus(!1),
                    (u = t.event) != null && u.id && this._room.actionsHandler.confirmEvent(t.event.id),
                    t.playerState.nickName && (d == null || d._setNickname(t.playerState.nickName)),
                    t.playerState.avatarComponents && !d.isSelf && d.xAvatar) {
                        const _ = safeParseComponents(t.playerState.avatarComponents);
                        d._changeComponents({
                            avatarComponents: _,
                            mode: ChangeComponentsMode.Preview
                        })
                    }
                } else {
                    const {position: _, angle: g} = t.playerState.player
                      , m = t.playerState.avatarId
                      , v = t.playerState.prioritySync
                      , y = safelyJsonParse(t.playerState.extra);
                    if (!m)
                        return;
                    const b = safeParseComponents(t.playerState.avatarComponents)
                      , T = safeDecodeURIComponent(t.playerState.nickName)
                      , C = this.calculatePriority(t.userId, y);
                    this.addAvatar({
                        userId: t.userId,
                        isHost: t.playerState.isHost,
                        nickname: T,
                        avatarPosition: _,
                        avatarRotation: g,
                        avatarScale: t.playerState.avatarSize,
                        avatarId: m,
                        avatarComponents: t.playerState.person === Person.First ? [] : b,
                        priority: C,
                        group: AvatarGroup.User,
                        prioritySync: v,
                        extraInfo: y
                    }).then(()=>{
                        var A;
                        (A = t.event) != null && A.id && this._room.actionsHandler.confirmEvent(t.event.id),
                        this.updateAvatarPositionAndRotation(t),
                        r && (this.xAvatarManager.setMainAvatar(t.userId),
                        this._room.emit("userAvatarLoaded"),
                        log.info("userAvatarLoaded"))
                    }
                    ).catch(A=>{
                        r && (this.xAvatarManager.setMainAvatar(t.userId),
                        this._room.emit("userAvatarFailed", {
                            error: A
                        }),
                        log.error("userAvatarFailed", A))
                    }
                    )
                }
            }
            if (t.event && SyncEventType.Disappear === t.event.type && ((c = t == null ? void 0 : t.event) != null && c.id && this._room.actionsHandler.confirmEvent(t.event.id),
            this.removeAvatar(t.userId)),
            t.event && [SyncEventType.Move, SyncEventType.ChangeRenderInfo].includes(t.event.type) || !t.event) {
                (h = t == null ? void 0 : t.event) != null && h.id && this._room.actionsHandler.confirmEvent(t.event.id);
                const d = this.avatars.get(t.userId);
                d && d.withModel && !d.isLoading && this.updateAvatarPositionAndRotation(t)
            }
            if (!r && ((f = t.event) == null ? void 0 : f.type) === SyncEventType.Rotate) {
                const d = this.avatars.get(t.userId);
                d.statusSyncQueue.append({
                    type: QueueType.Rotate,
                    action: ()=>d.statusSync(t)
                })
            }
        }
        )
    }
    calculatePriority(e, t) {
        var n;
        return e === this._room.userId ? EAvatarRelationRank.Self : (n = this._room.options.firends) != null && n.includes(e) ? EAvatarRelationRank.Friend : EAvatarRelationRank.Stranger
    }
    updateAvatarPositionAndRotation(e) {
        var t, r;
        if ((t = e == null ? void 0 : e.playerState) != null && t.player) {
            let {position: n, angle: o} = e.playerState.player;
            const a = this.avatars.get(e.userId);
            if (!a)
                return;
            if (n = positionPrecisionProtect(n),
            o = rotationPrecisionProtect(o),
            a.isSelf && !this._room.networkController.rtcp.workers.inPanoMode && (a.setPosition(n),
            a.setRotation(o)),
            e.event && (((r = e.event) == null ? void 0 : r.points.length) || 0) > 1 && !a.isSelf && a.statusSyncQueue.append({
                type: QueueType.Move,
                action: ()=>a.statusSync(e)
            }),
            e.renderInfo && a.isSelf) {
                const {isMoving: s, isRotating: l} = e.renderInfo;
                this._updateAvatarMovingStatus({
                    id: e.userId,
                    isMoving: !!s,
                    isRotating: !!l
                })
            }
        }
    }
    async addAvatar(e) {
        const {userId: t, isHost: r, avatarPosition: n, avatarId: o, avatarRotation: a, nickname: s, avatarComponents: l=[], priority: u, group: c=AvatarGroup.Npc, avatarScale: h=DEFAULT_AVATAR_SCALE, extraInfo: f, prioritySync: d} = e
          , _ = t === this._room.userId;
        let g = this.avatars.get(t);
        if (g)
            return Promise.resolve(g);
        if (g = new xe.subAvatar({
            userId: t,
            isHost: r,
            isSelf: _,
            room: this._room,
            avatarComponents: l,
            avatarId: o,
            nickname: s,
            group: c
        }),
        this.avatars.set(t, g),
        !g.withModel)
            return g.isLoading = !1,
            g.avatarLoadedHook(),
            this._room.emit("avatarChanged", {
                avatars: this._room.avatars
            }),
            g;
        const v = (await this._room.modelManager.getAvatarModelList()).find(b=>b.id === o)
          , y = Date.now();
        if (!v)
            return this._room.emit("avatarChanged", {
                avatars: this._room.avatars
            }),
            this.avatars.delete(t),
            Promise.reject(`no such avatar model with id: ${o}`);
        try {
            let b = await avatarComponentsModify(v, l);
            b = b.filter(A=>A.type != "pendant");
            const T = await avatarComponentsParser(v, b)
              , C = await this.xAvatarManager.loadAvatar({
                id: t,
                avatarType: o,
                priority: u,
                avatarManager: this.xAvatarManager,
                assets: T,
                status: {
                    avatarPosition: n,
                    avatarRotation: a,
                    avatarScale: h
                }
            })._timeout(8e3, new TimeoutError$1("loadAvatar timeout(8s)"));
            return C.setPickBoxScale(t === this._room.userId ? 0 : 1),
            g.xAvatar = C,
            g.setScale(h),
            g.extraInfo = f,
            g.priority = u,
            g.isLoading = !1,
            g.prioritySync = !!d,
            g._playAnimation("Idle", !0, !0),
            g.avatarLoadedHook(),
            this._room.emit("avatarChanged", {
                avatars: this._room.avatars
            }),
            s && g._setNickname(s),
            t === this._room.userId && (log.infoAndReportMeasurement({
                metric: "avatarLoadDuration",
                startTime: y,
                group: "costs"
            }),
            log.infoAndReportMeasurement({
                metric: "avatarLoadAt",
                startTime: this._room._startTime,
                group: "costs"
            })),
            g
        } catch (b) {
            return g.isLoading = !1,
            this._room.emit("avatarChanged", {
                avatars: this._room.avatars
            }),
            log.error(b),
            Promise.reject(b)
        }
    }
    removeAvatar(e, t=!1) {
        const r = this.avatars.get(e);
        if (!!r) {
            if (r.removeWhenDisconnected || t) {
                r.xAvatar && this.xAvatarManager.deleteAvatar(r.xAvatar),
                this.avatars.delete(e),
                this._room.emit("avatarChanged", {
                    avatars: this._room.avatars
                });
                return
            }
            r.setConnectionStatus(!0)
        }
    }
    clearOtherUsers() {
        this.avatars.forEach(e=>{
            !e.isSelf && e.group === AvatarGroup.User && this.removeAvatar(e.userId)
        }
        )
    }
    async _updateAvatarMovingStatus(e) {
        const {id: t, isMoving: r, isRotating: n} = e
          , o = this.avatars.get(t);
        if (!!o) {
            if (o.isRotating !== n) {
                o.isRotating = n;
                let a = "Idle";
                n && (a = "Walking",
                o.motionType === MotionType.Run && (a = "Running")),
                o._playAnimation(a, !0, !0),
                log.infoAndReportMeasurement({
                    startTime: Date.now(),
                    value: 0,
                    metric: n ? "userAvatarStartRotating" : "userAvatarStopRotating",
                    extra: {
                        motionType: o.motionType,
                        moveToExtra: this._room.moveToExtra
                    }
                })
            }
            if (o.isMoving !== r) {
                o.isMoving = r;
                let a = "Idle";
                r && (a = "Walking",
                o.motionType === MotionType.Run && (a = "Running")),
                r ? (o.avatarStartMovingHook(),
                o.emit("startMoving", {
                    target: o,
                    extra: this._room.moveToExtra
                })) : (o.avatarStopMovingHook(),
                o.emit("stopMoving", {
                    target: o,
                    extra: this._room.moveToExtra
                })),
                o._playAnimation(a, !0, !0),
                log.infoAndReportMeasurement({
                    startTime: Date.now(),
                    value: 0,
                    metric: r ? "userAvatarStartMoving" : "userAvatarStopMoving",
                    extra: {
                        motionType: o.motionType,
                        moveToExtra: this._room.moveToExtra
                    }
                })
            }
        }
    }
    _usersStatistics() {
        this.on("userAvatarLoaded", ()=>{
            window.setInterval(()=>{
                const e = this._room.avatars.filter(r=>r.group === AvatarGroup.User).length || 0
                  , t = this._room.avatars.filter(r=>r.group === AvatarGroup.User && r.isRender).length || 0;
                this._room.stats.assign({
                    userNum: e,
                    syncUserNum: this.syncAvatarsLength,
                    renderedUserNum: t
                })
            }
            , 3e3)
        }
        )
    }
}
;
let XverseAvatarManager = xe;
E(XverseAvatarManager, "subAvatar", XverseAvatar);
new Logger("Wsutils");
function downloadFileByBase64(i, e) {
    const t = dataURLtoBlob(i)
      , r = URL.createObjectURL(t);
    downloadFile(r, e)
}
function dataURLtoBlob(i) {
    var a;
    const e = i.split(",")
      , t = (a = e[0].match(/:(.*?);/)) == null ? void 0 : a[1]
      , r = atob(e[1]);
    let n = r.length;
    const o = new Uint8Array(n);
    for (; n--; )
        o[n] = r.charCodeAt(n);
    return new Blob([o],{
        type: t
    })
}
function downloadFile(i, e="screenShot.png") {
    const t = document.createElement("a");
    t.setAttribute("href", i),
    t.setAttribute("download", e),
    t.setAttribute("target", "_blank");
    const r = document.createEvent("MouseEvents");
    r.initEvent("click", !0, !0),
    t.dispatchEvent(r)
}
const Pe = class {
    static _GetStorage() {
        try {
            return localStorage.setItem("test", ""),
            localStorage.removeItem("test"),
            localStorage
        } catch {
            const e = {};
            return {
                getItem: t=>{
                    const r = e[t];
                    return r === void 0 ? null : r
                }
                ,
                setItem: (t,r)=>{
                    e[t] = r
                }
            }
        }
    }
    static ReadString(e, t) {
        const r = this._Storage.getItem(e);
        return r !== null ? r : t
    }
    static WriteString(e, t) {
        this._Storage.setItem(e, t)
    }
    static ReadBoolean(e, t) {
        const r = this._Storage.getItem(e);
        return r !== null ? r === "true" : t
    }
    static WriteBoolean(e, t) {
        this._Storage.setItem(e, t ? "true" : "false")
    }
    static ReadNumber(e, t) {
        const r = this._Storage.getItem(e);
        return r !== null ? parseFloat(r) : t
    }
    static WriteNumber(e, t) {
        this._Storage.setItem(e, t.toString())
    }
}
;
let DataStorage = Pe;
E(DataStorage, "_Storage", Pe._GetStorage());
class JoyStick {
    constructor(e) {
        E(this, "_zone", document.createElement("div"));
        E(this, "_joystick", null);
        E(this, "_room");
        this._room = e
    }
    init(e) {
        const {interval: t=33, triggerDistance: r=25, style: n={
            left: 0,
            bottom: 0
        }} = e
          , o = (u,c)=>{
            this._room.actionsHandler.joystick({
                degree: Math.floor(u),
                level: Math.floor(c / 5)
            })
        }
          , a = this._zone;
        document.body.appendChild(a),
        a.style.position = "absolute",
        a.style.width = "200px",
        a.style.height = "200px",
        a.style.left = String(n.left),
        a.style.bottom = String(n.bottom),
        a.style.zIndex = "999",
        a.style.userSelect = "none",
        a.style.webkitUserSelect = "none",
        this._joystick = nipplejs.create({
            zone: a,
            mode: "static",
            position: {
                left: "50%",
                top: "50%"
            },
            color: "white"
        });
        let s, l;
        return this._joystick.on("move", (u,c)=>{
            s = c
        }
        ),
        this._joystick.on("start", ()=>{
            l = window.setInterval(()=>{
                s && s.distance > r && o && o(s.angle.degree, s.distance)
            }
            , t)
        }
        ),
        this._joystick.on("end", ()=>{
            l && window.clearInterval(l),
            l = void 0
        }
        ),
        this._joystick
    }
    show() {
        if (!this._joystick)
            throw new Error("joystick is not created");
        this._zone.style.display = "block"
    }
    hide() {
        if (!this._joystick)
            throw new Error("joystick is not created");
        this._zone.style.display = "none"
    }
}
var app = "";
function toast(i, e) {
    const {onClick: t, duration: r} = e || {};
    return window.Toastify({
        text: i,
        duration: r || 3e3,
        position: "center",
        onClick: function() {
            t && t()
        }
    }).showToast()
}
class XverseRoom extends XverseRoom$1 {
    constructor() {
        super(...arguments);
        E(this, "joyStick", new JoyStick(this))
    }
    afterJoinRoomHook() {
        this.joyStick.init({})
    }
}
class Xverse extends Xverse$1 {
    async joinRoom(e) {
        const t = e.pathName || "thirdwalk"
          , r = e.rotationRenderType || RenderType.RotationVideo
          , n = e.person || Person.Third
          , o = new XverseRoom(le(oe({}, e), {
            appId: e.appId || this.appId,
            releaseId: e.releaseId || this.releaseId,
            pageSession: this.pageSession,
            isAllSync: !0,
            rotationRenderType: r,
            syncByEvent: !0,
            pathName: t,
            person: n,
            role: e.role || "audience"
        }));
        return o.initRoom().then(()=>o)
    }
}
var loadingImage = "./assets/loading.f375926b.png";
const jsx = jsxRuntime.exports.jsx
  , jsxs = jsxRuntime.exports.jsxs
  , urlParam = new window.URLSearchParams(location.search)
  , appId = urlParam.get("appId") || void 0
  , releaseId = urlParam.get("releaseId") || void 0;
appId || alert("AppId \u4E0D\u80FD\u4E3A\u7A7A");
const xverse = new Xverse({
    env: "DEV",
    appId,
    releaseId
});
let room;
function App() {
    const [i,e] = react.exports.useState(!0)
      , [t,r] = react.exports.useState(!0)
      , [n,o] = react.exports.useState("high")
      , [a,s] = react.exports.useState("");
    react.exports.useEffect(()=>{
        l()
    }
    , []);
    const l = async()=>{
        var R;
        const f = document.querySelector("#canvas")
          , d = urlParam.get("roomId") || "e629ef3e-022d-4e64-8654-703bb96410eb"
          , _ = urlParam.get("userId") || Math.random().toString(16).slice(2)
          , g = urlParam.get("avatarId") || void 0
          , m = urlParam.get("appId") || void 0
          , v = urlParam.get("skinId") || void 0
          , y = urlParam.get("pathName") || void 0
          , b = urlParam.get("objectFit") || void 0
          , T = {
            width: parseInt(urlParam.get("width") || "1920"),
            height: parseInt(urlParam.get("height") || "1080")
        }
          , C = urlParam.get("ws") ? decodeURIComponent(urlParam.get("ws")) : "wss://uat-eks.xverse.cn/ws"
          , A = !!urlParam.get("debug")
          , S = !!urlParam.get("preload")
          , P = "full";
        if (Logger.setLevel(A ? LoggerLevels.Debug : LoggerLevels.Warn),
        S)
            try {
                await ((R = xverse.preload) == null ? void 0 : R.start(P, (M,x)=>{
                    const I = `(${M}/${x})`;
                    s(I)
                }
                ))
            } catch (M) {
                if (console.error(M),
                M.code === Codes.PreloadCanceled) {
                    toast("\u9884\u52A0\u8F7D\u88AB\u53D6\u6D88");
                    return
                }
                toast("\u8FDB\u5165\u5931\u8D25, \u8BF7\u91CD\u8BD5");
                return
            }
        try {
            room = await xverse.joinRoom({
                canvas: f,
                skinId: v,
                avatarId: g,
                roomId: d,
                userId: _,
                wsServerUrl: C,
                appId: m,
                token: " ",
                nickname: _,
                firends: ["user1"],
                viewMode: "full",
                resolution: T,
                pathName: y,
                objectFit: b,
                hasAvatar: !0,
                syncToOthers: !0
            }),
            u(),
            c(),
            window.room = room,
            e(!1)
        } catch (M) {
            console.error(M),
            alert(M);
            return
        }
    }
      , u = ()=>{
        room.on("_coreClick", ({point: f})=>{
            room._userAvatar.moveTo({
                point: f
            })
        }
        )
    }
      , c = ()=>{
        room.on("repeatLogin", function() {
            toast("\u8BE5\u7528\u6237\u5DF2\u7ECF\u5728\u5176\u4ED6\u5730\u70B9\u767B\u5F55", {
                duration: 1e4
            })
        }),
        room.on("reconnecting", function({count: f}) {
            toast(`\u5C1D\u8BD5\u7B2C${f}\u6B21\u91CD\u8FDE`)
        }),
        room.on("reconnected", function() {
            toast("\u91CD\u8FDE\u6210\u529F")
        }),
        room.on("disconnected", function() {
            const f = toast("\u8FDE\u63A5\u5931\u8D25\uFF0C\u624B\u52A8\u70B9\u51FB\u91CD\u8BD5", {
                duration: 1e5,
                onClick() {
                    f.hideToast(),
                    room.reconnect()
                }
            })
        })
    }
    ;
    return jsxs("div", {
        className: "App",
        children: [jsx("canvas", {
            id: "canvas",
            className: "stream unselect"
        }), !i && (()=>jsxs("div", {
            className: "debug_control_btns",
            children: [jsx("button", {
                onClick: ()=>{
                    var y, b;
                    (y = room.stats) != null && y.isShow ? room.stats.hide() : (b = room.stats) == null || b.show()
                }
                ,
                children: "Toggle Stats"
            }), jsx("button", {
                onClick: ()=>{
                    room.debug.toggleSceneshading(),
                    r(room.debug.isSceneShading)
                }
                ,
                children: t ? "\u53D6\u6D88\u4F4E\u6A21\u7740\u8272" : "\u4F4E\u6A21\u7740\u8272"
            }), jsxs("button", {
                onClick: ()=>{
                    let y = "average";
                    n === "high" ? y = "average" : n === "average" ? y = "low" : n === "low" ? y = "high" : y = "average",
                    o(y),
                    room.setPictureQualityLevel(y)
                }
                ,
                children: ["\u753B\u8D28\uFF1A", n === "high" ? "\u9AD8" : n === "low" ? "\u4F4E" : "\u4E2D"]
            }), jsx("button", {
                onClick: ()=>{
                    room.debug.toggleNearbyBreathPoint()
                }
                ,
                className: "font-size-small",
                children: "Toggle\u5468\u8FB9\u547C\u5438\u70B9"
            }), jsx("button", {
                onClick: ()=>{
                    room.debug.toggleTapBreathPoint()
                }
                ,
                className: "font-size-small",
                children: "Toggle\u70B9\u51FB\u547C\u5438\u70B9"
            }), jsx("button", {
                onClick: ()=>{
                    try {
                        room.debug.dumpStream(()=>{
                            toast("\u5F55\u5236\u5B8C\u6210")
                        }
                        ),
                        toast("\u5F00\u59CB\u5F55\u5236")
                    } catch {
                        toast("\u7801\u6D41\u5F55\u5236\u4E2D\uFF0C\u8BF7\u7A0D\u7B49")
                    }
                }
                ,
                className: "font-size-small",
                children: "\u5F55\u5236\u7801\u6D41\uFF0810s\uFF09"
            })]
        }))(), i && jsxs("div", {
            className: "loading",
            id: "loading",
            children: [jsx("img", {
                src: loadingImage,
                alt: ""
            }), jsxs("div", {
                children: ["\u5373\u5C06\u8FDB\u5165\u573A\u666F ", a]
            })]
        })]
    })
}
ReactDOM.render(jsx(React.StrictMode, {
    children: jsx(App, {})
}), document.getElementById("root"));
